<template>
    <div class="relative h-full flex">
        <div :id="`hc_tree_card_${uuid}`">
            <hc-new-card scrollbar>
                <template #header>
                    <div class="w-full flex justify-between">
                        <el-button hc-btn type="primary" :loading="setLoading" @click="setTree">重新设置treeCode</el-button>
                        <el-button hc-btn type="primary" :loading="linkLoading" @click="linkDataClick(1)">关联资料</el-button>
                    </div>
                </template>
                <hc-lazy-tree
                    v-if="ishowTree"
                    :auto-expand-keys="TreeAutoExpandKeys"
                    tree-key="id"
                    :h-props="treeProps"
                    is-load-menu
                    @load="treeLoadNode"
                    @load-menu="treeLoadMenu"
                    @menu-tap="treeMenuTap"
                    @node-tap="treeNodeTap"
                />
            </hc-new-card>
        </div>
        <div :id="`hc_table_card_${uuid}`" class="flex-1">
            <hc-new-card scrollbar title="合同计量单元">
                <template #extra>
                    <el-button hc-btn type="primary" @click="editModalShow = true">修改</el-button>
                    <el-button hc-btn type="danger">删除</el-button>
                    <el-button hc-btn type="warning" @click="treeModalShow = true">增补单元</el-button>
                    <el-button hc-btn type="success" @click="leadModal">导入</el-button>
                </template>
                <div class="relative">
                    <infoTable :info-data="curTreeData" />
                    <HcTitle title="清单分解汇总列表">
                        <template #extra>
                            <div class="text-sm text-orange">温馨提示：累计分解量 > 合同变更后量，整行文字红色</div>
                        </template>
                    </HcTitle>
                    <div style="height: calc(50vh - 210px);">
                        <hc-table
                            :is-stripe="false" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                            is-new :index-style="{ width: 60 }" :row-style="tableRowStyle"
                        >
                            <template #key1="{ row }">
                                <i class="i-iconoir-open-select-hand-gesture inline-block" />
                            </template>
                        </hc-table>
                    </div>
                    <HcTitle title="质检关联清单">
                        <template #extra>
                            <el-button hc-btn type="primary" @click="linkDataClick(2)">关联</el-button>
                            <el-button hc-btn type="primary" :loading="batchCancleload" :disabled="cancelKeys.length == 0" @click="batchCancle">批量取消</el-button>
                        </template>
                    </HcTitle>
                    <div style="height: calc(50vh - 250px);">
                        <hc-table
                            :is-stripe="false" :column="qualtableColumn" :datas="qualtableData" :loading="tableLoading"
                            is-new :index-style="{ width: 60 }" 
                            is-check @selection-change="tableSelectionChange"
                        >
                            <template #appStatusName="{ row }">
                                <el-tag
                                    v-if="row.appStatusName"
                                    :type="`${row.appStatusName === '已审批' ? 'success' : row.appStatusName === '已填报-待审批' ? 'warning' : row.appStatusName === '已填报-未上报' ? 'primary' : 'info'}`"
                                    class="mx-1" effect="dark"
                                >
                                    {{ row.appStatusName }}
                                </el-tag>
                            </template>
                            <template #action="{ row }">
                                <el-button hc-btn type="primary" size="small" :loading="row?.load" @click="cancleLink(row)">取消关联</el-button>
                            </template>
                        </hc-table>
                    </div>
                </div>
            </hc-new-card>
        </div>

        <!-- 节点新增和编辑 -->
        <treeForm
            v-model="treeModalShow" :ids="curTreeData.id" :menu-type="menuType"
            :template-id="curTreeData.templateId" @finish="finishForm"
        />

        <!-- 修改合同计量单元 -->
        <rowData
            v-model="editModalShow" :is-table="isInfoView" :ids="curTreeData.id" :cur-tree-data="curTreeData"
            @finish="finishEdit" @close="closeEdit" @get-detail="getTreeNodeDetail"
        />

        <!-- 调整排序 -->
        <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 #key2="{ row }">
                    <span class="text-link">{{ row?.key2 }}</span>
                </template>
                <template #action="{ index }">
                    <span class="text-link text-xl" @click="upSortClick(index)">
                        <HcIcon name="arrow-up" fill />
                    </span>
                    <span class="text-link ml-2 text-xl" @click="downSortClick(index)">
                        <HcIcon name="arrow-down" fill />
                    </span>
                </template>
            </hc-table>
        </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/tree/contract/import" :data="{ id: checkTreeId, type: typevalue }" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                    :on-error="handFileError"
                    :on-success="handleFileDUcess"
                    :disabled="!typevalue"
                    @click="beforeUpload"
                >
                    <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>
                    <span style="color: red;">*</span> 切换范例模板：
                    <el-select
                        v-model="typevalue"
                        placeholder="请选择"
                        style="width: 240px"
                        clearable
                    >
                        <el-option
                            v-for="item in typeoptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <el-link type="primary" @click="downLoadExel">下载范例模板.xls</el-link>
                </template>
            </hc-title>
            <el-table v-if="typevalue === '2'" :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="清单编号" width="90" />
                <el-table-column prop="k4" label="工程名称" />
                <el-table-column prop="k5" label="施工图数量" width="100" />
                <el-table-column prop="k6" label="合同图号" width="90" />
                <el-table-column prop="k7" label="备注" />
            </el-table>
            <el-table v-if="typevalue === '1'" :data="tableLeadData1" style="width: 100%;" row-key="id" border>
                <el-table-column prop="k1" label="桩号支付编号" />
                <el-table-column prop="k2" label="图号" />
                <el-table-column prop="k3" label="403-1-1" />
                <el-table-column prop="k4" label="403-1-2" />
                <el-table-column prop="k5" label="403-1-3" />
                <el-table-column prop="k6" label="404-1-4" />
                <el-table-column prop="k7" label="清单编号..." />
                <el-table-column prop="k8" label="备注" />
            </el-table>
            <div v-if="typevalue === '1'" class="mt-3 text-orange font-400">温馨提示：清单编号需手动填写，清单编号列填写施工图数量，若有关联则填写数字，反之保留空白</div>
        </hc-new-dialog>
        <!-- 
        关联资料 -->
        <linkData :link-modal="linkModal" :is-check-id="isCheckId" :check-ids="checkTreeId" :right-tree-check="rightTreeCheck" @close="closeLink" @save="saveLink" />
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { arrToId, arrToKey, getArrValue, getObjValue, getRandom } from 'js-fast-way'
import infoTable from './components/unit/info-table.vue'
import treeForm from './components/unit/tree-form.vue'
import rowData from './components/unit/row-data.vue'
import unitApi from '~api/project/debit/contract/unit.js'
import linkData from './components/unit/link-data.vue'
import { useAppStore } from '~src/store'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { delMessageV2 } from '~com/message/index.js'
import { getDictionary } from '~api/other'
import BigNumber from 'bignumber.js'
import { getHeader } from 'hc-vue3-ui'


