<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"
                    tree-key="id"
                    :h-props="treeProps"
                    :menus="treeMenus"
                    :root-menu="treeRootMenu"
                    :auto-expand-keys="TreeAutoExpandKeys"
                    @load="treeLoadNode"
                    @menu-tap="treeMenuTap"
                    @node-tap="wbsElTreeClick"
                />
            </hc-new-card>
        </div>
        <div :id="`hc_table_card_${uuid}`" class="flex-1">
            <hc-new-card>
                <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" is-new :index-style="{ width: 60 }" />
                <!-- <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template> -->
            </hc-new-card>
        </div>

        <!-- 节点数据 -->
        <hc-new-dialog v-model="treeModalShow" widths="500px" :title="treeModalTitle" :loading="addNodeLoading" @save="treeModalSave">
            <el-form ref="formRef" class="p-2" label-position="left" size="large" label-width="auto" :model="formModel" :rules="formRules">
                <el-form-item label="节点编码：">
                    <el-input v-model="formModel.nodeCode" />
                </el-form-item>
                <el-form-item label="节点名称：" prop="nodeName">
                    <el-input v-model="formModel.nodeName" />
                </el-form-item>
                <el-form-item label="节点类型：">
                    <el-select v-model="formModel.nodeType" block>
                        <el-option v-for="item in nodeOptions" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工程类型">
                    <el-input v-model="formModel.engineeringTypeName" disabled />
                    <!-- <el-select v-model="formModel.engineeringTypeName" disabled block>
                        <el-option label="总则" :value="1" />
                    </el-select> -->
                </el-form-item>
                <!-- el-form-item label="显示类型：">
                    <el-select v-model="formModel.key5" block>
                        <el-option label="总则" :value="1" />
                    </el-select>
                </el-form-item -->
                <el-form-item label="备注：">
                    <el-input v-model="formModel.remarks" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" />
                </el-form-item>
            </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 #nodeName="{ row }">
                    <span class="text-link">{{ row?.nodeName }}</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, watch } from 'vue'
import { arrToId, formValidate, getArrValue, getObjValue, getRandom } from 'js-fast-way'
import unitApi from '~api/project/debit/project/unit.js'
import { useAppStore } from '~src/store'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { getDictionary } from '~api/other'
import { delMessageV2 } from '~com/message/index.js'
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId || '')
//监听
watch(() => [
useAppState.getProjectId,
], ([pid]) => {
 if (pid) {
    projectId.value = pid
    ishowTree.value = false
    setTimeout(() => {
        ishowTree.value = true
    }, 100)
 }
})
defineOptions({
    name: 'ProjectDebitProjectUnit',
})

const uuid = getRandom(4)

//渲染完成
onMounted(() => {
    setSplitRef()
    // getNodeType()
})
//获节点类型
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 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 searchForm = ref({ current: 1, size: 10, total: 0 })

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
//懒加载的数据
const treeLoadNode = async ({ item, level }, resolve) => {
    if (!projectId.value) return
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await unitApi.lazyTree({
        projectId: projectId.value,
        id: id,
    })
    resolve(getArrValue(data))
}

const ishowTree = ref(true)
//重新设置树
const setLoading = ref(false)
const setTree = async ()=>{
    setLoading.value = true
    const { error, code, msg } = await unitApi.refresh({
        projectId: projectId.value,
    })
    setLoading.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        ishowTree.value = false
        setTimeout(() => {
            ishowTree.value = true
        }, 100)
        } else {
            // newlistdata.value = []
        }
}
//根节点菜单
const treeRootMenu = [
    { icon: 'add', label: '新增', key: 'add' },
    { icon: 'arrow-up-down-line', label: '排序', key: 'sort' },
]

//节点菜单
const treeMenus = [
    { 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 }) => {
    getNodeType(data.id)
    menuType.value = key
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    if (key === 'add') {
        treeModalTitle.value = '新增下级节点'
        treeModalShow.value = true
        formModel.value = {}
        const { level } = node
        if (level >= 3) {
            getEngineerName(data.id)
        }

        formModel.value.nodeType = data.nodeType
        formModel.value.parentId = data.id
        formModel.value.ancestor = data.ancestor
        formModel.value.projectId = data.projectId
    }
    if (key === 'edit') {
        treeModalTitle.value = '项目计量单元修改'
        treeModalShow.value = true
        formModel.value = data
    }
    if (key === 'del') {
        delModalClick()
    }
    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
            // sortTableData.value = data.children
        }
}
//获取工程名称
const getEngineerName = async (id)=>{
    const { error, code, data } = await unitApi.getEngineeringTypeName({
       id,
    })
    if (!error && code === 200) {
        formModel.value.engineeringTypeName = data || ''

    } else {
        formModel.value.engineeringTypeName = ''

}
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
}

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'nodeCode', name: '节点编号' },
    { key: 'nodeName', name: '节点名称' },
    { key: 'nodeTypeName', name: '节点类型' },
    { key: 'engineeringTypeName', name: '工程类型' },
])
const tableData = ref([])

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

//弹窗表单
const formRef = ref(null)
const formModel = ref({})
const formRules = ref({
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },
})

//弹窗保存
const addNodeLoading = ref(false)
const treeModalSave = async () => {
    if (menuType.value === 'edit') {
        const isValidate = await formValidate(formRef.value)
        if (!isValidate) return false
        const { error, code } = await unitApi.updateForm({
            ...formModel.value,

        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('修改成功')
            treeModalShow.value = false
            window?.location?.reload() //刷新页面
        }
    }
    if (menuType.value === 'add') {
        const isValidate = await formValidate(formRef.value)
        if (!isValidate) return false
        const { error, code } = await unitApi.addNode({
            ...formModel.value,

        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('新增成功')
            treeModalShow.value = false
            window?.location?.reload() //刷新页面
        }
    }
}
//树被点击
const curTreeData = ref({})
const wbsElTreeClick = ({ node, data, keys }) => {
    getNodeType(data.id)
    TreeAutoExpandKeys.value = keys || []
    setStoreValue('wbsTreeExpandKeys', keys)
    getTreeNodeDetail(data)

}

//获取节点详情
const getTreeNodeDetail = async (node)=>{
    const { id } = node
    const { error, code, data } = await unitApi.getNodeDetail({
       id,
    })
    if (!error && code === 200) {
        curTreeData.value = getObjValue(data)
        nodeOptions.value.forEach((ele)=>{
            if (ele.dictKey == curTreeData.value.nodeType) {
                curTreeData.value.nodeTypeName = ele.dictValue
            }
        })
        tableData.value = [curTreeData.value]

    } else {
        curTreeData.value = {}
        tableData.value = []
    }
}
//删除节点
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 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 = (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 unitApi.sortForm({ ids })
    sortNodeLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortModalShow.value = false
        window?.location?.reload() //刷新页面
    }

}
</script>
