<template>
    <view class="accept page-common">
        <div class="card">
            <div class="card-header">
                <span class="title">任务信息</span>
            </div>
            <uni-forms :model="taskInfo" label-width="170rpx" :border="true">
                <uni-forms-item label="单位：" name="unitName">
                    <span style="height: 100%;display: flex;align-items: center;">{{ taskInfo.unitName }}</span>
                </uni-forms-item>
               <uni-forms-item label="工程：" name="proName">
                    <span style="height: 100%;display: flex;align-items: center;">{{ taskInfo.proName }}</span>
                </uni-forms-item>
                <uni-forms-item label="单号：" name="code">
                    <span style="height: 100%;display: flex;align-items: center;">{{ taskInfo.code }}</span>
                </uni-forms-item>
                <uni-forms-item label="人员：" name="backPerson">
                    <span style="height: 100%;display: flex;align-items: center;">{{ taskInfo.backPerson }}</span>
                </uni-forms-item>
                <uni-forms-item label="电话：" name="phone">
                    <span style="height: 100%;display: flex;align-items: center;">{{ taskInfo.phone }}</span>
                </uni-forms-item>
            </uni-forms>
        </div>
        <div class="card">
            <div class="card-header">
                <span class="title">退料物资</span>
                <div class="header-right">
                    <span class="tip">已选 {{ typeList.length }} 项</span>
                </div>
            </div>
            <div class="select-area">
                <uni-row :gutter="24" style="display: flex; align-items: center">
                    <uni-col :span="10">
                        <view>
                            <uni-data-select v-model="typeId" 
                                placeholder="请选择物资类型"
                                :localdata="maTypeSelectList" @change="getMaCode">
                            </uni-data-select>
                        </view>
                    </uni-col>
                    <uni-col :span="10">
                        <view>
                            <uni-data-select v-model="typeCode" 
                                placeholder="请选择规格型号"
                                :localdata="maCodeSelectList" @change="selectMaCode">
                            </uni-data-select>
                        </view>
                    </uni-col>
                </uni-row>
            </div>
            <div class="table-area">
                <uni-table border stripe emptyText="暂无更多数据">
                    <!-- 表头行 -->
                    <uni-tr>
                        <uni-th width="240rpx" align="center">类型名称</uni-th>
                        <uni-th width="240rpx" align="center">规格型号</uni-th>
                        <uni-th width="160rpx" align="center">在用数</uni-th>
                        <uni-th width="160rpx" align="center">退料数</uni-th>
                        <uni-th width="160rpx" align="center">外观</uni-th>
                        <uni-th width="120rpx" align="center">操作</uni-th>
                    </uni-tr>
                    <!-- 表格数据行 -->
                    <uni-tr v-for="(item,index) in typeList" :key="item.id">
                        <uni-td>{{item.materialName}}</uni-td>
                        <uni-td>{{item.typeName}}</uni-td>
                        <uni-td>{{item.num}}</uni-td>
                        <uni-td> 
                            <uni-easyinput 
                                placeholder="退料数" 
                                v-model="item.preNum" 
                                type="number" 
                                :clearable="false" 
                                @input="onChangeNumber(item)"
                                styles="width: 100rpx"
                            />
                        </uni-td>
                        <uni-td> 
                            <uni-easyinput 
                                placeholder="外观" 
                                v-model="item.apDetection"
                                styles="width: 100rpx"
                            />
                        </uni-td>
                        <uni-td>
                            <view class="uni-group">
                                <view class="action-btn" @click="uploadImg(item)">
                                    <uni-icons type="camera" size="20" style="color: #3784fb;"/>
                                </view>
                                <view class="action-btn delete" @click="delRow(index)">
                                    <uni-icons type="trash-filled" size="20" style="color: red;margin-left:10px;"/>
                                </view>
                            </view>
                        </uni-td>
                    </uni-tr>
                </uni-table>
            </div>
        </div>

        <div class="footer-btn">
            <button class="btn-cont" @click="submitNum">确认</button>
        </div>
    </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'  
import { getUseType,insertApp } from '../../services/back.js';
const taskInfo = ref({})    

