<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="purchaseNo">
                <u--input placeholder='自动生成'  v-model="inputForm.purchaseNo" disabled></u--input>
            </u-form-item>
            <u-form-item label="采购名称" borderBottom prop="purchaseSketch" :required="true">
                <u--input placeholder='请填写采购名称'  v-model="inputForm.purchaseSketch" ></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="purchaseDate" :required="true">
                <el-date-picker
                        v-model="inputForm.purchaseDate"
                        type="date"
                        placeholder="请选择采购申请时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="采购方式" borderBottom prop="purchaseMode" :required="true">
                <jp-picker placeholder='请选择采购方式' v-model="inputForm.purchaseMode" rangeKey="label" rangeValue="value" :range="[
						        { label: '办公室采购', value: '1' },
						        { label: '自行采购', value: '2' },
						    ]"></jp-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 + '].purchaserAgent'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].purchaserAgent" placeholder="请选择采购人" @focus="openUserPullForm(index_experience)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="采购人部门" :prop="'detailInfos[' + index_experience + '].procurementOffice'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].procurementOffice" placeholder="" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="采购类型" :prop="'detailInfos[' + index_experience + '].procurementType'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].procurementType" placeholder="请选择采购类型" @focus="showPicker(index_experience)" clearable></u--input>
                    </u-form-item>
                    <my-dropdown :index_experience="index_experience" :inputForm="inputForm"></my-dropdown>
                    <!--<u-form-item label="商品名称" :prop="'detailInfos[' + index_experience + '].tradeName'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].tradeName" placeholder="请选择物品名称" clearable></u--input>
                    </u-form-item>-->

                    <supplier-selector :index_experience="index_experience" :inputForm="inputForm"></supplier-selector>
<!--                    <u-form-item label="供应商" :prop="'detailInfos[' + index_experience + '].supplierName'" -->
<!--                                 :rules="[-->
<!--				     ]">-->
<!--                        <u--input v-model="inputForm.detailInfos[index_experience].supplierName" placeholder="请选择供应商" @focus="showGoods(index_experience)" clearable></u--input>-->
<!--                    </u-form-item>-->
                    <u-form-item label="商品单价(元)" :prop="'detailInfos[' + index_experience + '].tradePrice'"
                                 :rules="[
				     ]">
                        <u--input @blur="onInputCode(index_experience, $event,'tradePrice')" v-model="inputForm.detailInfos[index_experience].tradePrice" placeholder="请输入商品单价(元)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="商品数量" :prop="'detailInfos[' + index_experience + '].tradeNumber'"
                                 :rules="[
				     ]">
                        <u--input @blur="onInputCode(index_experience, $event,'tradeNumber')" v-model="inputForm.detailInfos[index_experience].tradeNumber" placeholder="请输入商品数量" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="商品总价" :prop="'detailInfos[' + index_experience + '].priceSum'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].priceSum" placeholder="请输入商品总价" :readonly="true" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="单位" :prop="'detailInfos[' + index_experience + '].company'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].company"  placeholder="请输入单位" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="备注" :prop="'detailInfos[' + index_experience + '].remarks'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].remarks"  placeholder="请输入备注" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="文件上传">
                        <el-upload
                                class="upload-demo"
                                :action="`http://pv4uct.natappfree.cc/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://pv4uct.natappfree.cc/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="purchaseNo">
                <u--input placeholder='自动生成'  v-model="inputForm.purchaseNo" disabled></u--input>
            </u-form-item>
            <u-form-item label="采购名称" borderBottom prop="purchaseSketch" :required="true">
                <u--input placeholder='请填写采购名称' disabled  v-model="inputForm.purchaseSketch" ></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="purchaseDate" :required="true">
                <el-date-picker
                        :disabled="true"
                        v-model="inputForm.purchaseDate"
                        type="date"
                        placeholder="请选择采购申请时间"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="采购方式" borderBottom prop="purchaseMode" :required="true">
                <jp-picker placeholder='请选择采购方式' v-model="inputForm.purchaseMode" :disabled="true" rangeKey="label" rangeValue="value" :range="[
						        { label: '办公室采购', value: '1' },
						        { label: '自行采购', value: '2' },
						    ]"></jp-picker>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注信息' :disabled="true" :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 + '].purchaserAgent'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].purchaserAgent" :disabled="true" placeholder="请选择采购人" @focus="openUserPullForm(index_experience)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="采购人部门" :prop="'detailInfos[' + index_experience + '].procurementOffice'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].procurementOffice" :disabled="true" placeholder="" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="采购类型" :prop="'detailInfos[' + index_experience + '].procurementType'" :required="true"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].procurementType" :disabled="true" placeholder="请选择采购类型" @focus="showPicker(index_experience)" clearable></u--input>
                    </u-form-item>
                    <my-dropdown :index_experience="index_experience" :disabled="true"  :inputForm="inputForm"></my-dropdown>
