<template>
    <hc-new-dialog is-table widths="95%" :show="isShow" :title="`中间计量${dataId ? isView ? '查看' : '修改' : '新增'}`" :footer="!isView	" @save="addModalSave" @close="addModalClose">
        <div v-loading="isLoading" class="relative h-full flex">
            <div v-if="!dataId" :id="`hc_tree_card_${uuid}`" class="hc_tree_card_border relative">
                <hc-body scrollbar padding="0px">
                    <hc-lazy-tree :h-props="treeProps" tree-key="id" :auto-expand-keys="treeAutoExpandKeys" @load="treeLoadNode" @node-tap="treeNodeTap" />
                </hc-body>
            </div>
            <div :id="`hc_table_card_${uuid}`" class="relative flex-1">
                <hc-body scrollbar padding="0px">
                    <!-- 基础表单 -->
                    <hc-card-item>
                        <el-form ref="baseFormRef" :model="baseForm" :rules="baseFormRules" label-position="left" label-width="auto" :disabled="isView">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="计量期：" prop="contractPeriodId">
                                        <el-select v-model="baseForm.contractPeriodId" placeholder="选择计量期" filterable block @change="periodChange">
                                            <el-option v-for="item in period" :key="item.id" :label="item.periodNumber" :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="计量单编号：">
                                        <el-input v-model="baseForm.meterNumber" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="业务日期：" prop="businessDate">
                                        <el-date-picker v-model="baseForm.businessDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="16">
                                    <el-form-item label="工程划分：">
                                        <el-input v-model="baseForm.engineerDivide" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="部位名称：">
                                        <el-input v-model="baseForm.partName" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="交工证书编号：">
                                        <el-input v-model="baseForm.certificateNumber" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="计量金额：">
                                        <el-input v-model="baseForm.meterMoney" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="变更令：">
                                        <el-input v-model="baseForm.changeTokenNumber" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="收方单：">
                                        <el-input v-model="baseForm.debitFormId" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="草图文件：">
                                        <hc-form-upload :src="baseForm.pictureList" :h-props="uploadFormProps" :disabled="isView" @upload="formUpload" @change="formUploadChange" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-button type="warning" class="w-full" style="height: 70%;" @click="associateQual">
                                        <span>点击关联质检资料</span>
                                    </el-button>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="计算式：">
                                        <el-input v-model="baseForm.calculateFormula" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </hc-card-item>
                    <!-- 收方清单列表 -->
                    <hc-card-item class="mt-3">
                        <template #header>
                            <span class="mr-3">计量清单列表111</span>
                            <span class="text-orange font-400">温馨提示：超计,累计计量量> 变更后数量，分解清单超计整行红色</span>
                        </template>
                        <template #extra>
                            <el-button type="primary" text :disabled="isView" @click="addBillBaseModalClick">
                                <HcIcon name="add" />
                                <span>添加清单</span>
                            </el-button>
                        </template>
                        <hc-table is-new :index-style="{ width: 60 }" :is-stripe="false" :column="addTableColumn" :datas="addTableData" :row-style="addTableRowStyle">
                            <template #currentPrice="{ row }">
                                <hc-table-input v-model="row.currentPrice" disabled />
                            </template>
                            <template #changeTotal="{ row }">
                                <hc-table-input v-model="row.changeTotal" disabled />
                            </template>
                            <template #currentMeterTotal="{ row }">
                                <hc-table-input v-model="row.currentMeterTotal" :disabled="isView" @blur="currentMeterTotalBlur(row)" />
                            </template>
                            <template #containChangeTotal="{ row }">
                                <hc-table-input v-model="row.containChangeTotal" :disabled="isView" @blur="containChangeTotalBlur(row)" />
                            </template>
                            <template #payRatio="{ row }">
                                <hc-table-input v-model="row.payRatio" :disabled="isView" />
                            </template>
                            <template #currentMeterMoney="{ row }">
                                <hc-table-input v-model="row.currentMeterMoney" disabled />
                            </template>
                            <template #allMeterTotal="{ row }">
                                <hc-table-input v-model="row.allMeterTotal" disabled />
                            </template>
                            <template #action="{ index }">
                                <el-link type="danger" :disabled="isView" @click="delAddTableClick(index)">删除</el-link>
                            </template>
                        </hc-table>
                    </hc-card-item>
                    <!-- 附件列表 -->
                    <hc-card-item class="mt-3" title="附件列表">
                        <template #extra>
                            <span class="text-orange font-400">可上传 图片(png、jpg、jpeg)、Excel(xls、xlsx)、PDF、Word(doc、docx)文件</span>
                        </template>
                        <el-form :model="baseForm" label-position="left" label-width="auto">
                            <el-form-item label="上传附件">
                                <hc-form-upload type="list" :src="baseForm.fileList" :h-props="uploadFormProps" :disabled="isView" @upload="attachmentUpload" @change="attachmentUploadChange" />
                            </el-form-item>
                        </el-form>
                    </hc-card-item>
                </hc-body>
            </div>
        </div>
    </hc-new-dialog>

    <!-- 添加分解清单 -->
    <HcBillBaseModal v-model="addBillBaseModalShow" :data-id="dataId" :ids="billBaseIds" :idn="nodeId" :period-id="baseForm.contractPeriodId" :contract-id="cid" @finish="finishChange" />

    <!-- 文件上传组件 -->
    <hc-upload-file
        ref="uploadFileRef"
        :echo-params="uploadFileParams"
        :options="uploadFileOptions"
        @success="uploadFileSuccess"
    />

    <!-- 关联质检资料 -->
    <qualityRleation :quality-moadal="qualityMoadal" :cid="cid" :period-id="period_id" :select-id="selectId" @close="closeQual" @finish="finishModal" />
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'

