<template>
    <hc-new-dialog is-table widths="95%" :show="isShow" :title="`中间计量${dataId ? isView ? '查看' : '修改' : '新增'}`" is-footer-center :footer="!isView" @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
                                            v-model="baseForm.pictureList"
                                            :disabled="isView"
                                            is-res
                                            :options="{
                                                type: 'list',
                                                props: uploadFormProps,
                                                isArr: true,
                                            }"
                                            :upload="{
                                                options: {
                                                    accept: '.png,.jpg,.jpeg',
                                                    accept_tip: '图片(png、jpg、jpeg)',
                                                    size: 50,
                                                    multiple: false,
                                                },
                                            }"
                                            @success="pictureUploadSuccess"
                                        />
                                    </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">计量清单列表</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 :key="tableKey" is-new :index-style="{ width: 60 }" :is-stripe="false" :column="addTableColumn" :datas="addTableData" :row-style="addTableRowStyle" :is-current-row="false">
                            <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-if="isNullES(row.upPayRatio)" v-model="row.payRatio" disabled />
                                <hc-table-input v-else v-model="row.payRatio" :disabled="isView || baseForm.fileList.length > 0" @blur="unPayRatioBlur(row)" />
                            </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
                                    v-model="baseForm.fileList"
                                    :disabled="isView"
                                    is-del
                                    is-res
                                    :options="{
                                        type: 'list',
                                        props: uploadFormProps,
                                        isArr: true,
                                        num: 0,
                                    }"
                                    @success="fileUploadSuccess"
                                    @del="attachMentDel"
                                    @change="attachmentUploadChange"
                                />
                            </el-form-item>
                        </el-form>
                    </hc-card-item>
                </hc-body>
            </div>
        </div>
        <template #footer>
            <el-button hc-btn @click="addModalClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="addModalSave">提交</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="submitClose">提交并关闭</el-button>
        </template>
    </hc-new-dialog>

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

    <!-- 关联质检资料 -->
    <qualityRleation :quality-moadal="qualityMoadal" :cid="cid" :period-id="period_id" :select-id="selectId" :is-remian-old-check="true" :disabled="baseForm?.isAutoBuild === 1" @close="closeQual" @finish="finishModal" />
</template>

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

import { isNumberReg, keepdecimal } 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 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 tableKey = ref(getRandom())
//监听
watch(() => baseForm.value.fileList, (list) => {
    console.log(list, 'list')
    tableKey.value = getRandom()
    // 验证数组中的对象是否包含名为 'selectId' 的字段

    if (list.length > 0) {
        const fieldName = 'selectId'//是否关联质检资料，已关联变为100(upPayRatio不等于null)
        const containsField = list.some(obj => obj.hasOwnProperty(fieldName))
        if (containsField) {
            addTableData.value.forEach((ele)=>{
                if (isNullES(ele.upPayRatio)) {
                    return
                }
                ele.upPayRatio = 100
            })
        } else {
            addTableData.value.forEach((ele)=>{
                if (!ischangeByGetNode.value) {
                    ele.upPayRatio = ele.oldupPayRatio || '0.00'
                }
            })
        }
    }

nextTick(()=>{
    console.log(isComparedRaVal.value, 'isComparedRaVal.value ')
    if (isComparedRaVal.value === 1 ) {
        window.$message.warning('累计计量金额超出支付比列，如需计量100%，请完成关联对应的质检资料')
    }
})

}, { deep: true })
//获取数据详情
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', ',')
    addTableData.value.forEach((ele)=>{
        ele.oldupPayRatio = ele.upPayRatio
    })
}

//数据格式
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 treeItemData = ref({})
const treeNodeTap = ({ data, keys }) => {
    treeItemData.value = data
    setStoreValue('middlepay-tree-auto-expand-keys', keys)
    const { notExsitChild } = data
    isLastChild.value = notExsitChild
    nodeId.value = data.id
    baseForm.value.contractUnitId = data.id
    baseForm.value.fileList = []
    ischangeByGetNode.value = false
    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)
    addTableData.value.forEach((ele)=>{
        ele.oldupPayRatio = ele.upPayRatio
    })
}

