<template>
    <!-- 领料出库详情 -->
    <view class="page-container">
        <uni-row :gutter="24" class="search-form">
            <uni-col :span="18">
                <view>
                    <uni-easyinput placeholder="请输入内容" v-model="keyWord" maxlength="10"/>
                </view>
            </uni-col>
            <uni-col :span="6">
                <view class="search" @click="search">查询</view>
            </uni-col>
        </uni-row>

        <scroll-view scroll-y class="scroll-container">
            <view
                v-for="(item, index) in detailsList"
                :key="index"
                class="table-list-item"
            >
                <uni-swipe-action class="swipe-action">
                    <uni-swipe-action-item :right-options="item.preNum == item.alNum ? options2 : item.alNum ==0 ? options3 : options" 
					@click="onClick($event, item)">
                        <div class="title">
                            <span class="main-title">领料出库</span>
                            <div class="status-tag">
                                <uni-tag :text="item.preNum == item.alNum ? '已完成' : '未完成'" 
                                    :type="item.preNum == item.alNum ? 'success' : 'warning'"
                                    :custom-style="item.preNum == item.alNum ? successStyle : warningStyle"
                                />
                            </div>
                        </div>
                        <view class="line"></view>
                        <uni-row :gutter="24">
                            <uni-col :span="6">物资名称：</uni-col>
                            <uni-col :span="16">
                                <view class="cont">{{ item.maTypeName }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">规格型号：</uni-col>
                            <uni-col :span="16">
                                <view class="cont">{{ item.typeName }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">预领数量：</uni-col>
                            <uni-col :span="16">
                                <view class="cont" style="font-size: 20px">{{ item.preNum }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">已领数量：</uni-col>
                            <uni-col :span="16">
                                <view class="cont" style="font-size: 20px">{{ item.alNum }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">待领数量：</uni-col>
                            <uni-col :span="16">
                                <view class="cont" style="font-size: 20px">{{ formatDiff(item.preNum, item.alNum) }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">单位：</uni-col>
                            <uni-col :span="16">
                                <view class="cont">{{ item.unitName }}</view>
                            </uni-col>
                        </uni-row>
                        <uni-row :gutter="24">
                            <uni-col :span="6">管理模式：</uni-col>
                            <uni-col :span="16">
                                <view class="cont">
                                    <uni-tag
                                        text="编码"
                                        type="warning"
                                        v-if="item.manageType === 0"
                                        :custom-style="codeStyle"
                                    />
                                    <uni-tag
                                        text="数量"
                                        type="success"
                                        v-if="item.manageType === 1"
                                        :custom-style="numStyle"
                                    />
                                </view>
                            </uni-col>
                        </uni-row>
                    </uni-swipe-action-item>
                </uni-swipe-action>
            </view>
        </scroll-view>
    </view>
    <PopupConfirm ref="popupConfirm" :content="content" />
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { getOutboundDetailsAPI,getOutboundDetailsAPITwo,leaseOutBackApi,backOutDetailsApi } from '@/services/picking/outbound.js'
import { onLoad, onShow } from '@dcloudio/uni-app' 
import { formatDiff } from '@/utils/bnsBase.js'
import PopupConfirm from '@/components/PopupConfirm'
const taskStatus = ref(3)//进行中
const detailsList = ref([]) 
const keyWord = ref('')
const popupConfirm = ref()
const content = ref('')
const search = () => {
    console.log('🚀 ~ search ~ keyWord:', keyWord.value) 
	getOutboundDetailsData()
}
// 领料单位，参数等信息
const leaseApplyInfo = ref({
    leaseUnitId: '', //       领料单位
    leaseUnit: '', //       领料单位
    leaseProjectId: '', //    领料工程
    leaseProject: '', //    领料工程
    maTypeName: '', //      物资类型
    typeName: '', //        规格型号
    unitName: '', //        单位
    storageNum: '', //      库存数量
    preNum: '', //          预领数量
    parentId: '', //  出库时所需参数 取列表 id
    id: '', //              出库时所需参数 取详情接口 id
    typeId: '', //          出库时所需参数 取详情接口 typeId 
    manageType: '', //      出库时所需参数 取详情接口 manageType
    publishTask: '', //      出库时所需参数 取详情接口 publishTask
    oldTypeId: '',
})

onLoad((options) => {
    leaseApplyInfo.value.parentId = options.id
    if(options.publishTask == "null"){
        leaseApplyInfo.value.publishTask = ""
        console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
    }else{
        leaseApplyInfo.value.publishTask = options.publishTask
    }
    // leaseApplyInfo.value.publishTask = options.publishTask
    console.log('🚀 ~ onLoad ~ options:', options)
    // getOutboundDetailsData()
}) 
onShow(() => {
    getOutboundDetailsData()
})
// 获取列表详情
const getOutboundDetailsData = async () => {
    console.log('Full leaseApplyInfo:', leaseApplyInfo.value);
    console.log('parentId:', leaseApplyInfo.value.parentId);
    console.log('keyWord:', keyWord.value);
    console.log('publishTask:', leaseApplyInfo.value.publishTask);
    console.log('publishTask type:', typeof leaseApplyInfo.value.publishTask);

    try {
        uni.showLoading({
            title: '加载中...',
            mask: true
        })
        let res;
        if (leaseApplyInfo.value.publishTask === null || leaseApplyInfo.value.publishTask == "" || leaseApplyInfo.value.publishTask == 'null') {
            console.log("Condition: publishTask is null or empty string");
            // 如果 publishTask 为空，则只传递两个参数
            console.log("yyyyyyyyyyyyyyyyyyyy");
            leaseApplyInfo.value.publishTask = ''
            const { data } = await getOutboundDetailsAPI(
                leaseApplyInfo.value.parentId,
                keyWord.value,
                leaseApplyInfo.value.publishTask
            );
            res = data;
            console.log('🚀 ~ getOutboundDetailsData ~ res:', res);
        } else {
            console.log("Condition: publishTask is not null and not empty string");
            // 如果 publishTask 不为空，则传递三个参数
            const { data } = await getOutboundDetailsAPITwo(
                leaseApplyInfo.value.parentId,
                keyWord.value,
                leaseApplyInfo.value.publishTask
            );
            res = data;
            console.log("xxxxxxxxxxx", res);
        }
        
        detailsList.value = res.leaseApplyDetailsList;
        leaseApplyInfo.value.taskId = res.leaseApplyInfo.taskId; 
        leaseApplyInfo.value.typeId = res.leaseApplyInfo.typeId; 
        leaseApplyInfo.value.leaseUnitId = res.leaseApplyInfo.leaseUnitId;
        leaseApplyInfo.value.leaseUnit = res.leaseApplyInfo.leaseUnit;
        leaseApplyInfo.value.leaseProjectId = res.leaseApplyInfo.leaseProjectId;
        leaseApplyInfo.value.leaseProject = res.leaseApplyInfo.leaseProject;
        leaseApplyInfo.value.code = res.leaseApplyInfo.code
        taskStatus.value = res.leaseApplyInfo.taskStatus;
        if(taskStatus.value==3){
            options.value = [
                { 	text: '出库',style: {backgroundColor: '#84c649',color: '#fff',fontSize: '28rpx'}	},
                // {	text: '退回',style: {backgroundColor: '#ed6042',color: '#fff',fontSize: '28rpx'}	},
                {   text: '查看',style: {backgroundColor: '#3784fb',color: '#fff',fontSize: '28rpx'}	},
                {   text: '退回',style: {backgroundColor: '#ed6042',color: '#fff',fontSize: '28rpx'}	}
            ];
            options2.value = [
                // {	text: '退回',style: {backgroundColor: '#ed6042',color: '#fff',fontSize: '28rpx'}},
                {   text: '查看',style: {backgroundColor: '#3784fb',color: '#fff',fontSize: '28rpx'}},
                {   text: '退回',style: {backgroundColor: '#ed6042',color: '#fff',fontSize: '28rpx'}}
            ]
        }else if(taskStatus.value==4){
            options.value = [
                { 	text: '出库',style: {backgroundColor: '#84c649',color: '#fff',fontSize: '28rpx'}	}, 
                {   text: '查看',style: {backgroundColor: '#3784fb',color: '#fff',fontSize: '28rpx'}	}
            ];
            options2.value = [ 
                {   text: '查看',style: {backgroundColor: '#3784fb',color: '#fff',fontSize: '28rpx'}}
            ]
        }
    } catch (error) {
        console.log('🚀 ~ getOutboundDetailsData ~ error:', error)
    } finally {
        uni.hideLoading()
    }
}

// 数量退回
const leaseOutBack = async (item) => {
	console.log(item)
	if(item.alNum==0){
		uni.showToast({
		    title: '暂无物资可退！',
		    icon: 'none',
		})
	}else{
		if(item.manageType==0){//编码
        console.log('编码xxxxxxxxx', item)
			// const { status,manageType,maTypeName,typeName,storageNum,preNum,alNum,unitName,id,typeId, unitValue} = item
			// leaseApplyInfo.value.maTypeName = maTypeName
			// leaseApplyInfo.value.typeName = typeName
			// leaseApplyInfo.value.unitName = unitName
			// leaseApplyInfo.value.storageNum = storageNum
			// leaseApplyInfo.value.preNum = preNum
			// leaseApplyInfo.value.alNum = alNum
			// leaseApplyInfo.value.id = id
			// leaseApplyInfo.value.typeId = typeId 
			// leaseApplyInfo.value.manageType = manageType
			// leaseApplyInfo.value.unitValue = unitValue 
            leaseApplyInfo.value = item
			console.log(leaseApplyInfo.value)
			let codingUrl = '/pages/picking/outbound/inner-detail' 
			// 把 leaseApplyInfo 领料信息转成 json 传递到下个页面
			uni.navigateTo({ url: `${codingUrl}?queryParams=${JSON.stringify(leaseApplyInfo.value)}&isBack=1` })
		}else{
			let param = {
				outNum:item.alNum,
				taskId:leaseApplyInfo.value.taskId,
				typeId:item.typeId,
				parentId:item.parentId,
                publishTask:leaseApplyInfo.value.publishTask
			}
			console.log("yyyyyyyyyyyyyyyyyyyyyyyy",param)
			uni.showModal({
				title: '退回',
				content: `是否确定退回该类型的出库?`,
				confirmText: '确定',
				cancelText: '取消',
				success: async (res) => {
				  if (res.confirm) {
					const res = await leaseOutBackApi(param)
					console.log(res)
					if(res.code==200){
						uni.showToast({
						    title: '退回成功！',
						    icon: 'none',
						})
						getOutboundDetailsData()
					} 
				  } 
				}
			})
		}
	}
	
}
// 状态标签样式
const successStyle = {
    color: '#52c41a',
    backgroundColor: 'rgba(82, 196, 26, 0.1)',
    border: '2rpx solid rgba(82, 196, 26, 0.2)',
    fontWeight: '600'
}

const warningStyle = {
    color: '#fa8c16',
    backgroundColor: 'rgba(250, 140, 22, 0.1)',
    border: '2rpx solid rgba(250, 140, 22, 0.2)',
    fontWeight: '600'
}

// 管理方式标签样式
const codeStyle = {
    color: '#ff9800',
    backgroundColor: 'rgba(255, 152, 0, 0.1)',
    border: '2rpx solid rgba(255, 152, 0, 0.2)',
    padding: '4rpx 16rpx',
    fontSize: '26rpx',
    fontWeight: '600'
}

const numStyle = {
    color: '#13c2c2',
    backgroundColor: 'rgba(19, 194, 194, 0.1)',
    border: '2rpx solid rgba(19, 194, 194, 0.2)',
    padding: '4rpx 16rpx',
    fontSize: '26rpx',
    fontWeight: '600'
}

// 右滑按钮组
const options = ref([
    {
        text: '出库',
        style: {
            backgroundColor: '#84c649',
            // color: '#fff',
            fontSize: '28rpx',
        },
    },
	{
	    text: '查看',
	    style: {
	        backgroundColor: '#3784fb',
	        // color: '#fff',
	        fontSize: '28rpx',
	    },
	},
    {
        text: '退回',
        style: {
            backgroundColor: '#ed6042',
            // color: '#fff',
            fontSize: '28rpx',
        },
	}
]) 
const options2 = ref([
    {
        text: '查看',
        style: {
            backgroundColor: '#3784fb',
            // color: '#fff',
            fontSize: '28rpx',
        },
    },
])

const options3 = ref([
    {
        text: '出库',
        style: {
            backgroundColor: '#84c649',
            // color: '#fff',
            fontSize: '28rpx',
        },
    },
	{
	    text: '查看',
	    style: {
	        backgroundColor: '#3784fb',
	        // color: '#fff',
	        fontSize: '28rpx',
	    },
	}
]) 

// 点击滑动按钮
 const onClick = async (e, item) => {
    console.log("tttttttttt",e,item)
	if(taskStatus.value==3){//出库进行中
    console.log("333333333333333333333333333")
		if (e.content.text == '出库') {
			if (item.status == 2) {//已完成
				leaseOutBack(item)
			}else{
				console.log("rrrrrrrrrrrrr",30)
				onCodingItem(item)//出库  
			}
		}
		if (e.content.text == '查看') {
			checkViewDetail(item)//查看
		}
        if (e.content.text == '退回') {
            content.value = `是否确定退回?`
            popupConfirm.value.openPopup().then(async confirm => {
                if (!confirm.data) return
                try {
                    uni.showLoading({ title: '操作中...', mask: true })
                    let param ={
                        taskId:leaseApplyInfo.value.taskId,
                        typeId:item.typeId,
                        parentId:item.parentId,
                        newTypeId:item.newTypeId,
                        alNum:item.alNum,
                        outNum:item.alNum,
                        maCodeVoList:item.maCodeVoList
                    }
                    const res = await  backOutDetailsApi(param)//退回
                    if(res.code==200){
                        uni.showToast({
                            title: '退回成功！',
                            icon: 'none',
                        })
                        setTimeout(() => {
                            getOutboundDetailsData()
                        }, 500)
        
                    }else{
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                        })
                    }
                } catch (error) {
                    console.log('🚀 ~ onClick ~ error:', error)
                } finally {
                    uni.hideLoading()
                }
            })
		}
	}
	if(taskStatus.value==4){//出库已完成
		checkViewDetail(item)//查看 
	}  
	// onCodingItem(item)//出库  
	// checkViewDetail(item)//查看 
	// onCodingItem(item)//出库  
}
// 点击跳转出库页面
const onCodingItem = (item) => { 
    console.log("uuuuuuuuuuuuuuu",item)
    // 解构所需要的数据
    const {
        status,
        manageType,
        maTypeName,
        typeName,
        storageNum,
        preNum,
        alNum,
        unitName,
        id,
        typeId, 
        unitValue,
        oldTypeId,
    } = item
    leaseApplyInfo.value.maTypeName = maTypeName
    leaseApplyInfo.value.typeName = typeName
    leaseApplyInfo.value.unitName = unitName
    leaseApplyInfo.value.storageNum = storageNum
    leaseApplyInfo.value.preNum = preNum
    leaseApplyInfo.value.alNum = alNum
    leaseApplyInfo.value.id = id
    leaseApplyInfo.value.typeId = typeId
    leaseApplyInfo.value.manageType = manageType
    leaseApplyInfo.value.unitValue = unitValue
    leaseApplyInfo.value.oldTypeId = oldTypeId
	console.log(leaseApplyInfo.value)
    let codingUrl = ''
    if (manageType === 0) {
        codingUrl = '/pages/picking/outbound/code-outbound' // 编码出库
    }
    if (manageType == 1) {
        codingUrl = '/pages/picking/outbound/num-outbound' // 数量出库
    } 
    // 把 leaseApplyInfo 领料信息转成 json 传递到下个页面
    uni.navigateTo({ url: `${codingUrl}?queryParams=${JSON.stringify(leaseApplyInfo.value)}` })
}

const checkViewDetail = (item) => {
	// 解构所需要的数据
	const {
	    status,
	    manageType,
	    maTypeName,
	    typeName,
	    storageNum,
	    preNum,
	    alNum,
	    unitName,
	    id,
	    typeId, 
	    unitValue,
        publishTask,
	} = item
	leaseApplyInfo.value.maTypeName = maTypeName
	leaseApplyInfo.value.typeName = typeName
	leaseApplyInfo.value.unitName = unitName
	leaseApplyInfo.value.storageNum = storageNum
	leaseApplyInfo.value.preNum = preNum
	leaseApplyInfo.value.alNum = alNum
	leaseApplyInfo.value.id = id
	leaseApplyInfo.value.typeId = typeId 
	leaseApplyInfo.value.manageType = manageType
	leaseApplyInfo.value.unitValue = unitValue
    leaseApplyInfo.value.publishTask = publishTask 
	console.log(leaseApplyInfo.value)
	let codingUrl = '/pages/picking/outbound/inner-detail' 
	// 把 leaseApplyInfo 领料信息转成 json 传递到下个页面
	uni.navigateTo({ url: `${codingUrl}?queryParams=${JSON.stringify(leaseApplyInfo.value)}&isBack=0` })
}
</script>

<style lang="scss" scoped>
.page-container {
    display: flex;
    height: 100%;
    flex-direction: column;
    background-color: #f7f8fa;
    padding: 24rpx;

    // 搜索表单
    .search-form {
        display: flex;
        align-items: center;
        background: #fff;
        padding: 14rpx 24rpx;
        border-radius: 20rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

        :deep(.uni-easyinput__content) {
            background-color: #f7f8fa;
            border: 2rpx solid #e8e8e8;
            border-radius: 12rpx;
            height: 75rpx;
            padding: 0 24rpx;
            transition: all 0.3s ease;

            &:focus-within {
                border-color: #3784fb;
                box-shadow: 0 0 0 2rpx rgba(55, 132, 251, 0.1);
            }

            .uni-easyinput__content-input {
                font-size: 28rpx;
                color: #262626;
                height: 75rpx;
                line-height: 75rpx;
            }
        }

        // 搜索按钮
        .search {
            height: 60rpx;
            background: linear-gradient(135deg, #4b8eff 0%, #3784fb 100%);
            text-align: center;
            line-height: 60rpx;
            color: #fff;
            border-radius: 12rpx;
            font-size: 28rpx;
            font-weight: 600;
            box-shadow: 0 6rpx 20rpx rgba(55, 132, 251, 0.2);
            transition: all 0.3s ease;

            &:active {
                transform: scale(0.98);
                opacity: 0.9;
                box-shadow: 0 2rpx 8rpx rgba(55, 132, 251, 0.2);
            }
        }
    }

    // 列表项样式
    .table-list-item {
        background: #fff;
        border-radius: 20rpx;
        padding: 24rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        transition: all 0.3s ease;

        &:active {
            transform: scale(0.99);
            opacity: 0.9;
        }

        // 标题栏
        .title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24rpx;

            .main-title {
                font-size: 32rpx;
                font-weight: 600;
                color: #262626;
            }

            // 状态标签
            .status-tag {
                :deep(.uni-tag) {
                    padding: 8rpx 24rpx;
                    border-radius: 8rpx;
                    font-size: 24rpx;
                    font-weight: 500;
                    border: none;

                    &[type="warning"] {
                        color: #fa8c16;
                        background: rgba(250, 140, 22, 0.1);
                    }

                    &[type="success"] {
                        color: #52c41a;
                        background: rgba(82, 196, 26, 0.1);
                    }
                }
            }
        }

        // 分隔线
        .line {
            height: 2rpx;
            background: linear-gradient(90deg, 
                rgba(232, 232, 232, 0) 0%,
                rgba(232, 232, 232, 1) 50%,
                rgba(232, 232, 232, 0) 100%
            );
            margin: 24rpx 0;
        }

        // 内容行
        .uni-row {
            /* margin-bottom: 20rpx; */
            font-size: 28rpx;

            .uni-col-6 {
                color: #8c8c8c;
            }

            .cont {
                color: #262626;
                text-align: right;
            }
        }
    }
}

// 加载提示文字
.loading-text {
    text-align: center;
    font-size: 26rpx;
    color: #8c8c8c;
    padding: 32rpx 0;
    letter-spacing: 1rpx;
}


// 优化滑动区域样式
:deep(.uni-swipe_action) {
    border-radius: 20rpx;
    overflow: hidden;
    
    .uni-swipe_content {
        margin: 0 !important;
        padding: 0;
        background-color: #fff;
    }
    
    .uni-swipe_button-group {
        height: 100%;
        
        .uni-swipe_button {
            height: 100%;
            padding: 0 20rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28rpx;
            font-weight: 600;
            color: #fff;
            border: none;
            writing-mode: vertical-rl;
            
            // 查看按钮
            &:nth-child(1) {
                background: linear-gradient(to bottom, #3ad980, #34C759) !important;
            }
            
            // 出库按钮
            &:nth-child(2) {
                background: linear-gradient(to bottom, #3b95ff, #007AFF) !important;
            }

            &:active {
                opacity: 0.85;
            }
        }
    }
}
</style>