import { isNumberReg } from '~uti/tools'
import HcBillBaseModal from './addBillBaseModal.vue'
import qualityRleation from './qualityRleation.vue'
import { arrDelKey, arrToId, arrToKey, deepClone, getArrValue, getObjValue, getRandom, isArrIndex, isNullES } from 'js-fast-way'
import BigNumber from 'bignumber.js'
import { getHeader } from 'hc-vue3-ui'

import unitApi from '~api/project/debit/contract/unit'
import mainApi from '~api/debit-pay/admin/middlepay'


import { getStoreValue, setStoreValue } from '~src/utils/storage'
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    allPeriods: {
        type: Array,
        default: () => ([]),
    },
    periodId: {
        type: [String, Number],
        default: '',
    },
    ids: {
        type: [String, Number],
        default: '',
    },
    isView:{
        type:Boolean,
        default:false, //是否预览
    },
})

//事件
const emit = defineEmits(['finish', 'close'])
const uuid = getRandom(4)
const dataId = ref(props.ids)
const period = ref(props.allPeriods)
const period_id = ref(props.periodId)
const pid = ref(props.projectId)
const cid = ref(props.contractId)
const isLoading = ref(false)
const isView = ref(props.isView)

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.allPeriods,
    props.periodId,
    props.isView,
], ([projectId, contractId, periods, periodId, view]) => {
    period.value = periods
    pid.value = projectId
    cid.value = contractId
    period_id.value = periodId
    isView.value = view
    setBasePeriodForm(periodId)
}, { deep: true })

//监听
watch(() => props.ids, (id) => {
    dataId.value = id
}, { deep: true })

