<template>
    <div class="relative h-full flex">
        <div :id="`hc_tree_card_${uuid}`">
            <hc-new-card v-loading="treeLoaing" scrollbar>
                <hc-lazy-tree  
                    v-if="ishowTree"
                    :h-props="treeProps" 
                    is-load-menu
                    :auto-expand-keys="autoExpandKeys" 
                    tree-key="id" 
                    @load="treeLoadNode" 
                    @menu-tap="treeMenuTap" 
                    @node-tap="treeNodeTap" 
                    @load-menu="treeLoadMenu"
                />
            </hc-new-card>
        </div>
        <div :id="`hc_table_card_${uuid}`" class="flex-1">
            <hc-new-card scrollbar title="合同工程清单明细">
                <template #extra>
                    <el-button v-if="infoData?.isFormNode === 0" hc-btn type="primary" @click="addsupply">增补清单</el-button>
                    <el-button hc-btn type="primary" @click="leadModalShow = true">导入</el-button>
                    <el-button hc-btn type="primary">导出</el-button>
                </template>
                <div class="relative">
                    <infoTable1 v-if="isInfoView" :info-data="infoData" />
                    <template v-else>
                        <infoTable :info-data="infoData" />
                        <el-divider border-style="dashed">下级节点列表</el-divider>
                        <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" is-new :index-style="{ width: 60 }" />
                    </template>
                </div>
            </hc-new-card>
        </div>

        <!-- 节点数据 -->
        <hc-new-dialog v-model="treeModalShow" widths="1100px" :title="treeModalTitle" :loading="addNodeLoading" @save="treeModalSave">
            <div v-if="menuType === 'edit'" class="ml-5 text-orange font-400">温馨提示：如果合同清单已经计量或变更(包括零号变更) ，则不可修改单价和数量</div>
            <el-form ref="formRef" class="p-4" label-position="left" label-width="auto" :model="formModel" :rules="formRules">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="清单编号：" prop="formNumber">
                            <el-input v-model="formModel.formNumber" :disabled="infoData.citeStatus === 1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="清单名称：" prop="formName">
                            <el-input v-model="formModel.formName" :disabled="infoData.citeStatus === 1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位：">
                            <el-input v-model="formModel.unit" :disabled="infoData.citeStatus === 1" />
                        </el-form-item>
                    </el-col>
                    <!-- 新增 -->
                    <template v-if="menuType === 'add'">
                        <el-col :span="8">
                            <el-form-item label="清单节点：">
                                <el-select v-model="formModel.isFormNode" block @change="changeAddFormType">
                                    <el-option label="是" :value="1" />
                                    <el-option label="否" :value="0" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.isFormNode === 1" :span="8">
                            <el-form-item label="中标单价：" prop="bidPrice">
                                <el-input-number v-model="formModel.bidPrice" :disabled="formModel.isFormNode === 0" :controls="false" :min="0" class="w-100" />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="formModel.isFormNode === 1" :span="8">
                            <el-form-item label="合同数量：" prop="contractTotal">
                                <el-input-number v-if="formModel.isFormNode === 1" v-model="formModel.contractTotal" :disabled="formModel.isFormNode === 0" :controls="false" :min="0" class="w-100" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="章编号：" prop="chapterNumber">
                                <el-input v-model="formModel.chapterNumber" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="清单标识：">
                                <el-input v-model="formModel.formTag" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="清单类型：">
                                <el-select v-model="formModel.formType" block placeholder="请选择">
                                    <el-option v-for="item in formtypeOptions" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <!-- 修改和清单 -->
                    <template v-if="menuType === 'edit' && formModel.isFormNode === 1">
                        <el-col :span="8">
                            <el-form-item label="中标单价：" prop="bidPrice">
                                <el-input v-model="formModel.bidPrice" :disabled="infoData.citeStatus === 1" @change="changeBidPrice" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="现行单价：">
                                <el-input v-model="formModel.currentPrice" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="变更后单价：">
                                <el-input v-model="formModel.changePrice" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="合同数量：" prop="contractTotal">
                                <el-input v-model="formModel.contractTotal" :disabled="infoData.citeStatus === 1" @change="changeContractTotal" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="变更后数量：">
                                <el-input v-model="formModel.changeTotal" disabled />
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="8">
                            <el-form-item label="章编号：">
                                <el-input v-model="formModel.chapterNumber" :disabled="treeItem.nodeTier !== 0" />
                            </el-form-item>
                        </el-col> -->
                    </template>
                    <!-- 修改和非清单 -->
                    <template v-if="menuType === 'edit'">
                        <el-col :span="8">
                            <el-form-item label="合同金额：">
                                <el-input v-model="formModel.contractMoney" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="变更后金额：">
                                <el-input v-model="formModel.changeMoney" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="清单标识：">
                                <el-input v-model="formModel.formTag" :disabled="infoData.citeStatus === 1" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="是否清单节点：">
                                <el-select v-if="treeItem.isFormNode === 0" v-model="formModel.isFormNode" block :disabled="infoData.citeStatus === 1" @change="FchangeIsForm">
                                    <el-option label="是" :value="1" />
                                    <el-option label="否" :value="0" />
                                </el-select>
                                <el-select v-if="treeItem.isFormNode === 1" v-model="formModel.isFormNode" block :disabled="infoData.citeStatus === 1" @click="IchangeIsForm">
                                    <el-option label="是" :value="1" />
                                    <el-option label="否" :value="0" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </template>
                    <el-col v-if="menuType === 'edit'" :span="8">
                        <el-form-item label="清单类型：">
                            <el-select v-model="formModel.formType" block placeholder="请选择" :disabled="treeItem.nodeTier !== 0 || infoData.citeStatus === 1">
                                <el-option v-for="item in formtypeOptions" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="menuType === 'edit'" :span="8">
                        <el-form-item label="章编号：">
                            <el-input v-model="formModel.chapterNumber" :disabled="treeItem.nodeTier !== 0 || infoData.citeStatus === 1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <el-input v-model="formModel.remark" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" :disabled="infoData.citeStatus === 1" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </hc-new-dialog>

        <!-- 导入清单 -->
        <hc-new-dialog v-model="leadModalShow" scrollbar widths="1100px" title="合同工程清单导入" @save="leadModalSave">
            <div class="hc-el-upload-drag">
                <el-upload
                    ref="leadUploadRef" hc drag :show-file-list="true" :auto-upload="false" :headers="getHeader()"
                    action="/api/blade-meter/contractInventoryForm/importExcel" :data="leadUploadData" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              
                    :on-success="handleFileDUcess"
                >
                    <div class="hc-ui-upload-btn">
                        <div class="hc-uploader-drop">
                            <div class="upload-icon">
                                <HcIcon name="upload-cloud" />
                            </div>
                            <div class="text">将文件拖动到此处，或点击上传</div>
                        </div>
                        <div class="hc-uploader-accept">支持的文件格式： Excel(xls、xlsx)</div>
                    </div>
                </el-upload>
            </div>
            <hc-title>
                <span>范例模板</span>
                <template #extra>
                    <el-link type="primary" @click="downLoadExel">下载范例模板.xls</el-link>
                </template>
            </hc-title>
            <el-table :data="tableLeadData" style="width: 100%;" row-key="id" border>
                <el-table-column prop="k1" label="导入编号" width="90" />
                <el-table-column prop="k2" label="清单编号" width="90" />
                <el-table-column prop="k3" label="清单名称" />
                <el-table-column prop="k4" label="单位" width="80" />
                <el-table-column prop="k5" label="合同数量" width="90" />
                <el-table-column prop="k6" label="中标单价" width="90" />
                <el-table-column prop="k7" label="清单类型" width="90" />
                <el-table-column prop="k8" label="章编号" width="80" />
                <el-table-column prop="k9" label="备注" width="90" />
            </el-table>
            <div class="mt-4 text-orange">特别提示：清单类型分为：1、普通清单，2、计日工清单，3、暂定金清单，请填写具体数字对应</div>
        </hc-new-dialog>

        <!-- 增补清单 -->
        <hc-new-dialog v-model="supplementsModalShow" widths="1100px" title="增补清单" :loading="supplementLoading" @save="supplementsModalSave">
            <el-form ref="supplementsFormRef" class="p-4" label-position="left" label-width="auto" :model="supplementsFormModel" :rules="supplementsFormRules">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="清单编号：" prop="formNumber">
                            <el-input v-model="supplementsFormModel.formNumber" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="清单名称：" prop="formName">
                            <el-input v-model="supplementsFormModel.formName" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位：">
                            <el-input v-model="supplementsFormModel.unit" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="现行单价：" prop="currentPrice">
                            <el-input v-model="supplementsFormModel.currentPrice" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="清单类型：">
                            <el-select v-model="supplementsFormModel.formType" block placeholder="请选择">
                                <el-option v-for="item in formtypeOptions" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="章编号：">
                            <el-input v-model="supplementsFormModel.chapterNumber" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="清单节点：">
                            <el-select v-model="supplementsFormModel.isFormNode" disabled block>
                                <el-option label="是" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="增补清单：">
                            <el-select v-model="supplementsFormModel.isSupplement" disabled block>
                                <el-option label="是" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="清单标识：">
                            <el-input v-model="supplementsFormModel.formTag" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <el-input v-model="supplementsFormModel.remark" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </hc-new-dialog>

        <!-- 调整排序 -->
        <hc-new-dialog v-model="sortModalShow" is-table widths="1100px" title="调整排序" :loading="sortNodeLoading" @save="sortModalSave">
            <hc-table
                ui="hc-table-row-drop"
                :column="sortTableColumn" :datas="sortTableData" :loading="sortTableLoading"
                is-row-drop quick-sort is-new :index-style="{ width: 80 }"
                @row-drop="sortTableRowDrop" @row-sort="sortTableRowDrop"
            >
                <template #formName="{ row }">
                    <span class="text-link">{{ row?.formName }}</span>
                </template>
                <template #action="{ row, index }">
                    <span class="text-link text-xl" @click="upSortClick(row, index)">
                        <HcIcon name="arrow-up" fill />
                    </span>
                    <span class="text-link ml-2 text-xl" @click="downSortClick(row, index)">
                        <HcIcon name="arrow-down" fill />
                    </span>
                </template>
            </hc-table>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { arrToId, formValidate, getArrValue, getObjValue, getRandom, isNullES } from 'js-fast-way'
