<template>
    <div class="relative h-full flex">
        <div :id="`hc_tree_card_${uuid}`">
            <hc-new-card scrollbar>
                <template #header>
                    <el-button hc-btn type="primary" :loading="setLoading" @click="setTree">重新设置treeCode</el-button>
                </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(100vh - 420px);">
                        <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>
                </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 }" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                    :on-error="handFileError"
                    :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="清单编号" 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>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { arrToId, 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 { 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 {
        // newlistdata.value = []
    }
}
//懒加载的数据
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 }) => {

    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 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']
        nodeOptions.value.forEach((ele) => {
            if (curTreeData.value.nodeType === ele.dictKey) {
                curTreeData.value.nodeTypeName = ele.dictValue
            }
        })
    } else {
        curTreeData.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: '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 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 } = await unitApi.deleteNode({
        id: curTreeData.value.id || '',
    })
    loadingInstance.close()
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload() //刷新页面
    }
}
//表格数据
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 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 } = await unitApi.sortForm({ ids })
    sortNodeLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortModalShow.value = false
        window?.location?.reload() //刷新页面
    }
}
//合同计量单元导入
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 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 leadModalSave = async () => {
    await leadUploadRef.value.submit()
    leadModalShow.value = false
    ishowTree.value = false
    setTimeout(() => {
        ishowTree.value = true
    }, 1000)
}
//下载范例模板
const downLoadExel = ()=>{
   window.open('https://bladex-chongqing-info.oss-cn-hangzhou.aliyuncs.com//upload/20240109/98addbf48d620030504b2cb03b1c24f5.xls', '_blank')
}
</script>