//监听
watch(isShow, (val) => {
    if (val) {
        if (dataId.value ) {
            getDataDetail()
        } else {
            setBasePeriodForm(period_id.value)
            nextTick(() => {
                setSplitRef()
            })
        }
    } else {
        baseForm.value = { fileList: [], pictureUrl: '', pictureName:'', pictureList:[] }
    }
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    try {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    } catch (error) {
        console.log(error)
    }
}

//基础表单
const baseFormRef = ref(null)
const baseForm = ref({ fileList: [], pictureUrl: '', pictureName:'' })
const baseFormRules = {
    contractPeriodId: {
        required: true,
        trigger: 'blur',
        message: '请选择计量期',
    },
    businessDate: {
        required: true,
        trigger: 'blur',
        message: '请选择业务日期',
    },
}

//获取数据详情
const selectId = ref('')
const getDataDetail = async () => {
    if (!dataId.value) return
    const { data } = await mainApi.getDetail({ id: dataId.value })
    const res = getObjValue(data)
    res.pictureList = [{
        fileName: res.pictureName ?? '',
        filePdfUrl: res.pictureUrl ?? '',
        fileUrl: res.pictureUrl ?? '',
    }]
    res.pictureUrl = res.pictureUrl ?? ''
    res.pictureName = res.pictureName ?? ''
    nodeId.value = res.contractUnitId ?? ''
    baseForm.value = res
    addTableData.value = getArrValue(res.formList)
    selectId.value = arrToKey(res.fileList, 'selectId', ',')
}

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}

//懒加载的数据
const treeAutoExpandKeys = ref(getStoreValue('middlepay-tree-auto-expand-keys') || [])
const treeLoadNode = async ({ item, level }, resolve) => {
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await unitApi.lazyTree({
        id: id,
        contractId: cid.value,
        contractPeriodId: period_id.value,
    })
    resolve(getArrValue(data))
}
const nodeId = ref('')
const isLastChild = ref(true)//是否是最底层节点
const treeNodeTap = ({ data }) => {
    const { notExsitChild } = data
    isLastChild.value = notExsitChild
    nodeId.value = data.id
    baseForm.value.contractUnitId = data.id
    baseForm.value.fileList = []
    getNodeDivide(data.id)
    getCurrentNodeAllFormData(data.id)
}

//获取工程划分
const getNodeDivide = async (nodeId) => {
    const { data } = await mainApi.getNodeDivide({ nodeId: nodeId })
    baseForm.value.engineerDivide = data ?? ''
}
 //获取当前节点下，当期未被计量的所有清单
 const getCurrentNodeAllFormData = async (nodeId) => {
    const { data } = await mainApi.getCurrentNodeAllForm({ contractId:  cid.value, contractPeriodId:baseForm.value.contractPeriodId, contractUnitId:nodeId })
 addTableData.value = getArrValue(data)
 
}

//获取变更令
const getNodeToken = async () => {
    isLoading.value = true
    const { businessDate } = baseForm.value
    const { data } = await mainApi.getNodeToken({
        projectId: pid.value,
        contractId: cid.value,
        nodeId: nodeId.value,
        businessDate: businessDate,
        formIds: arrToId(addTableData.value),
    })
    //处理数据
    const { changeTokenNumber, changeTokenIds, files } = getObjValue(data)
    baseForm.value.changeTokenNumber = changeTokenNumber ?? ''
    baseForm.value.changeTokenIds = changeTokenIds ?? ''
    //处理文件
    let newFileList = []
    const fileList = deepClone(baseForm.value.fileList)
    //移除非手动上传的文件
    for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].fileType === 1) {
            newFileList.push(fileList[i])
        }
    }
    //追加附件列表
    const filesArr = getArrValue(files)
    for (let i = 0; i < filesArr.length; i++) {
        newFileList.push(filesArr[i])
    }
    //更新数据
    baseForm.value.fileList = newFileList
    isLoading.value = false
}

//计量期被改变
const periodChange = () => {
    setBasePeriodForm(baseForm.value.contractPeriodId)
    getCurrentNodeAllFormData( nodeId.value)
}

//计量期相关的数据
const setBasePeriodForm = (periodId) => {
    if (dataId.value) return
    treeAutoExpandKeys.value = getStoreValue('middlepay-tree-auto-expand-keys') || []
    const periods = period.value
    baseForm.value.contractPeriodId = periodId
    const periodData = periods.find((item) => item.id === periodId)
    baseForm.value.periodNumber = periodData.periodNumber
    baseForm.value.businessDate = periodData.endDate ?? null
    getMeterNumber(periodId)
}