import { getHeader } from 'hc-vue3-ui'
import { useAppStore } from '~src/store'
import infoTable from './components/check-list/info-table.vue'
import infoTable1 from './components/check-list/info-table1.vue'
import { addNode, deleteNode, getDetail, getImportTemplate, getLazyFormTree, lockNode, sortForm, updateForm } from '~api/project/debit/contract/check-list.js'
import { getDictionary } from '~api/other'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { delMessageV2 } from '~com/message/index.js'
import { isNumberReg } from '~uti/tools'
import BigNumber from 'bignumber.js'

//变量
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
defineOptions({
    name: 'ProjectDebitContractList',
})

const uuid = getRandom(4)

//渲染完成
onMounted(() => {
    setSplitRef()
   
    getFormType()
  
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    })
}
//获取表但类型数据
const formtypeOptions = ref([])
const getFormType = async () => {
    const { data } = await getDictionary({
        code: 'meter_form_type',
    })
    formtypeOptions.value = getArrValue(data)
    formtypeOptions.value.forEach((ele)=>{
        ele.dictKey = Number(ele.dictKey)
    })
}
//搜索表单
const searchForm = ref({})

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: function (data) {
          return !data.hasChild
    },
}
const ishowTree = ref(true)

//自动展开缓存
const autoExpandKeys = ref(getStoreValue('autoExpandKeys') || [])
//获取树的数据