//获取变更令
const ischangeByGetNode = ref(false)
const getNodeToken = async () => {
    ischangeByGetNode.value = true
    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 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 isComparedRaVal = ref(-1)
//计算本期计量金额
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)).toFixed(2).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
        //计算本期支付比例
        //本期支 付比例=本期计量数量/变更后数量
        //如果不存在unPayRatio，支付比例不能计算
        if (!isNullES(row.upPayRatio)) {
            row.payRatio = isNaN(BigNumber(currentMeterTotal).dividedBy(row.changeTotal).toString() * 100) ? '0.00' : BigNumber(currentMeterTotal).dividedBy(row.changeTotal).toString() * 100
            row.payRatio = row.payRatio .toFixed(2) === 'Infinity' ? 0 : row.payRatio .toFixed(2)
        }
        compareRowUnpayRatio(row, 1)
    })
}

//计算含变更数量
const containChangeTotalBlur = (row) => {
    let val = row.containChangeTotal
    const isMeter = isNumberReg(val)
    if (isNullES(val) || !isMeter) {
        val = 0
    }
    nextTick(() => {
        row.containChangeTotal = val
    })
}
const compareRowUnpayRatio = (row, type)=>{
    // 计算方式：
    //本期支 付比例=本期计量数量/变更后数量
    //本期支付比例=本期计量数量/变更后数量
    //本期计量数量=本期支付比例*变更后数量
    // 会返回最大支付比例   upPayRatio
    // 和其他期支付比例 otherPayRatio

    // 每次填写完 本期计量数量或者支付比例后
    // 就去对比：本期支付比例+其他期支付比例
    // 是否大于最大支付比例
    // 如果大于，则提示
    let payRatio = new BigNumber(row.payRatio )//本期支付比例
    let upPayRatio = new BigNumber(row.upPayRatio )//最大支付比例
    let otherPayRatio = new BigNumber(row.otherPayRatio )//其他期支付比例
    let result = BigNumber(payRatio).plus(otherPayRatio)//本期支付比例+其他期支付比例
    const isComparedRa = result.comparedTo(upPayRatio)
    isComparedRaVal.value = isComparedRa
    if (isComparedRa === 1 ) {
        isCanSave.value = true
        if (type === 1) {
            window.$message.warning('累计计量金额超出支付比列，如需计量100%，请完成关联对应的质保资料')
        } else if (type === 2) {
            return isComparedRa
        }
    } else {
        isCanSave.value = false
    }
}
const unPayRatioBlur = (row)=>{
    row.payRatio = keepdecimal(row.payRatio)
    nextTick(()=>{
        //如果为空
        let payRatio1 = row.payRatio
        const isMeter = isNumberReg(payRatio1)
        if (isNullES(payRatio1) || !isMeter) {
            payRatio1 = 0
        }
        let payRatio = new BigNumber(payRatio1 )//本期支付比例
        let changeTotal = new BigNumber(row.changeTotal )//变更后数量
        // 本期计量数量=本期支付比例*变更后数量
        row.currentMeterTotal = (payRatio.dividedBy(100).multipliedBy(changeTotal)).toFixed(2).toString()
        row.currentMeterMoney = (BigNumber(row.currentMeterTotal).multipliedBy(row.currentPrice)).toFixed(2).toString()//本期计量金额额
        row.allMeterTotal = (BigNumber(row.currentMeterTotal).plus(row.otherMeterTotal)).toFixed(2).toString()
         // 就去对比：本期支付比例+其他期支付比例
        //   是否大于最大支付比例
        compareRowUnpayRatio(row, 1)
        //计算总计量金额
        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
    })
}

//判断是否红色
const isCanSave = ref(false)