//获取计量单编号
const getMeterNumber = async (periodId) => {
    const { data } = await mainApi.getMeterNumber({
        projectId: pid.value,
        contractId: cid.value,
        contractPeriodId: periodId,
    })
    baseForm.value.meterNumber = data ?? ''
}


//草图文件上传
const formUpload = () => {
    uploadFileParams.value = { type: '草图文件' }
    uploadFileOptions.value.accept = 'image/png,image/jpg,image/jpeg'
    uploadFileOptions.value.accept_tip = '图片(png、jpg、jpeg)'
    uploadFileOptions.value.size = 50
    uploadFileRef.value?.selectFile()
}
const formUploadChange = (url) => {
    baseForm.value.pictureUrl = url
}

//收方清单列表
const addTableColumn = ref([
    { key: 'formNumber', name: '清单编号', width: '120' },
    { key: 'formName', name: '清单名称', minWidth: '280' },
    { key: 'currentPrice', name: '单价(元)', width: '100' },
    { key: 'resolveTotal', name: '分解数量', width: '100' },
    { key: 'changeTotal', name: '变更后数量', width: '100' },
    { key: 'currentMeterTotal', name: '本期计量数量', width: '140' },
    { key: 'payRatio', name: '支付比例', width: '140' },
    { key: 'containChangeTotal', name: '含变更数量', width: '100' },
    { key: 'currentMeterMoney', name: '本期计量金额', width: '120' },
    { key: 'allMeterTotal', name: '累计计量量', width: '100' },
    { key: 'otherMeterTotal', name: '基数', width: '80' },
    { key: 'action', name: '操作', fixed: 'right', width: 80, align: 'center' },
])
const addTableData = ref([])

//计算本期计量金额
const currentMeterTotalBlur = (row) => {
    //如果为空
    let currentMeterTotal = row.currentMeterTotal
    const isMeter = isNumberReg(currentMeterTotal)
    if (isNullES(currentMeterTotal) || !isMeter) {
        currentMeterTotal = 0
    }
    //计算本期计量金额
    nextTick(() => {
        row.currentMeterTotal = currentMeterTotal
        row.currentMeterMoney = (BigNumber(currentMeterTotal).multipliedBy(row.currentPrice)).toString()
        row.allMeterTotal = (BigNumber(currentMeterTotal).plus(row.otherMeterTotal)).toString()
        //计算总计量金额
        let meterMoney = 0, table = addTableData.value
        for (let i = 0; i < table.length; i++) {
            meterMoney = (BigNumber(meterMoney).plus(table[i].currentMeterMoney)).toString()
        }
        baseForm.value.meterMoney = meterMoney


     
     //  累计计量金额 > 最高支付金额   变红
    // 当前行多返回一个字段otherPayMoney 代表其他期计量金额
    // 累计计量金额 = 其他期计量金额+（本期计量金额*支付比例）
    // 当前行多返回一个字段upPayMoney 代表最高支付金额
    // let otherPayMoney = new BigNumber(row.otherPayMoney )//其他期计量金额
    // let currentMeterMoney = new BigNumber(row.currentMeterMoney )//本期计量金额
    // let upPayRatio = new BigNumber(row.upPayRatio ).dividedBy(100)//支付比例
    // let upPayRatioMoney = (otherPayMoney.plus((currentMeterMoney.multipliedBy(upPayRatio)).toNumber()))//累计计量金额
    // let upPayMoney = new BigNumber(row.upPayMoney)//最高支付金额
    // const isComparedmoney = upPayRatioMoney.comparedTo(upPayMoney)
    // //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
    //     if (isComparedmoney === 1 || isComparedmoney === null) {
    //         isCanSave.value = true
          
    //        window.$message.warning('累计计量金额超出支付比列，如需计量100%，请完成关联对应的质保资料')
    //         return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
            
        
    //     } else {
    //         isCanSave.value = false
           
    //     }
    })
}