const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')
defineOptions({
    name: 'ProjectDebitContractUnit',
})

const uuid = getRandom(4)

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

//初始化设置拖动分割线
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 nodeOptions = ref([])
const getNodeType = async (id) => {
    const { data } = await unitApi.getNodeTypeList({
        id,
    })
    nodeOptions.value = getArrValue(data)
    nodeOptions.value.forEach((ele) => {
        ele.dictKey = Number(ele.dictKey)
    })
}
//搜索表单
const searchForm = ref({})

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}
const ishowTree = ref(true)
//重新设置树
const setLoading = ref(false)
const setTree = async () => {
    setLoading.value = true
    const { error, code, msg } = await unitApi.refresh({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    setLoading.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        ishowTree.value = false
        setTimeout(() => {
            ishowTree.value = true
        }, 100)
    } else {
       window.$message.error(msg)
    }
}
//懒加载的数据
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
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 unitApi.lazyTree({
        contractId: contractId.value,
        id: id,
    })

    resolve(getArrValue(data))
}

//节点点击
const isInfoView = ref(false)
const checkTreeId = ref('')
const checkTreeLevel = ref('')
const treeNodeTap = ({ node, data, keys }) => {
    treeClickdata.value = data
  
    const { level } = node
    checkTreeLevel.value = level
    checkTreeId.value = data.id

    getNodeType(data.id)
    isInfoView.value = node.isLeaf
    TreeAutoExpandKeys.value = keys || []
    setStoreValue('wbsTreeExpandKeys', keys)
    getTreeNodeDetail(data)
}

//获取节点详情
//选中的节点数组
const rightTreeCheck = ref([])
const curTreeData = ref({})
const getTreeNodeDetail = async ({ id }) => {
    const { error, code, data } = await unitApi.getNodeDetail({ id })
    if (!error && code === 200) {
        curTreeData.value = getObjValue(data)
        tableData.value = curTreeData.value['decompositionList']
        qualtableData.value = curTreeData.value['linkNodeList']
        rightTreeCheck.value = arrToKey(qualtableData.value, 'wbsTreeId', ',').split(',')
        nodeOptions.value.forEach((ele) => {
            if (curTreeData.value.nodeType === ele.dictKey) {
                curTreeData.value.nodeTypeName = ele.dictValue
            }
        })
    } else {
        curTreeData.value = {}
        tableData.value = []
        qualtableData.value = []
    }
}