const addTableRowStyle = ({ row }) => {
    console.log(row, 'xuan')
    //本期支付比例+其他期支付比例
     //  是否大于最大支付比例
      const isComparedRa = compareRowUnpayRatio(row, 2)
        if (isComparedRa === 1 ) {
            isCanSave.value = true

            return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'


        } else {
            isCanSave.value = false

        }
    // 判断施工图数量是否大于合同数据
    //      大于：如果超计= 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 attachmentUploadChange = () => {
    const fileList = getArrValue(baseForm.value.fileList)
    ischangeByGetNode.value = false
    selectId.value = arrToKey(fileList, 'selectId', ',')
}

const attachMentDel = ({ file }, resolve)=>{
    const { selectId } = file
    if (selectId && baseForm.value.isAutoBuild === 1) {
        window.$message.warning('该文件不可删除')
        resolve(false)
    } else {
        resolve(true)
    }
}

//草图文件上传成功的回调
const pictureUploadSuccess = ({ res }, resolve) => {
    const { link, pdfUrl, originalName } = getObjValue(res.data)
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        resolve()
        return
    }
    baseForm.value.pictureUrl = link ?? ''
    baseForm.value.pictureName = originalName ?? ''
    resolve({
        fileName: originalName ?? '',
        filePdfUrl: pdfUrl ?? '',
        fileUrl:  link ?? '',
    })
    ischangeByGetNode.value = false
}

//附件上传成功的回调
const fileUploadSuccess = ({ res }, resolve) => {
    const { link, pdfUrl, originalName } = getObjValue(res.data)
    if (isNullES(pdfUrl)) {
        window.$message.warning('该文件不能生成pdf,请更换文件上传')
        resolve()
        return
    }
    resolve({
        contractId: cid.value,
        fileName: originalName ?? '',
        filePdfUrl: pdfUrl ?? '',
        fileUrl: link ?? '',
        fileType: 1,
    })
    ischangeByGetNode.value = false
}

//提交保存
const submitLoading = ref(false)
const submitData = async () => {
    submitLoading.value = true
    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('保存成功')
        return true
    } else {
        submitLoading.value = false
        window.$message.error(msg ?? '保存失败')
        return false
    }
}

//连续新增
const continuousOperation = () => {
    //处理数据
    if (dataId.value) {
        addModalClose()
    } else {
        //清空数据
        baseForm.value = { fileList: [], pictureUrl: '' }
        addTableData.value = []
        selectId.value = ''
        isComparedRaVal.value = null
        setStoreValue('checkRows', [])
        setBasePeriodForm(period_id.value)
        //树节点数据
        const treeData = treeItemData.value
        const { notExsitChild } = treeData
        isLastChild.value = notExsitChild
        nodeId.value = treeData.id
        baseForm.value.contractUnitId = treeData.id
        baseForm.value.fileList = []
        ischangeByGetNode.value = false
        getNodeDivide(treeData.id)
        getCurrentNodeAllFormData(treeData.id)
    }
}

//保存
const isSubmit = ref(false)
const addModalSave = async () => {
    const isValidate = await submitData()
    if (isValidate) {
        isSubmit.value = true
        continuousOperation()
        submitLoading.value = false
    }
}

//提交并关闭
const submitClose = async () => {
    const isValidate = await submitData()
    if (isValidate) {
        submitLoading.value = false
        addModalClose()
        emit('finish')
    }
}

//关闭弹窗
const addModalClose = () => {
    isShow.value = false
    baseForm.value = { fileList: [], pictureUrl: '' }
    addTableData.value = []
    selectId.value = ''
    isComparedRaVal.value = null
    setStoreValue('checkRows', [])
    emit('close')
    if (isSubmit.value) {
        emit('finish')
    }
}
//关联质检资料
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)=>{
    console.log(rows, 'rows')
    let fileList = []
    rows.forEach(ele => {
        const isPush = isArrIndex( baseForm.value.fileList, 'selectId', ele.selectId)
        if (!isPush) {
            if (!ele.evisaPdfUrl && !ele.pdfUrl) {
                window.$message.warning('该节点没有资料信息')
                return
            }
            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', ',')
   ischangeByGetNode.value = false

}
</script>
