<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" 
                    @loadMenu="treeLoadMenu" 
                    @menuTap="treeMenuTap"
                    @nodeTap="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">导入</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 :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" />

        <!-- 调整排序 -->
        <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>
    </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'
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 ()=>{
    const { error, code, msg } = await unitApi.refresh({
        projectId: projectId.value,
        contractId:contractId.value,
    })
    setLoading.value = false
    if (!error && code === 200) {
        window.$meaasge.sucess(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 treeNodeTap = ({ node, data, keys }) => {
    getNodeType(data.id)
    isInfoView.value = node.isLeaf
    TreeAutoExpandKeys.value = keys || []
    setStoreValue('wbsTreeExpandKeys', keys)
    getTreeNodeDetail(data)
}
//获取节点详情
const curTreeData = ref({})
const getTreeNodeDetail = async (node)=>{
    const { id } = node
    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 }) => {
    isInfoView.value = node.isLeaf
    menuType.value = key
    getTreeNodeDetail(data)
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    if (data?.isLock !== 1) {
        if (key === 'add') {
            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: 'poseNum', name: '施工图数量', align: 'center' },
    { key: 'changeTotal', name: '施工图变更后数量', align: 'center' },
])
const tableData = ref([

])
//设置某一行的样式
const tableRowStyle = ({ row, rowIndex }) => {
    if (row.poseNum > row.contractTotal) {
        return '--el-table-tr-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 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() //刷新页面
    }
}
</script>