//菜单
const treeLoadMenu = ({ item, level }, resolve) => {
    const { isLock } = item
    if (level === 1) {
        if (isLock === 1) {
            return resolve([
                { icon: 'lock', label: '解锁', key: 'lock' },
                { icon: 'upload-cloud', label: '导入', key: 'lead' },
                { icon: 'add', label: '新增', key: 'add' },
                { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
            ])
        } else {
            return resolve([
                { icon: 'lock', label: '锁定', key: 'lock' },
                { icon: 'upload-cloud', label: '导入', key: 'lead' },
                { 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: 'upload-cloud', label: '导入', key: 'lead' },
                { 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: 'upload-cloud', label: '导入', key: 'lead' },
                { 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 treeClickdata = ref()
const treeMenuTap = ({ key, node, data, keys }) => {
    const { isDecompositionData } = data
    isInfoView.value = node.isLeaf
    menuType.value = key
    getTreeNodeDetail(data)

    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    if (data?.isLock !== 1) {
        if (key === 'add') {
            if (isDecompositionData === 1) {
                window.$message.warning('该节点下面不允许新增节点')

            } else {
                treeModalShow.value = true
            }

        }
        if (key === 'edit') {
            editModalShow.value = true
        }
        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({
                    nodeName: res?.nodeName,
                    id: res?.id,
                })
            }
            sortTableData.value = nodes
            sortModalShow.value = true
        }
        if (key === 'del') {
            delModalClick()
        }
    }
    if (data?.isLock === 1 && key !== 'lock') {
        window.$message.warning('当前节点为锁定状态，不允许操作')
    }

    if (key === 'lock') {
        handleLockNode()
    }
}
//锁定节点
const handleLockNode = async () => {
    const { error, code, msg } = await unitApi.getLock({
        id: curTreeData.value.id || '',
        lockStatus: curTreeData.value?.isLock === 1 ? 0 : 1,
    })
    if (!error && code === 200) {
        window?.$message?.success(msg)
        window?.location?.reload() //刷新页面
    }
}
//删除节点
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, msg } = await unitApi.deleteNode({
        id: curTreeData.value.id || '',
    })
    loadingInstance.close()
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload() //刷新页面
    } else {
        window.$message.error(msg)
     }
}
//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'key1', name: '分解明细', width: 80, align: 'center' },
    { key: 'formNumber', name: '清单编号', width: 120, align: 'center' },
    { key: 'formName', name: '清单名称', align: 'center' },
    { key: 'currentPrice', name: '单价', width: 90, align: 'center' },
    { key: 'contractTotal', name: '合同数量', width: 100, align: 'center' },
    { key: 'changeTotal', name: '变更后数量', width: 110, align: 'center' },
    { key: 'buildPictureTotal', name: '施工图数量', align: 'center' },
    { key: 'changeBuildPictureTotal', name: '施工图变更后数量', align: 'center' },
])
const tableData = ref([])
//质检关联清单
const qualtableColumn = ref([
    { key: 'part', name: '分/子分项部位', align: 'center' },
    { key: 'appStatusName', name: '审核状态', align: 'center' },
    { key: 'action', name: '操作', align: 'center' },
 
])
const qualtableData = ref([])
const cancelKeys = ref('')
//多选事件
const tableSelectionChange = (rows) => {
    console.log(rows)
    cancelKeys.value = arrToKey(rows, 'id', ',')
}
//设置某一行的样式
const tableRowStyle = ({ row }) => {
    let residueNum = new BigNumber(row.residueNum) //a
    let contract = new BigNumber('0') //b
    //a 大于 b = 1，a 等于 b = 0，a 小于 b = -1， a 或 b 的值异常时 = null
    const isCompared = residueNum.comparedTo(contract)
    if (isCompared === -1 || isCompared === null) {
        return '--el-table-tr-bg-color: #fe0000; --el-table-row-hover-bg-color: #fe0000; color: white;'
    }
}

//弹窗
const treeModalShow = ref(false)
const editModalShow = ref(false)
const finishForm = () => {
    treeModalShow.value = false
    ishowTree.value = false
    setTimeout(() => {
        ishowTree.value = true
    }, 100)
}

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