<!--                    <u-form-item label="商品名称" :prop="'detailInfos[' + index_experience + '].tradeName'" -->
<!--                                 :rules="[-->
<!--				     ]">-->
<!--                        <u--input v-model="inputForm.detailInfos[index_experience].tradeName" placeholder="请选择物品名称" @focus="showGoods(index_experience)" clearable></u--input>-->
<!--                    </u-form-item>-->
                    <supplier-selector :index_experience="index_experience" :disabled="true"  :inputForm="inputForm"></supplier-selector>
<!--                    <u-form-item label="供应商" :prop="'detailInfos[' + index_experience + '].supplierName'" -->
<!--                                 :rules="[-->
<!--				     ]">-->
<!--                        <u--input v-model="inputForm.detailInfos[index_experience].supplierName" placeholder="请选择供应商" @focus="showGoods(index_experience)" clearable></u--input>-->
<!--                    </u-form-item>-->
                    <u-form-item label="商品单价(元)" :prop="'detailInfos[' + index_experience + '].tradePrice'"
                                 :rules="[
				     ]">
                        <u--input @change="changeValue" :disabled="true" v-model="inputForm.detailInfos[index_experience].tradePrice" placeholder="请输入商品单价(元)" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="商品数量" :prop="'detailInfos[' + index_experience + '].tradeNumber'"
                                 :rules="[
				     ]">
                        <u--input @change="changeValue" v-model="inputForm.detailInfos[index_experience].tradeNumber" :disabled="true" placeholder="请输入商品数量" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="商品总价" :prop="'detailInfos[' + index_experience + '].priceSum'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].priceSum" :disabled="true" placeholder="请输入商品总价" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="单位" :prop="'detailInfos[' + index_experience + '].company'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].company" :disabled="true" placeholder="请输入单位" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="备注" :prop="'detailInfos[' + index_experience + '].remarks'"
                                 :rules="[
				     ]">
                        <u--input v-model="inputForm.detailInfos[index_experience].remarks" :disabled="true" placeholder="请输入备注" clearable></u--input>
                    </u-form-item>
                    <u-form-item label="文件上传">
                        <el-upload
                                :disabled="true"
                                class="upload-demo"
                                :action="`http://pv4uct.natappfree.cc/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%" :disabled="true" 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" :disabled="true" @click="addRow()" plain>新增采购详情</el-button>
            </u-form-item>

            <u-form-item label="附件">
                <el-upload
                        :disabled="true"
                        class="upload-demo"
                        :action="`http://pv4uct.natappfree.cc/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>
        <user-select ref="userPicker" @input="handleEvent"></user-select>
        <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 userSelect from '@/components/user-select/user-select-radio.vue'
    import OSSService from "@/api/sys/OSSService"
    import SupplierSelector from './SupplierSelector';
    import MyDropdown from './MyDropdown';
    import goodsInfoPicker from '../collect/GoodsInfoPicker'
    import MaterialTypeService from '@/api/materialManagement/MaterialTypeService'
    import WareHouseService from '@/api/materialManagement/WareHouseService'
    import materialManagementService from '@/api/materialManagement/MaterialManagementService'
    import CommonApi from '@/api/common/CommonApi'
    import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
    import {mapState, mapMutations, mapActions} from 'vuex'
    export default {
        components: {
            userSelect,
            baTreePicker,
            goodsInfoPicker,
            'my-dropdown': MyDropdown,
            'supplier-selector': SupplierSelector
        },
        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: {
                    purchaseNo: '',
                    purchaseSketch: '',
                    handledBy: '',
                    handledById: '',
                    handledByOffice: '',
                    handledByOfficeName: '',
                    purchaseDate: '',
                    purchaseMode: '',
                    remarks: '',
                    detailInfos: [],
                    files: [], // 附件信息
                    procInsId: ''
                },
                rules: {
                    'purchaseDate': [
                        {
                            required: true,
                            message: '采购申请时间不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                    'purchaseSketch': [
                        {
                            required: true,
                            message: '采购名称不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                    'purchaseMode': [
                        {
                            required: true,
                            message: '采购方式不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                }
            }
        },
        materialTypeService: null,
        ossService: null,
        wareHouseService: null,
        commonApi: null,
        // 页面加载时执行
        created() {
            this.commonApi = new CommonApi()
            this.materialTypeService = new MaterialTypeService()
            this.ossService = new OSSService()
            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.purchaserAgent = data.name
                        detail.purchaserAgentId = data.id
                        detail.procurementOffice = data.officeDTO.name
                    }
                })
            });
        },
        props: {
            businessId: {
                type: String,
                default: ''
            },
            formReadOnly: {
                type: Boolean,
                default: false
            }
        },
        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) {

                this.searchForm.wareHouseType = this.inputForm.detailInfos[index].procurementTypeId
                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],
                    procurementType: names,
                    procurementTypeId: 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],
                    tradeName: names,
                    surplusNumber: tradeNumber
                });
            },
            init (id) {
                this.nodeFlag = true
                this.inputForm.id = id
                if (id) {
                    materialManagementService.findById(id).then((data) => {

                        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.purchaseDate = new Date(data.purchaseDate);

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

                        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);
                                })

                            }
                            this.inputForm.detailInfos[index].priceSum = parseFloat(parseFloat(this.inputForm.detailInfos[index].tradePrice)
                                * parseFloat(this.inputForm.detailInfos[index].tradeNumber)).toFixed(2)

                        })
                    })
                }
            },
            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({ purchaserAgent: this.userInfo.name,
                    purchaserAgentId: this.userInfo.id, procurementOffice: 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页面的路径
                // });
                this.$refs.userPicker.open(index,"");
            },
            handleEvent(data,index,type) {
                // 在这里处理子组件传递过来的数据
                this.inputForm.detailInfos[index].purchaserAgentId = data.id
                this.inputForm.detailInfos[index].purchaserAgent = data.label
                this.inputForm.detailInfos[index].procurementOffice = data.parentLabel
                this.inputForm.detailInfos[index].deptId = data.parentId
                // 进行进一步处理...
            },
            handleUploadSuccess (res, file, fileList, index, type) {
                // 将 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，找到上传成功的文件，设置对应索引的 showFileList2 为 true
                    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.inputForm.files = formattedFiles;
                // fileList.forEach((item, index) => {
                //     if (item === file) {
                //         this.$set(this.showFileList, index, true);
                //     }
                // });
                // 强制更新视图
                this.$forceUpdate();
            },
            handleRemove(file, fileList, index, type) {
                // 处理移除文件逻辑
                // 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.purchaseDate)) {
                        this.inputForm.purchaseDate = this.formatDate(this.inputForm.purchaseDate);
                    }

                    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].purchaserAgent)) {
                                this.$message.error('采购详情第' + k + '行请选择采购人')
                                this.loading = false
                                return
                            }
                            if (this.isEmpty(this.inputForm.detailInfos[j].procurementType)) {
                                this.$message.error('采购详情第' + k + '行请选择采购类型')
                                this.loading = false
                                return
                            }
                            if (this.isEmpty(this.inputForm.detailInfos[j].tradeName)) {
                                this.$message.error('采购详情第' + k + '行请填写商品名称')
                                this.loading = false
                                return
                            }
                        }
                        for (let j = 0; j < i; j++) {
                            for (let k = j + 1; k < i; k++) {
                                if (this.inputForm.detailInfos[j].procurementType === this.inputForm.detailInfos[k].procurementType) { // 如果采购类型相同
                                    if (this.inputForm.detailInfos[j].tradeName === this.inputForm.detailInfos[k].tradeName) { // 如果商品名称相同
                                        if (this.inputForm.detailInfos[j].supplierName === this.inputForm.detailInfos[k].supplierName) {
                                            this.$message.warning(`采购详情中，同种采购类型、同一供应商的商品名称只能输入一条`)
                                            this.loading = false
                                            throw new Error('采购详情中，同种采购类型、同一供应商的商品名称只能输入一条')
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 计算总价
                    const tradeTotalPrice = this.inputForm.detailInfos.reduce((total, item) => {
                        // 将每个 detailInfo 的 priceSum 加到总价中
                        return total + parseFloat(item.priceSum || 0); // 转换为浮点数并累加，避免字符串拼接
                    }, 0); // 初始值为 0

                    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';
                            materialManagementService.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') {
                    materialManagementService.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}
                                materialManagementService.updateStatusById(param).then(() => {
                                    this.loading = false
                                    callback()
                                })
                            }
                        }
                    })
                } else if (type === 'hold') {
                    materialManagementService.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}
                            materialManagementService.updateStatusById(param).then(() => {
                                this.loading = false
                                callback()
                            })
                        }
                    })
                }
            },
            reapplyForm (callback) {
                this.loading = true
                materialManagementService.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.purchaseDate)) {
                    this.inputForm.purchaseDate = this.formatDate(this.inputForm.purchaseDate);
                }
                this.$refs.inputForm.validate().then(res => {
                    this.inputForm.status = '2'
                    // 计算总价
                    const tradeTotalPrice = this.inputForm.detailInfos.reduce((total, item) => {
                        // 将每个 detailInfo 的 priceSum 加到总价中
                        return total + parseFloat(item.priceSum || 0); // 转换为浮点数并累加，避免字符串拼接
                    }, 0); // 初始值为 0

                    materialManagementService.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.purchaseDate)) {
                    this.inputForm.purchaseDate = this.formatDate(this.inputForm.purchaseDate);
                }
                this.$refs.inputForm.validate().then(res => {
                    this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
                        if (this.isNotEmpty(data)) {
                            if (data === '公司领导审批') {
                                this.inputForm.status = '5'
                            }
                        }
                        materialManagementService.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()
                        })
                    })
                })
            },
            // 值改变事件
            changeValue () {
                let i = this.inputForm.detailInfos.length
                for (let j = 0; j < i; j++) {
                    if (this.isNotEmpty(this.inputForm.detailInfos[j].tradePrice)) {
                        if (this.isNotEmpty(this.inputForm.detailInfos[j].tradeNumber)) {
                            // parseFloat(item.account).toFixed(2)
                            this.inputForm.detailInfos[j].priceSum = parseFloat(parseFloat(this.inputForm.detailInfos[j].tradePrice) * parseFloat(this.inputForm.detailInfos[j].tradeNumber)).toFixed(2)
                        } else {
                            this.inputForm.detailInfos[j].priceSum = ''
                        }
                    } else {
                        this.inputForm.detailInfos[j].priceSum = ''
                    }
                }
            },
            async handleFileClick(file) {
                await this.ossService.getTemporaryUrl(file.url).then((data) => {
                    file.lsUrl = data
                })
                if (this.isImage(file.name)) {
                    // 如果是图片文件，则执行放大显示图片的逻辑
                    this.handleImageClick(file);
                } else {
                    // window.open(file.lsUrl, '_blank')
                    window.location.href = file.lsUrl
                    // 如果不是图片文件，则执行其他操作，比如下载文件等
                }
            },
            // 判断文件是否是图片类型
            isImage(fileName) {
                const ext = fileName.toLowerCase().split('.').pop(); // 获取文件的后缀名
                return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext); // 判断后缀名是否是图片类型
            },
            handleImageClick(file) {
                // 在点击图片时执行放大显示的逻辑
                this.$alert(`<img src="${file.lsUrl}" style="max-width: 100%; max-height: 100%;" />`, '图片详情', {
                    dangerouslyUseHTMLString: true,
                    customClass: 'custom-alert'
                });
            },
            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中移除对应的元素
                    }
                }

            },
            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 或者其他适当的
            },
            onInputCode(index, event,type) {
                const inputValue = event
                const formattedValue = this.formatInput(inputValue);
                if (type === 'tradePrice') {
                    this.$set(this.inputForm.detailInfos[index], 'tradePrice', formattedValue)
                }
                if (type === 'tradeNumber') {
                    this.$set(this.inputForm.detailInfos[index], 'tradeNumber', formattedValue)
                }
                if (this.isNotEmpty(this.inputForm.detailInfos[index].tradePrice && this.inputForm.detailInfos[index].tradeNumber)) {
                     let priceSum =
                        parseFloat(parseFloat(this.inputForm.detailInfos[index].tradePrice) * parseFloat(this.inputForm.detailInfos[index].tradeNumber)).toFixed(2)
                    this.$set(this.inputForm.detailInfos[index], 'priceSum', priceSum)
                }
            },
            // 通用的输入限制和格式化方法
            formatInput(inputValue, decimalLimit = 2) {
                // 如果输入值不是数字或者不是有效的小数，则返回空字符串
                if (!/^\d*\.?\d*$/.test(inputValue)) {
                    return '';
                }
                // 只保留数字和一个小数点
                let value = inputValue.replace(/[^\d.]/g, '');
                // 只允许一个小数点
                const dotIndex = value.indexOf('.');
                if (dotIndex !== -1) {
                    const substr = value.substr(dotIndex + 1);
                    if (substr.indexOf('.') !== -1) {
                        value = value.substr(0, dotIndex + 1) + substr.replace(/\./g, '');
                    }
                }
                // 限制小数位数为指定的decimalLimit位数
                if (dotIndex !== -1) {
                    const integerPart = value.substring(0, dotIndex);
                    const decimalPart = value.substring(dotIndex + 1);
                    if (decimalPart.length > decimalLimit) {
                        uni.showToast({
                            title: '商品数量小数点后只能输入两位，请正确输入！',
                            icon: 'none',
                            duration: 2000
                        });
                        return ''; // 返回空字符串
                    }
                    value = integerPart + '.' + decimalPart;
                }

                return value;
            },
        }
    }
</script>

<style>
    .cu-form-group .title {
        min-width: calc(4em + 40px);
    }
    .custom-alert {
        max-width: 80% !important;
        max-height: 80% !important;
    }

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