const maTypeSelectList = ref([])
const typeId = ref("")//类型
const maCodeSelectList = ref([])
const typeCode = ref("")//规格型号
const typeList = ref([])    
//类下拉选
const getMaType = () => { 
    let obj = {
        "agreementId":taskInfo.value.agreementId,
	} 
	getUseType(obj).then(res => { 
        console.log(res)
		maTypeSelectList.value = res.data.map(option => {
            return {
                value:option.typeId,
                text:option.typeName,
            }
        }); 
	}).catch(error => {
		console.log(error) 
	})  
} 
//规格
const getMaCode = () => { 
    let obj = {
        "agreementId":taskInfo.value.agreementId,
        "typeId":typeId.value
	} 
	getUseType(obj).then(res => { 
        console.log(res)
		maCodeSelectList.value = res.data.map(option => {
            let obj = {
                ...option,
                bmFileInfos:[],
                value:option.typeId,
                text:option.typeName, 
            }
            return obj
        }); 
	}).catch(error => {
		console.log(error) 
	})  
}
//选择规格型号
const selectMaCode = (e) => { 
    console.log(e)
    maCodeSelectList.value.forEach(item=>{
        console.log(item)
        if(item.typeId==e){
            typeList.value.push(item)
        }
    })
    console.log(typeList.value)
} 
//提交
const submitNum = () => {
    console.log(taskInfo.value)
    console.log(typeList.value)
    let obj = {
        "backApplyInfo":taskInfo.value,
        "backApplyDetailsList":typeList.value
    }
    insertApp(obj).then(res => { 
        console.log(res)
        if(res.code==200){
			uni.showToast({ title: '编辑成功', icon: 'none' })
			uni.navigateBack({
				delta: 1 // 返回到已存在的页面
			});
		}else{
			uni.showToast({ title: res.msg, icon: 'none' })
		}
	}).catch(error => {
		console.log(error) 
	})  
} 
//上传
const uploadImg = (item) => {
    uni.chooseImage({
    count: 1, //图片可选择数量
    sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
    sourceType: ['album', 'camera',], //album 从相册选图，camera 使用相机，默认二者都有。
    success: res => {
        console.log(res)
        let imgFiles = res.tempFilePaths //图片的本地文件路径列表
		// imgBeseUrl.value = imgFiles[0]
        // console.log('本地地址', imgFiles)
        // console.log('请求地址', baseURL+"/file/upload") 
		uni.uploadFile({
			// url: baseURL+"/file/upload",//app
			url: "/file/upload",//h5
			filePath: imgFiles[0],
			name: 'file', 
			success: (res) => {
				res = JSON.parse(res.data)
				console.log('上传成功', res.code);
				console.log('上传成功', res.data);
				if(res.code&&res.code==200){
					let obj = {
						"name":res.data.name,
						"url":res.data.url
					}
					item.bmFileInfos.value = [obj]
					uni.showToast({ title: '上传成功', icon: 'none' })
				}else{
					item.bmFileInfos.value = []
					uni.showToast({ title: '上传失败', icon: 'none' })
				}
			},
			fail: (err) => {
			  console.error('上传失败', err);
			}
		});
        // this.$refs.vForm.clearValidate()
    }
	})
}
//删除
const delRow = (index) => {
    console.log(index)
    console.log(typeList.value)
    typeList.value.splice(index,1)
}
// 数量框change事件
const onChangeNumber = (item) => {
    console.log(item)
    console.log(item.preNum)
    console.log(item.preNum)
    let maxNum = Number(item.num)
    // outboundNum.value
    setTimeout(()=>{ 
        if(item.unitValue==1){ 
            item.preNum = Number(String(item.preNum).replace(/[^\d.]/g,'')) 
        }else{ 
            item.preNum = Number(String(item.preNum).replace(/[^\d]/g,''))  
        } 
        if (Number(item.preNum)<= 0) { 
            item.preNum = 0; 
        }
        if (Number(item.preNum) > maxNum) {
            uni.showToast({
                title: '已达到当前资最大在用数量！',
                icon: 'none',
            }) 
            item.preNum = maxNum; 
        }
    },500) 
}

onLoad((options)=>{
	console.log(options)
	taskInfo.value = JSON.parse(options.taskInfo)
    console.log(taskInfo.value)
    getMaType()
})
</script>

<style lang="scss">
.accept {
    padding: 24rpx;
    height: 95vh;
    word-break: break-all;
    background-color: #f7f8fa;
    display: flex;
    flex-direction: column;

    // 卡片样式
    .card {
        padding: 32rpx;
        background-color: #fff;
        border-radius: 20rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
        margin-bottom: 24rpx;

        // 卡片头部
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24rpx;

            .title {
                font-size: 32rpx;
                font-weight: 600;
                color: #262626;
                position: relative;
                padding-left: 24rpx;

                &::before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 6rpx;
                    height: 28rpx;
                    background: #3784fb;
                    border-radius: 6rpx;
                }
            }

            .header-right {
                .tip {
                    font-size: 26rpx;
                    color: #8c8c8c;
                }
            }
        }

        // 选择区域
        .select-area {
            padding: 24rpx 0;
            border-bottom: 2rpx solid #f5f5f5;
        }

        // 表格区域
        .table-area {
            margin-top: 24rpx;
            margin: 24rpx -32rpx 0;
            overflow-x: auto;

            :deep(.uni-table) {
                width: 1080rpx;
                padding: 0 32rpx;
                .uni-table-tr {
                    .uni-table-th {
                        min-width: 140rpx;
                        &:last-child {
                            min-width: 120rpx;
                        }
                    }

                    .uni-table-td {
                        .action-btn {
                            display: inline-flex;
                            padding: 12rpx;
                            border-radius: 8rpx;
                            transition: all 0.3s ease;
                            margin: 0 8rpx;

                            &:active {
                                background-color: rgba(0, 0, 0, 0.05);
                            }

                            &.delete:active {
                                background-color: rgba(255, 77, 79, 0.05);
                            }
                        }
                    }
                }
            }
        }
    }

    // 底部按钮
    .footer-btn {
        margin-top: auto;
        padding: 32rpx;
        background: #fff;
        box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);

        .btn-cont {
            width: 100%;
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            background: linear-gradient(135deg, #4b8eff 0%, #3784fb 100%);
            color: #fff;
            border-radius: 44rpx;
            font-size: 32rpx;
            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);
            }
        }
    }
}
</style>