//计算含变更数量
const containChangeTotalBlur = (row) => {
    let val = row.containChangeTotal
    const isMeter = isNumberReg(val)
    if (isNullES(val) || !isMeter) {
        val = 0
    }
    nextTick(() => {
        row.containChangeTotal = val
    })
}
const unPayRatioBlur = (row)=>{
    nextTick(()=>{
             
     //  累计计量金额 > 最高支付金额   变红
    // 当前行多返回一个字段otherPayMoney 代表其他期计量金额
    // 累计计量金额 = 其他期计量金额+（本期计量金额*支付比例）
    // 当前行多返回一个字段upPayMoney 代表最高支付金额
    let otherPayMoney = new BigNumber(row.otherPayMoney )//其他期计量金额
    let currentMeterMoney = new BigNumber(row.currentMeterMoney )//本期计量金额
    let upPayRatio = new BigNumber(row.upPayRatio ).dividedBy(100)//支付比例
    let upPayRatioMoney = (otherPayMoney.plus((currentMeterMoney.multipliedBy(upPayRatio)).toNumber()))//累计计量金额
    let upPayMoney = new BigNumber(row.upPayMoney)//最高支付金额
    const isComparedmoney = upPayRatioMoney.comparedTo(upPayMoney)
    //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
        if (isComparedmoney === 1 || isComparedmoney === null) {
            isCanSave.value = true
          
           window.$message.warning('累计计量金额超出支付比列，如需计量100%，请完成关联对应的质保资料')
            return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
            
        
        } else {
            isCanSave.value = false
           
        }
    })
    
}
//判断是否红色
const isCanSave = ref(false)

const addTableRowStyle = ({ row }) => {

    // 判断施工图数量是否大于合同数据
    //      大于：如果超计= 1并且 划分=1
    //          不显示红色，否则显示
    //      小于：判断累计计量量是否大于变更后数量
    //            大于： 如果超计=1 不变红
    //                  不等于1则变红
    //            小于：不变红
    //施工图数量是否大于合同数据
    let isBuildThanContract = row.isBuildThanContract
    //是否超计
    let isContractOver = row.isContractOver
    //是否生成划分
    let isCreateDivide = row.isCreateDivide

    if (isBuildThanContract) {
        if (isContractOver && isCreateDivide) {
            isCanSave.value = false
        } else {
            isCanSave.value = true
            return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
        }

    } else {
            let allMeterTotal = new BigNumber(row.allMeterTotal) //a 累计计量量
            let changeTotal = new BigNumber(row.changeTotal) //b 变更后数量
            //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
            const isCompared = allMeterTotal.comparedTo(changeTotal)
            if (isCompared === 1 || isCompared === null) {
                if (isContractOver) {
                    isCanSave.value = false
                } else {
                    isCanSave.value = true
                    return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
                }
            } else {
                isCanSave.value = false
            }
    }



}

//删除清单
const delAddTableClick = (index) => {
    addTableData.value.splice(index, 1)
    //获取变更令
    nextTick(() => {
        getNodeToken()
    })
}

//添加分解单
const addBillBaseModalShow = ref(false)
const billBaseIds = ref('')
const addBillBaseModalClick = () => {
    if (!nodeId.value) {
        window.$message.warning('请先选择一个树节点')
        return
    }
    if ( isLastChild.value) {
        addBillBaseModalShow.value = true
    } else {
        window.$message.warning('请选择最底层节点')
    }
    
    addBillBaseModalShow.value = true
    billBaseIds.value = arrToId(addTableData.value)
}
//添加完成
const finishChange = (data) => {
    for (let i = 0; i < data.length; i++) {
        addTableData.value.push(data[i])
    }
    //获取变更令
    nextTick(() => {
        getNodeToken()
    })
}

//附件上传
const uploadFormProps = {
    url: 'filePdfUrl',
    name: 'fileName',
}