//向下
const downSortClick = (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 = (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, msg } = await unitApi.sortForm({ ids })
    sortNodeLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortModalShow.value = false
        window?.location?.reload() //刷新页面
    } else {
         window.$message.error(msg)
     }
}
//合同计量单元导入
const leadModalShow = ref(false)
const leadUploadRef = ref(null)

const leadModal = ()=>{
    if (!checkTreeId.value) {
        window.$message.warning('请先选择左侧节点')
        return
    }
    // if (checkTreeLevel.value > 3) {
    //     window.$message.warning('只能从前三层节点开始导入，操作失败')
    //     return
    // }
    leadModalShow.value = true
}
const handleFileDUcess = (res)=>{
    const { msg, code } = res
    if ( code === 200) {
        window?.$message?.success(msg)
     } else {
        window.$message.warning(msg)
     }

}
const beforeUpload = ()=>{
    if (!typevalue.value) {
        window.$message.warning('请先选择模板')
        return
    
    }
}
const handFileError = (err)=>{
    const msg = JSON.parse(err.message).msg
    window.$message.warning(msg)

}
const tableLeadData = ref([
    { id: 1, k1: '100', k2: '100-1', k3: '', k4: 'K01+000~K015+000(举例本标段里程号)', k5: '', k6: '', k7: '' },
    { id: 2, k1: '100', k2: '100-1', k3: '101-1a', k4: '按合同条款规定，提供建筑工程一切险', k5: '5', k6: '', k7: '' },
    { id: 3, k1: '100', k2: '100-1', k3: '101-1b', k4: '线外供电干线设施', k5: '3', k6: '', k7: '' },
    { id: 4, k1: '200', k2: '100-2', k3: '', k4: 'K01+000~K015+000(举例本标段里程桩号)', k5: '', k6: '', k7: '' },
    { id: 5, k1: '200', k2: '100-2', k3: '200-2-a', k4: '按合同条款规定，提供建筑工程一切险', k5: '5', k6: '', k7: '' },
    { id: 6, k1: '200', k2: '100-2', k3: '200-2-b', k4: '线外供电干线设施', k5: '3', k6: '', k7: '' },
])
const tableLeadData1 = ref([
    { id: 1, k1: '0-A#桩基', k2: '', k3: '1', k4: '', k5: '1', k6: '1', k7: '1', k8:'' },
    { id: 2, k1: '0-A#桩基', k2: '', k3: '1', k4: '1', k5: '0', k6: '1', k7: '1', k8:'' },
    { id: 3, k1: '0-A#桩基', k2: '', k3: '', k4: '1', k5: '1', k6: '1', k7: '1', k8:'' },
   
])

const leadModalSave = async () => {
    await leadUploadRef.value.submit()
    leadModalShow.value = false
    ishowTree.value = false
    setTimeout(() => {
        ishowTree.value = true
    }, 1000)
}
//下载范例模板
const downLoadExel = ()=>{
  if (typevalue.value) {
    if (typevalue.value === '1') {
    window.open('https://blade-oss-chongqing.oss-cn-shenzhen.aliyuncs.com//upload/20240307/1430b65643615f80156ec328a9a09ff8.xlsx', '_blank')
   } else {
    window.open('https://bladex-chongqing-info.oss-cn-hangzhou.aliyuncs.com//upload/20240109/98addbf48d620030504b2cb03b1c24f5.xls', '_blank')
   }
  } else {
    window.$message.warning('请先选择模板')
  }
 
}
const typeoptions = ref([
{
    value: '1',
    label: '模板1',
  },
  {
    value: '2',
    label: '模板2',
  },
])
const typevalue = ref('')
//关联资料
const isCheckId = ref(1)
const linkLoading = ref(false)
const linkModal = ref(false)
const linkDataClick = (type)=>{
    linkModal.value = true
    isCheckId.value = type
}
const closeLink = ()=>{
    linkModal.value = false
    getTreeNodeDetail(treeClickdata.value)
}
const saveLink = ()=>{
    linkModal.value = false
    getTreeNodeDetail(treeClickdata.value)
}
const cancleLink = async (row)=>{
    row.load = true
    const { error, code, msg } = await unitApi.deleteLinkWbsTree({ ids:row.id })
    row.load = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success(msg)
        getTreeNodeDetail(treeClickdata.value)
    } else {
         window.$message.error(msg)
     }
}
const batchCancleload = ref(false)
const batchCancle = async ()=>{
    batchCancleload.value = true
    const { error, code, msg } = await unitApi.deleteLinkWbsTree({ ids:cancelKeys.value })
    batchCancleload.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success(msg)
        getTreeNodeDetail(treeClickdata.value)
    } else {
         window.$message.error(msg)
     }
}
</script>