const treeLoaing = ref(false)
//懒加载的数据
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { error, code, data } = await getLazyFormTree({
        projectId: projectId.value,
        parentId:id,
        contractId:contractId.value,
    })

    resolve(getArrValue(data))
}

//树被点击
const isInfoView = ref(false)

const treeNodeTap = ({ node, data, keys }) => {
    isInfoView.value = !!node.isLeaf
    treeItem.value = data
    autoExpandKeys.value = keys || []
    getTreeNodeDetail(data)
    setStoreValue('autoExpandKeys', keys)
}
const infoData = ref({})
//获取节点详情
const getTreeNodeDetail = async (node)=>{
    const { id } = node
    const { error, code, data } = await getDetail({
       id,
    })

    if (!error && code === 200) {
        infoData.value = getObjValue(data)
        tableData.value = infoData.value['list']
   
    } else {
        infoData.value = {}
        tableData.value = []
    }
}
//菜单
const treeLoadMenu = ({ item, level }, resolve) => {
    const { isLock } = item
    if (level === 1) {
        if (isLock === 1) {
                return resolve([
                    { icon: 'lock', label: '解锁', key: 'lock' },
                    { icon: 'add', label: '新增', key: 'add' },
                    { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
                ])
        } else {
            return resolve([
                    { icon: 'lock', label: '锁定', key: 'lock' },
                    { icon: 'add', label: '新增', key: 'add' },
                    { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
            ])
        }
       
    } else {
        if (isLock === 1) {
            return resolve([
                { icon: 'lock', label: '解锁', key: 'lock' },
                { icon: 'add', label: '新增', key: 'add' },
                { icon: 'pencil', label: '修改', key: 'edit' },
                { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
                { icon: 'close', label: '删除', key: 'del' },
            ])
        } else {
            return resolve([
                { icon: 'lock', label: '锁定', key: 'lock' },
                { icon: 'add', label: '新增', key: 'add' },
                { icon: 'pencil', label: '修改', key: 'edit' },
                { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
                { icon: 'close', label: '删除', key: 'del' },
            ])
        }
    }
}


const menuType = ref('')
const treeItem = ref({})
const treeMenuTap = ({ key, data, node }) => {
    treeItem.value = data
    if (data?.isLock !== 1) {
        if (key === 'add') {
            menuType.value = 'add'
            treeModalTitle.value = '新增合同工程清单'
            const { isFormNode } = data
            if (isFormNode === 1) {
                window.$message.warning('非清单节点才可新增下级清单节点')
                return
            }
            treeModalShow.value = true
            infoData.value.citeStatus = null
            formModel.value = {
                isFormNode:0,
                formType:data?.formType,
                chapterNumber:data?.chapterNumber,
                contractId:contractId.value,
                projectId:projectId.value,
                parentId:data.id,
            }
        }
        if (key === 'edit') {
            menuType.value = 'edit'
            treeModalTitle.value = data.formName + ' - 修改合同工程清单'
            treeModalShow.value = true
            // formModel.value = data
            getTreeNodeDetail(data)
            formModel.value = infoData.value
        }
        if (key === 'sort') {
            let nodes = [], childNodes = []
            childNodes = node?.parent?.childNodes || node?.parent?.children || []
            
            for (let i = 0; i < childNodes.length; i++) {
                const res = childNodes[i]?.data
                nodes.push({
                    formName:res?.formName,
                    id:res?.id,
                })
            }
            sortTableData.value = nodes
            sortModalShow.value = true
            // sortTableData.value = data.children
        }
        if (key === 'del') {
            delModalClick()
        }
    } 
    if (data?.isLock === 1 && key !== 'lock') {
        window.$message.warning('当前节点为锁定状态，不允许操作')
    }
   
    if (key === 'lock') {
        handleLockNode()
    }
}
//、新增修改是否为清单节点限制
const changeAddFormType = (val)=>{
    const { isFormNode } = treeItem.value
    if (isFormNode === 1 && val === 1) {
        window.$message.warning('非清单节点才可新增下级清单节点')
    }
}
//修改非清单节点是否为清单节点限制
const FchangeIsForm = (val)=>{
    const { hasChild } = treeItem.value
    const { citeStatus } = infoData.value
  
    if (hasChild && val === 1) {
        window.$message.warning('该节点下面存在子节点，不允许修改为清单节点')
        formModel.value.isFormNode = 0
        
    }
    if (citeStatus && val === 0) {
        window.$message.warning('当前前清单已经被计量引用，不允许修改为非清单节点')
        formModel.value.isFormNode = 1
        
    }
}
//修改清单节点是否为清单节点限制
const IchangeIsForm = (val)=>{
    const { citeStatus } = treeItem.value
    if (citeStatus && val === 0) {
        window.$message.warning('当前清单已经被计量引用，则不允许修改为非清单节点')
        formModel.value.isFormNode = 1
        
    }
}
//删除节点
const delModalClick = () => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeContractTreeNode()
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
}
const removeContractTreeNode = async () => {
    const loadingInstance = window.$loading.service({
        fullscreen: true,
        text: '删除节点中，请耐心等待...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const { error, code } = await deleteNode({
        id: treeItem.value.id || '',
        contractId:contractId.value,
    })
    loadingInstance.close()
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload() //刷新页面
    }
}
//锁定节点
const handleLockNode = async ()=>{
    const { error, code, msg } = await lockNode({
        id: treeItem.value.id || '',
        contractId:contractId.value,
        status:treeItem.value?.isLock,
    })
    if (!error && code === 200) {
        window?.$message?.success(msg)
        window?.location?.reload() //刷新页面
    }
}
//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'formNumber', name: '清单编号' },
    { key: 'formName', name: '清单名称' },
    { key: 'unit', name: '单位' },
    { key: 'currentPrice', name: '现行单价' },
    { key: 'contractTotal', name: '合同数量' },
    { key: 'contractMoney', name: '合同金额' },
    { key: 'changePrice', name: '变更后单价' },
    { key: 'changeTotal', name: '变更后数量' },
    { key: 'changeMoney', name: '变更后金额' },
    { key: 'isSupplementName', name: '是否增补' },
])
const tableData = ref([])