const attachmentUpload = () => {
    uploadFileParams.value = { type: '附件文件' }
    uploadFileOptions.value.accept = ''
    uploadFileOptions.value.accept_tip = ''
    uploadFileOptions.value.size = null
    uploadFileRef.value?.selectFile()
}
const attachmentUploadChange = (a, b, fileList) => {
    baseForm.value.fileList = getArrValue(fileList)
    selectId.value = arrToKey( baseForm.value.fileList, 'selectId', ',')
}

//文件上传
const uploadFileRef = ref(null)
const uploadFileParams = ref({})
const uploadFileOptions = ref({
    headers: getHeader(),
    multiple: false,
})

// 文件上传成功的回调
const uploadFileSuccess = ({ echoParams, resData }) => {
    const { pdfUrl } = resData
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        uploadFileRef.value?.setModalShow(false)
        return
    }
    if (echoParams.type === '草图文件') {
        baseForm.value.pictureUrl = resData.link ?? ''
        baseForm.value.pictureName = resData.originalName ?? ''
        baseForm.value.pictureList = [{
            fileName: resData.originalName ?? '',
            filePdfUrl: resData.pdfUrl ?? '',
            fileUrl:  resData.link ?? '',
        }]
        uploadFileRef.value?.setModalShow(false)
    } else if (echoParams.type === '附件文件') {
        baseForm.value.fileList.push({
            contractId: cid.value,
            fileName: resData.originalName ?? '',
            filePdfUrl: resData.pdfUrl ?? '',
            fileUrl: resData.link ?? '',
            fileType: 1,
        })
        uploadFileRef.value?.setModalShow(false)
    }
}

//保存
const addModalSave = async () => {
    if (!nodeId.value) {
        window.$message.warning('请先选择一个树节点')
        return
    }
    // if (isCanSave.value) {
    //     window.$message.warning('累计计量量 > 变更后数量,不允许修改')
    //     return
    // }
    const form = baseForm.value
    form.formList = addTableData.value
    form.projectId = pid.value
    form.contractId = cid.value
    let res = {}
    if (dataId.value) {
        res = await mainApi.edit(form)
    } else {
        res = await mainApi.add(form)
    }
    //处理数据
    const { code, msg } = res
    if (code === 200) {
        window.$message.success('保存成功')
        addModalClose()
        emit('finish')
    } else {
        window.$message.error(msg ?? '保存失败')
    }
}

//关闭弹窗
const addModalClose = () => {
    isShow.value = false
    baseForm.value = { fileList: [], pictureUrl: '' }
    addTableData.value = []
    selectId.value = ''
    setStoreValue('checkRows', [])
    emit('close')
}
//关联质检资料
const qualityMoadal = ref(false)

const associateQual = ()=>{
    if (!nodeId.value) {
        window.$message.warning('请先选择一个树节点')
        return
    }
    if ( isLastChild.value) {
        qualityMoadal.value = true
    } else {
        window.$message.warning('请选择最底层节点')
    }
    
}
const closeQual = ()=>{
    qualityMoadal.value = false
}
const finishModal = (rows, cancelcheck)=>{
    let fileList = []
    rows.forEach(ele => {
        const isPush = isArrIndex( baseForm.value.fileList, 'selectId', ele.selectId)
        if (!isPush) {
            fileList.push({
                fileName:ele.dataName,
                filePdfUrl:ele.evisaPdfUrl ? ele.evisaPdfUrl : ele.pdfUrl,	
                fileType:1,
                fileUrl:ele.evisaPdfUrl ? ele.evisaPdfUrl : ele.pdfUrl,	
                selectId:ele.selectId,
            })
        }
    })

   fileList.forEach((ele)=>{
    baseForm.value.fileList.push(ele)
   })

//表格取消勾选回显
cancelcheck.forEach((ele)=>{
    baseForm.value.fileList.forEach((ele1)=>{
        if (ele === ele1.selectId) {
          let arr = arrDelKey(baseForm.value.fileList, 'selectId', ele)
          baseForm.value.fileList = arr
        }
    })
})
   selectId.value = arrToKey( baseForm.value.fileList, 'selectId', ',')

}
</script>
