<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index'" :isBack="true" bgColor="bg-gradual-blue" >
            <block slot="content">领用申请</block>
        </cu-custom>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag">
            <u-form-item label="领用编号" borderBottom prop="collectNo">
                <u--input placeholder='自动生成'  v-model="inputForm.collectNo" disabled></u--input>
            </u-form-item>
            <u-form-item label="经办人" borderBottom prop="handledBy">
                <u--input placeholder=''  v-model="inputForm.handledBy" disabled></u--input>
            </u-form-item>
            <u-form-item label="经办人部门" borderBottom prop="handledByOfficeName">
                <u--input placeholder=''  v-model="inputForm.handledByOfficeName" disabled></u--input>
            </u-form-item>
            <u-form-item label="领用时间" borderBottom prop="collectDate" :required="true">
                <el-date-picker
                        v-model="inputForm.collectDate"
                        type="date"
                        placeholder="请选择领用时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注信息' :rows="5" :maxlength="500" v-model="inputForm.remarks" ></u--textarea>
            </u-form-item>


            <el-row  :gutter="15" :key="index_experience" v-for="(item,index_experience) in this.inputForm.detailInfos">
                <el-col :span="24">
                    <u-form-item label="" >
                        <el-divider content-position="left"> 领用详情 {{index_experience + 1}}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="领用人" :prop="'detailInfos[' + index_experience + '].recipientAgent'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].recipientAgent" placeholder="请选择领用人" @focus="openUserPullForm(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用人部门" :prop="'detailInfos[' + index_experience + '].recipientOffice'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].recipientOffice" placeholder="" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用类型" :prop="'detailInfos[' + index_experience + '].collectType'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].collectType" placeholder="请选择领用类型" @focus="showPicker(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="物品名称" :prop="'detailInfos[' + index_experience + '].goodsName'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].goodsName" placeholder="请选择物品名称" @focus="showGoods(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用数量" :prop="'detailInfos[' + index_experience + '].collectNumber'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].collectNumber" placeholder="请选择领用数量" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="库存数量" :prop="'detailInfos[' + index_experience + '].surplusNumber'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].surplusNumber" :disabled="true" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="单位" :prop="'detailInfos[' + index_experience + '].company'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].company"  placeholder="请输入单位" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="备注" :prop="'detailInfos[' + index_experience + '].remarks'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].remarks"  placeholder="请输入备注" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="文件上传">
                        <el-upload
                                class="upload-demo"
                                :action="`http://localhost:2800/api/public-modules-server/oss/file/webUpload/upload`"
                                :on-remove="(file, fileList) => handleRemove(file, fileList, index_experience,'detail')"
                                :file-list="inputForm.detailInfos[index_experience].fileInfoLost"
                                :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,index_experience,'detail')"
                                :limit="3">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                            <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file,index_experience,'detail') || testFlag">
                                <span @click="handleFileClick(file)">{{ file.name }}</span>
                                <el-button type="text" icon="el-icon-close" @click="handleDelete(file,index_experience,'detail')">✕</el-button>
                            </template>
                        </el-upload>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="" >
                        <el-button style="width: 100%" type="danger" @click="removeRow(index_experience)" plain>删除领用详情 {{index_experience + 1}}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" >
                <el-button style="width: 100%" type="primary" @click="addRow()" plain>新增领用详情</el-button>
            </u-form-item>

            <u-form-item label="附件">
                <el-upload
                        class="upload-demo"
                        :action="`http://localhost:2800/api/public-modules-server/oss/file/webUpload/upload`"
                        :on-remove="(file, fileList) => handleRemove(file, fileList, '','')"
                        :file-list="inputForm.files"
                        :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,'','')"
                        :limit="3">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file) || testFlag">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" icon="el-icon-close" @click="handleDelete(file)">✕</el-button>
                    </template>
                </el-upload>
            </u-form-item>
        </u--form>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-else-if="nodeFlag">
            <u-form-item label="领用编号" borderBottom prop="collectNo">
                <u--input placeholder='自动生成'  v-model="inputForm.collectNo" :disabled="true"></u--input>
            </u-form-item>
            <u-form-item label="经办人" borderBottom prop="handledBy">
                <u--input placeholder=''  v-model="inputForm.handledBy" :disabled="true"></u--input>
            </u-form-item>
            <u-form-item label="经办人部门" borderBottom prop="handledByOfficeName">
                <u--input placeholder=''  v-model="inputForm.handledByOfficeName" :disabled="true"></u--input>
            </u-form-item>
            <u-form-item label="领用时间" borderBottom prop="collectDate" :required="true">
                <el-date-picker
                        :disabled="true"
                        v-model="inputForm.collectDate"
                        type="date"
                        placeholder="请选择领用时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注信息' :rows="5" :maxlength="500" v-model="inputForm.remarks" :disabled="true"></u--textarea>
            </u-form-item>


            <el-row  :gutter="15" :key="index_experience" v-for="(item,index_experience) in this.inputForm.detailInfos" >
                <el-col :span="24">
                    <u-form-item label="" >
                        <el-divider content-position="left"> 领用详情 {{index_experience + 1}}</el-divider>
                    </u-form-item>
                </el-col>

                <el-col :span="24">
                    <u-form-item label="领用人" :prop="'detailInfos[' + index_experience + '].recipientAgent'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].recipientAgent" :disabled="true" placeholder="请选择领用人" @focus="openUserPullForm(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用人部门" :prop="'detailInfos[' + index_experience + '].recipientOffice'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].recipientOffice" :disabled="true" placeholder="" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用类型" :prop="'detailInfos[' + index_experience + '].collectType'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].collectType" :disabled="true" placeholder="请选择领用类型" @focus="showPicker(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="物品名称" :prop="'detailInfos[' + index_experience + '].goodsName'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].goodsName" :disabled="true" placeholder="请选择物品名称" @focus="showGoods(index_experience)" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="领用数量" :prop="'detailInfos[' + index_experience + '].collectNumber'" :required="true"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].collectNumber" :disabled="true" placeholder="请选择领用数量" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="库存数量" :prop="'detailInfos[' + index_experience + '].surplusNumber'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].surplusNumber" :disabled="true" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="单位" :prop="'detailInfos[' + index_experience + '].company'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].company" :disabled="true" placeholder="请输入单位" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="备注" :prop="'detailInfos[' + index_experience + '].remarks'"
                                 :rules="[
				     ]">
                        <el-input v-model="inputForm.detailInfos[index_experience].remarks" :disabled="true" placeholder="请输入备注" clearable></el-input>
                    </u-form-item>
                    <u-form-item label="文件上传">
                        <el-upload
                                class="upload-demo"
                                :action="`http://localhost:2800/api/public-modules-server/oss/file/webUpload/upload`"
                                :on-remove="(file, fileList) => handleRemove(file, fileList, index_experience,'detail')"
                                :file-list="inputForm.detailInfos[index_experience].fileInfoLost"
                                :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,index_experience,'detail')"
                                :limit="3">
                            <el-button size="small" :disabled="true" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                            <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file,index_experience,'detail') || testFlag">
                                <span @click="handleFileClick(file)">{{ file.name }}</span>
                                <el-button type="text" icon="el-icon-close" @click="handleDelete(file,index_experience,'detail')">✕</el-button>
                            </template>
                        </el-upload>
                    </u-form-item>
                </el-col>

                <el-col :span="24" style="text-align: center">
                    <u-form-item label="" >
                        <el-button style="width: 100%" type="danger" @click="removeRow(index_experience)" disabled plain>删除领用详情 {{index_experience + 1}}</el-button>
                    </u-form-item>
                </el-col>
            </el-row>
            <u-form-item label="" >
                <el-button style="width: 100%" type="primary" @click="addRow()" disabled plain>新增领用详情</el-button>
            </u-form-item>

            <u-form-item label="附件">
                <el-upload
                        style="width: 20%;"
                        class="upload-demo"
                        :action="`http://localhost:2800/api/public-modules-server/oss/file/webUpload/upload`"
                        :on-remove="(file, fileList) => handleRemove(file, fileList, '','')"
                        :file-list="inputForm.files"
                        :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,'','')"
                        :limit="3">
                    <el-button size="small" :disabled="true" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
                    <template slot="file" slot-scope="{ file }" v-if="shouldShowFile(file) || testFlag">
                        <span @click="handleFileClick(file)">{{ file.name }}</span>
                        <el-button type="text" icon="el-icon-close" @click="handleDelete(file)">✕</el-button>
                    </template>
                </el-upload>
            </u-form-item>
        </u--form>
        <ba-tree-picker ref="treePicker" :multiple='false' @select-change="selectChange" title="类型选择"
                        :localdata="listData" valueKey="value" textKey="label" childrenKey="children" />
        <goods-info-picker ref="goodsPicker" :multiple='false' @select-goods-change="selectGoodsChange" title="物品名称"
                        :localdata="goodsListData" valueKey="value" textKey="label" childrenKey="children" />
    </view>