//弹窗
const treeModalShow = ref(false)
const treeModalTitle = ref('')

//弹窗表单
const formRef = ref(null)
const formModel = ref({})
const formRules = ref({
    
    formNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入清单编号',
    },
    formName: {
        required: true,
        trigger: 'blur',
        message: '请输入清单名称',
    },
    chapterNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入章编号',
    },
    bidPrice: {
        required: true,
        trigger: 'blur',
        message: '请输入中标单价',
    },
    contractTotal: {
        required: true,
        trigger: 'blur',
        message: '请输入合同数量',
    },
    
})
const addNodeLoading = ref(false)
//弹窗保存
const treeModalSave = async () => {
    console.log(formModel.value, 'form')
    console.log(menuType.value, 'val')
    const res = await formValidate(formRef.value)
    if (res) {
        if (menuType.value === 'add') {
            const { error, code } = await addNode({
                ...formModel.value,
                isSupplement:0,
            })
            //判断状态
            addNodeLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success('新增成功')
                treeModalShow.value = false
                window?.location?.reload() //刷新页面
            }
        } else if (menuType.value === 'edit') {
            const { error, code } = await updateForm({
                ...formModel.value,
                isSupplement:0,
            })
            //判断状态
            addNodeLoading.value = false
            if (!error && code === 200) {
                window?.$message?.success('修改成功')
                treeModalShow.value = false
                window?.location?.reload() //刷新页面
            }
        }
    }
   
}

//合同工程清单导入
const leadModalShow = ref(false)
const leadUploadRef = ref(null)
const leadUploadData = ref({
    projectId:projectId.value,
    contractId:contractId.value,
})
const handleFileDUcess = (res)=>{
    const { data } = res
    window.$message.success(data)
}
const tableLeadData = ref([
    { id: 1, k1: '100', k2: '100', k3: '总则', k4: '', k5: '', k6: '', k7: '1', k8: '100', k9: '' },
    { id: 2, k1: '101-1', k2: '101-1', k3: '保险费', k4: '', k5: '', k6: '', k7: '1', k8: '100', k9: '' },
    { id: 3, k1: '101-1a', k2: '101-1a', k3: '按合同条款规定，提供建筑工程一切险', k4: '总额', k5: '27', k6: '1.2', k7: '1', k8: '100', k9: '' },
    { id: 4, k1: '101-1b', k2: '101-1b', k3: '按合同条款规定，提供建筑工程一切险', k4: '总额', k5: '20', k6: '3', k7: '1', k8: '100', k9: '' },
    { id: 5, k1: '101-1c', k2: '101-1c', k3: '按合同条款规定，提供建筑工程一切险', k4: '总额', k5: '12', k6: '3.9', k7: '1', k8: '100', k9: '' },
])