</template>

<script>
    import OSSService from "@/api/sys/OSSService"
    import goodsInfoPicker from './GoodsInfoPicker'
    import MaterialTypeService from '@/api/materialManagement/MaterialTypeService'
    import WareHouseService from '@/api/materialManagement/WareHouseService'
    import collectService from '@/api/materialManagement/CollectService'
    import CommonApi from '@/api/common/CommonApi'
    import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
    import {mapState, mapMutations, mapActions} from 'vuex'
    import registerService from '@/api/human/register/RegisterService'
    export default {
        components: {
            baTreePicker,
            goodsInfoPicker
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                showFileList: [], // 控制每个文件是否显示的数组
                showFileList2: [], // 控制每个文件是否显示的数组
                testFlag: false,
                nodeFlag: false,
                loading: false,
                listData: [],
                fileList3: [],
                goodsListData: [],
                materialList: [],
                searchForm: {
                    wareHouseType: '',
                },
                inputForm: {
                    collectNo: '',
                    handledBy: '',
                    handledById: '',
                    handledByOffice: '',
                    handledByOfficeName: '',
                    remarks: '',
                    detailInfos: [],
                    files: [], // 附件信息
                    procInsId: ''
                },
                rules: {
                    'collectDate': [
                        {
                            required: true,
                            message: '领用时间不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                }
            }
        },
        ossService: null,
        materialTypeService: null,
        wareHouseService: null,
        commonApi: null,
        // 页面加载时执行
        created() {
            this.ossService = new OSSService()
            this.commonApi = new CommonApi()
            this.materialTypeService = new MaterialTypeService()
            this.wareHouseService = new WareHouseService()
            this.materialTypeService.cgList().then((data)=>{
                this.materialList = data
            }).catch((e)=>{
                throw e
            })

            this.inputForm.handledBy = this.userInfo.name
            this.inputForm.handledById = this.userInfo.id
            this.inputForm.handledByOffice = this.userInfo.officeDTO.id
            this.inputForm.handledByOfficeName = this.userInfo.officeDTO.name

            // 监听事件
            uni.$on('eventName', (data) => {
                // 在这里处理传递过来的数据
                //循环遍历领用详情，估计index将用户id与用户名称放入到领用人里面
                this.inputForm.detailInfos.forEach((detail,index) => {
                    if (index === parseInt(data.index)) {
                        detail.recipientAgent = data.name
                        detail.recipientAgentId = data.id
                        detail.recipientOffice = data.officeDTO.name
                    }
                })
            });
        },
        props: {
            businessId: {
                type: String,
                default: ''
            },
            formReadOnly: {
                type: Boolean,
                default: false
            },
            status: {
                type: String,
                default: ''
            }
        },
        watch: {
            'businessId': {
                handler (newVal) {
                    if (this.businessId) {
                        this.init(this.businessId)
                    } else {
                        this.$nextTick(() => {
                            // this.$refs.inputForm.reset()
                        })
                    }
                },
                immediate: true,
                deep: false
            }
        },
        methods: {
            // 显示选择器
            showPicker(index) {
                this.$refs.treePicker._show(index);
            },
            showGoods(index) {

                if (this.isEmpty(this.inputForm.detailInfos[index].collectTypeId)) {
                    uni.showToast({
                        title: '请先选择领用类型',
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    this.searchForm.wareHouseType = this.inputForm.detailInfos[index].collectTypeId
                    this.wareHouseService.wareHouseSummaryList({
                        'current': 0,
                        'size': -1,
                        'orders': [],
                        ...this.searchForm
                    }).then((data) => {
                        this.goodsListData = data.records
                    })

                    this.$refs.goodsPicker._show(index);
                }
            },
            //监听选择
            selectChange(ids, names, index) {
                // this.inputForm.detailInfos.forEach((detail,inde) => {
                //     if (inde === parseInt(index)) {
                //         detail.collectType = names
                //         detail.collectTypeId = ids[0]
                //     }
                // })
                this.$set(this.inputForm.detailInfos, index, {
                    ...this.inputForm.detailInfos[index],
                    collectType: names,
                    collectTypeId: ids[0]
                });

            },
            //监听选择
            selectGoodsChange(ids, names, index,tradeNumber) {
                // this.inputForm.detailInfos.forEach((detail,inde) => {
                //     if (inde === parseInt(index)) {
                //         detail.goodsName = names
                //         detail.tradeNumber = tradeNumber
                //     }
                // })
                this.$set(this.inputForm.detailInfos, index, {
                    ...this.inputForm.detailInfos[index],
                    goodsName: names,
                    surplusNumber: tradeNumber
                });
            },
            init (id) {
                this.nodeFlag = true
                this.inputForm.id = id
                if (id) {
                    collectService.findById(id).then((data) => {

                        // 只有从我发起的还有已办事项抄送给我 进入流程页面的时候才会有这个值
                        if (this.status === 'testSee') {
                            this.nodeFlag = true
                        } else {
                            this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
                                if (this.isNotEmpty(data)) {
                                    if (data === '重新发起申请' || this.isEmpty(data)) {
                                        this.nodeFlag = false
                                    } else {
                                        this.nodeFlag = true
                                    }
                                }
                            })
                        }

                        this.inputForm = this.recover(this.inputForm, data)
                        this.inputForm.collectDate = new Date(data.collectDate);

                        if (this.inputForm.files) {
                            this.inputForm.files.forEach( (item,index) => {
                                this.$set(this.showFileList, index, true);
                            })
                        }

                        console.log('this.inputForm.detailInfos', this.inputForm.detailInfos)
                        if (this.isNotEmpty(this.inputForm.detailInfos)){
                            this.inputForm.detailInfos.forEach( (item,index) => {
                                if (this.isNotEmpty(item.fileInfoLost)) {
                                    this.fileList3[index] = []
                                    item.fileInfoLost.forEach( (item,index2) => {
                                        this.fileList3[index].push(item)
                                        this.$set(this.showFileList2, index2, true);
                                    })

                                }

                            })
                        }

                    })
                }
            },
            buildTree(nodes, parentId = '0') {
                const tree = [];
                for (const node of nodes) {
                    if (node.parentId === parentId) {
                        const children = this.buildTree(nodes, node.id);
                        if (children.length) {
                            node.children = children;
                        }
                        tree.push(node);
                    }
                }
                return tree;
            },
            formatDate(date) {
                const dateNew = new Date(date); // 将日期字符串转换为 Date 对象
                const year = dateNew.getFullYear();
                const month = (dateNew.getMonth() + 1).toString().padStart(2, '0');
                const day = dateNew.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${day}`;
            },
            isEmpty(value) {
                let result = false;
                if (value == null || value == undefined) {
                    result = true;
                }
                if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
                    result = true;
                }
                if (typeof value == "object" && value instanceof Array && value.length === 0) {
                    result = true;
                }
                return result;
            },
            isNotEmpty (value) {
                return !this.isEmpty(value)
            },
            /**
             * 判断是否为空
             */
            isNull(val) {
                if (val instanceof Array) {
                    if (val.length === 0) return true;
                } else if (val instanceof Object) {
                    if (JSON.stringify(val) === "{}") return true;
                } else {
                    if (
                        val === "null" ||
                        val == null ||
                        val === "undefined" ||
                        val === undefined ||
                        val === ""
                    )
                        return true;
                    return false;
                }
                return false;
            },
            addRow() {
                // 点击新增按钮时，向表格中添加一行空数据
                this.inputForm.detailInfos.push({ recipientAgent: this.userInfo.name,
                    recipientAgentId: this.userInfo.id, recipientOffice: this.userInfo.officeDTO.name });
                let valueData = this.materialList;
                // 将扁平数据转换为树形结构
                const result = this.buildTree(valueData);
                this.listData = result

            },
            removeRow(index) {
                // 点击删除按钮时，从表格中移除指定行
                // this.tableData.splice(index, 1);
                this.inputForm.detailInfos.splice(index, 1);
            },
            formatDateNew(date) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            // 领用人下拉弹窗
            openUserPullForm(index) {
                // 点击 "领用人" 输入框时打开userPullForm页面，传入index用于区分不同的行
                uni.navigateTo({
                    url: '/pages/materialManagement/collect/UserPullForm?index=' + index // userPullForm页面的路径
                });
            },
            handleUploadSuccess (res, file, fileList, index, type) {
                console.log('fileListSuccess', fileList)

                // 将 fileList 转换为你期望的格式
                const formattedFiles = fileList.map(fileItem => {
                    return {
                        name: fileItem.name,
                        size: fileItem.size,
                        url: fileItem.response ? '/' + fileItem.response.url : fileItem.url,
                        lsUrl: fileItem.response ? fileItem.response.lsUrl : fileItem.lsUrl, // 如果没有 lsUrl，可以根据需要设置为空字符串或其他默认值
                        createBy: this.userInfo,
                        by: this.userInfo.id,
                        createTime: this.formatDateNew(new Date())
                    };
                });
                if (type === 'detail') {
                    // 将格式化后的数据设置到 detailInfos 的 fileInfoLost 属性中
                    this.inputForm.detailInfos[index].fileInfoLost = formattedFiles;
                    fileList.forEach((item, i) => {
                        if (item === file) {
                            this.$set(this.showFileList2, i, true);
                        }
                    });
                } else {
                    this.inputForm.files = formattedFiles
                    fileList.forEach((item, index) => {
                        if (item === file) {
                            this.$set(this.showFileList, index, true);
                        }
                    });
                }

                // 强制更新视图
                this.$forceUpdate();
            },
            handleRemove(file, fileList, index, type) {
                console.log('fileList', fileList)
                // 处理移除文件逻辑
                // file 是移除的文件
                // fileList 是当前文件列表
                const formattedFiles = fileList.map(fileItem => {
                    return {
                        name: fileItem.name,
                        size: fileItem.size,
                        url: '/' + fileItem.response.url,
                        createBy: this.userInfo,
                        by: this.userInfo.id,
                        createTime: this.formatDateNew(new Date())
                    };
                });
                if (type === 'detail') {

                    this.inputForm.detailInfos[index].fileInfoLost = formattedFiles;
                } else {
                    this.inputForm.files = formattedFiles
                }


                // 如果你想要更新文件列表，可以在这里更新 inputForm.fileInfoLost
                // this.inputForm.fileInfoLost = fileList;
            },
            saveForm(callback) {
                return new Promise((resolve, reject) => {
                    // 表单规则验证
                    // ...

                    let errors = [];

                    if (this.isNotEmpty(this.inputForm.collectDate)) {
                        this.inputForm.collectDate = this.formatDate(this.inputForm.collectDate);
                    }

                    if (this.isEmpty(this.inputForm.detailInfos)) {
                        errors.push('至少填写一条领用详情信息');
                    } else {
                        let i = this.inputForm.detailInfos.length;
                        for (let j = 0; j < i; j++) {
                            let k = j + 1;
                            if (this.isEmpty(this.inputForm.detailInfos[j].recipientAgent)) {
                                errors.push('领用详情第' + k + '行请选择领用人');
                            } else if (this.isEmpty(this.inputForm.detailInfos[j].collectType)) {
                                errors.push('领用详情第' + k + '行请选择领用类型');
                            } else if (this.isEmpty(this.inputForm.detailInfos[j].goodsName)) {
                                errors.push('领用详情第' + k + '行请选择物品名称');
                            } else if (this.isEmpty(this.inputForm.detailInfos[j].collectNumber)) {
                                errors.push('领用详情第' + k + '行请输入领用数量');
                            }
                        }
                    }

                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        reject('Form validation failed');
                    } else {
                        // 所有验证通过，执行保存操作
                        this.$refs.inputForm.validate().then(() => {
                            uni.showLoading();
                            this.inputForm.status = '2';
                            collectService.save(this.inputForm).then(data => {
                                callback(data.businessTable, data.businessId);
                                resolve('Form saved successfully');
                            }).catch(error => {
                                reject('Save operation failed');
                            });
                        }).catch(() => {
                            reject('Form validation failed');
                        });
                    }
                });
            },

            // 修改状态
            async updateStatusById (type, callback) {
                if (type === 'reject' || type === 'reback') {
                    collectService.findById(this.inputForm.id).then((data) => {
                        if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
                            this.loading = false
                            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                            throw new Error()
                        } else {
                            if (type === 'reject') {
                                // 驳回
                                this.inputForm.status = '4'
                            }
                            if (type === 'reback') {
                                // 撤回
                                this.inputForm.status = '3'
                            }
                            if (type === 'reject' || type === 'reback') {
                                let param = {status: this.inputForm.status, id: this.inputForm.id}
                                collectService.updateStatusById(param).then(() => {
                                    this.loading = false
                                    callback()
                                })
                            }
                        }
                    })
                } else if (type === 'hold') {
                    collectService.findById(this.inputForm.id).then((data) => {
                        if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
                            this.loading = false
                            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                            throw new Error()
                        } else {
                            // 终止
                            let param = {status: '1', id: this.inputForm.id}
                            collectService.updateStatusById(param).then(() => {
                                this.loading = false
                                callback()
                            })
                        }
                    })
                }
            },
            reapplyForm (callback) {
                this.loading = true
                collectService.findById(this.inputForm.id).then((data) => {
                    if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
                        this.loading = false
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                    } else {
                        this.startFormTrue(callback)
                    }
                })
            },
            // 送审
            async startFormTrue (callback) {
                if (this.isNotEmpty(this.inputForm.collectDate)) {
                    this.inputForm.collectDate = this.formatDate(this.inputForm.collectDate);
                }
                this.$refs.inputForm.validate().then(res => {
                    this.inputForm.status = '2'
                    collectService.save(this.inputForm).then((data) => {
                        this.inputForm.id = data.businessId
                        callback(data.businessTable, data.businessId, this.inputForm)
                        this.$refs.inputForm.resetFields()
                        this.loading = false
                    }).catch(() => {
                        this.$refs.inputForm.resetFields()
                    }).catch((e) => {

                    })
                })
            },
            // 通过
            async agreeForm (callback) {
                if (this.isNotEmpty(this.inputForm.collectDate)) {
                    this.inputForm.collectDate = this.formatDate(this.inputForm.collectDate);
                }
                console.log('this.inputForm', this.inputForm)
                this.$refs.inputForm.validate().then(res => {
                    this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
                        if (this.isNotEmpty(data)) {
                            if (data === '仓库管理员审核') {
                                this.inputForm.status = '5'
                            }
                        }
                        collectService.save(this.inputForm).then((data) => {
                            callback(data.businessTable, data.businessId, this.inputForm)
                            this.$refs.inputForm.resetFields()
                            this.loading = false
                        }).catch(() => {
                            this.loading = false
                            this.$refs.inputForm.resetFields()
                        })
                    })
                })
            },
            shouldShowFile(file,index,type) {
                if (type === 'detail') {
                    if (this.inputForm.detailInfos[index].fileInfoLost && this.inputForm.detailInfos[index].fileInfoLost.length > 0) {
                        // 返回一个布尔值，确定是否显示上传成功后的文件

                        return this.showFileList2[this.inputForm.detailInfos[index].fileInfoLost.indexOf(file)];
                    }

                }else {
                    if (this.inputForm.files && this.inputForm.files.length > 0) {
                        // 返回一个布尔值，确定是否显示上传成功后的文件
                        return this.showFileList[this.inputForm.files.indexOf(file)];
                    }
                }
                return false; // 默认返回 false 或者其他适当的
            },
            async handleFileClick(file) {
                await this.ossService.getTemporaryUrl(file.url).then((data) => {
                    file.lsUrl = data
                })
                console.log('file', file)
                if (this.isImage(file.name)) {
                    // 如果是图片文件，则执行放大显示图片的逻辑
                    this.handleImageClick(file);
                } else {
                    // window.open(file.lsUrl, '_blank')
                    window.location.href = file.lsUrl
                    // 如果不是图片文件，则执行其他操作，比如下载文件等
                }
            },
            handleImageClick(file) {
                // 在点击图片时执行放大显示的逻辑
                this.$alert(`<img src="${file.lsUrl}" style="max-width: 100%; max-height: 100%;" />`, '图片详情', {
                    dangerouslyUseHTMLString: true,
                    customClass: 'custom-alert'
                });
            },
            // 判断文件是否是图片类型
            isImage(fileName) {
                const ext = fileName.toLowerCase().split('.').pop(); // 获取文件的后缀名
                return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext); // 判断后缀名是否是图片类型
            },
            handleDelete(file,lineIndex,type) {
                // 处理删除文件的逻辑
                if (type === 'detail') {
                    const index = this.inputForm.detailInfos[lineIndex].fileInfoLost.indexOf(file);
                    if (index !== -1) {
                        this.inputForm.detailInfos[lineIndex].fileInfoLost.splice(index, 1);
                        this.showFileList2.splice(index, 1); // 从showFileList中移除对应的元素
                    }
                } else {
                    // 从文件列表中移除文件
                    const index = this.inputForm.files.indexOf(file);
                    if (index !== -1) {
                        this.inputForm.files.splice(index, 1);
                        this.showFileList.splice(index, 1); // 从showFileList中移除对应的元素
                    }
                }

            },
        }
    }
</script>

<style>
    .cu-form-group .title {
        min-width: calc(4em + 40px);
    }

    /* 样式示例，您可能需要根据实际情况调整 */
    .upload-demo {
        width: 40%;
    }
</style>