const leadModalSave = async () => {
    await leadUploadRef.value.submit()
    leadModalShow.value = false
    ishowTree.value = false
    setTimeout(() => {
        ishowTree.value = true
    }, 1000)
}

//增补清单表单
const supplementsModalShow = ref(false)
const supplementsFormRef = ref(null)
const supplementsFormModel = ref({})
const supplementsFormRules = ref({
    formNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入清单编号',
    },
    formName: {
        required: true,
        trigger: 'blur',
        message: '请输入清单名称',
    },
    chapterNumber: {
        required: true,
        trigger: 'blur',
        message: '请输入章编号',
    },
    currentPrice:{
        required: true,
        trigger: 'blur',
        message: '请输入现行单价',
    },
})
const supplementLoading = ref(false)
const addsupply = ()=>{
    supplementsFormModel.value = {
        isFormNode:1,
        isSupplement:1,
        chapterNumber:treeItem.value?.chapterNumber,
        formType:treeItem.value?.formType,
  
    }
    supplementsModalShow.value = true
}
const supplementsModalSave = async () => {
    supplementsFormModel.value.isSupplement = 1
    console.log(supplementsFormModel.value, 'val')
    const res = await formValidate(supplementsFormRef.value)
    if (res) {
       
        const { error, code } = await addNode({
            ...supplementsFormModel.value,
            isSupplement:1,
            parentId:treeItem.value?.id || '',
            contractId:contractId.value,
            projectId:projectId.value,
        })
        //判断状态
        supplementLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('新增成功')
            supplementsModalShow.value = false
            window?.location?.reload() //刷新页面
        }
    }
    
}

//调整排序
const sortModalShow = ref(false)
//表格数据
const sortTableColumn = ref([
    { key:'formName', name: '节点名称' },
    { key:'action', name: '排序', width: 90 },
])
const sortTableLoading = ref(false)
const sortTableData = ref([])
//拖动完成
const sortTableRowDrop = (rows) => {
    sortTableData.value = [] // 先清空，否则排序会异常
    nextTick(() => {
        sortTableData.value = rows
    })
}

//向下
const downSortClick = (row, index) => {
    const indexs = index + 1
    const data = sortTableData.value
    if (indexs !== data.length) {
        const tmp = data.splice(indexs, 1)
        sortTableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}

//向上
const upSortClick = (row, index) => {
    const data = sortTableData.value || []
    if (index !== 0) {
        const tmp = data.splice(index - 1, 1)
        sortTableData.value.splice(index, 0, tmp[0])
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}
const sortNodeLoading = ref(false)
const sortModalSave = async () => {
    const ids = arrToId(sortTableData.value)
  //发起请求
  sortNodeLoading.value = true
    const { error, code } = await sortForm({ ids })
    sortNodeLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortModalShow.value = false
        window?.location?.reload() //刷新页面
    }
   
}
//下载范例模板
const downLoadExel = async ()=>{
    const { error, code, data, msg } = await getImportTemplate()
    //判断状态
    if (!error && code === 200) {
        if (data) {
            window.open(data, '_blank')
        } else {
            window.$message.warning(msg)
        }
       
    }
}
//修改中标单价
const changeBidPrice = (val)=>{
     //如果为空
     let money = val
    const isMeter = isNumberReg(money)
    if (isNullES(money) || !isMeter) {
        money = 0
        formModel.value.bidPrice = money
    }
    formModel.value.currentPrice = money
    formModel.value.changePrice = money
    //计算计量金额
    formModel.value.contractMoney = (BigNumber(money).multipliedBy(formModel.value.contractTotal)).toString()
    formModel.value.changeMoney = (BigNumber(money).multipliedBy(formModel.value.contractTotal)).toString()
}
const changeContractTotal = (val)=>{
         //如果为空
     let total = val
    const isMeter = isNumberReg(total)
    if (isNullES(total) || !isMeter) {
        total = 0
        formModel.value.contractTotal = total
    }
    formModel.value.changeTotal = total
    formModel.value.contractMoney = (BigNumber(total).multipliedBy(formModel.value.bidPrice)).toString()
    formModel.value.changeMoney = (BigNumber(total).multipliedBy(formModel.value.bidPrice)).toString()
    
}
</script>
