<template>
    <HcLazyTree
        v-if="isShowTree"
        :h-props="treeProps" :auto-expand-keys="autoExpandKeys" :tree-key="treeKey" :show-checkbox="showCheckbox"
        @load="treeLoadNode"
        @nodeTap="treeNodeClick"
    >
        <template #default="{ node, data, level }">
            <div :class="level === 1 ? 'level-name' : ''" class="label flex items-center">
                <span v-if="level !== 1" class="hc-tree-node-type">{{ getNodeTypeName(data?.nodeType) }}</span>
                <span>{{ node.label }}</span>
            </div>
            <!-- 树组件，操作菜单 -->
            <div v-if="isMenus" :class="node.showTreeMenu ? 'show' : ''" class="menu-icon1">
                <div class="cu-tree-node-popover-menu-icon" @click.prevent.stop="treeLabelContextMenu($event, data, node)">
                    <HcIcon name="apps" ui="text-2xl" />
                </div>
            </div>
        </template>
    </HcLazyTree>
    <!-- 右键菜单 -->
    <HcContextMenu v-if="isMenus" ref="contextMenuRef" :datas="treeMenu" @closed="handleMenuClosed" @item-click="handleMenuSelect" />
    <!-- 新增/编辑 -->
    <HcDialog is-to-body bg-color="white" :show="rowModal" :title="formModel.id ? '编辑区域' : '新增区域'" widths="30rem" :loading="submitLoading" @save="rowModalSave" @close="rowModalClose">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" size="large">
            <el-form-item label="区域名称：" prop="key">
                <el-input v-model="formModel.areaName" />
            </el-form-item>
            <el-form-item label="征拆桩号：">
                <el-input v-model="formModel.stakeMark" />
            </el-form-item>
            <el-form-item label="节点类型：">
                <el-select v-model="formModel.nodeType" block>
                    <el-option v-for="item in nodeTypeData" :key="item.id" :label="item.dictValue" :value="item.dictKey" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注：">
                <el-input v-model="formModel.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
            </el-form-item>
        </el-form>
    </HcDialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { formValidate, getArrValue, getObjValue, isNullES } from 'js-fast-way'
import { addOrUpdateTree, deleteTree, getDictInfo, getLazyTree } from '~api/other'
import { useAppStore } from '~src/store'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { delMessageV2 } from '~com/message/index.js'
//参数
const props = defineProps({
    isMenu: {
        type: Boolean,
        default: true,
    },
    showCheckbox: {
        type: Boolean,
        default: false,
    },
})
//事件
const emit = defineEmits(['menuTap', 'nodeTap'])
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)

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

//事件

//节点类型字典
const nodeTypeData = ref([])
const getNodeTypeData = async () => {
    const { error, code, data } = await getDictInfo('region_node_type')
    //判断状态
    if (!error && code === 200) {
        nodeTypeData.value = getArrValue(data)
        nodeTypeData.value.forEach((ele)=>{
            ele.dictKey = parseInt(ele.dictKey)
        })
    } else {
        nodeTypeData.value = []
    }
}
//获取节点类型名称
const getNodeTypeName = (val)=>{
    switch (val) {
            case 1:
                return '省'
            case 2:
                return '市'
            case 3:
                return '区'
            case 4:
                return '县'
            case 5:
                return '乡/镇'
            case 6:
            return '村'
            case 7:
            return '组'
            default:
                return ''
        }
}
const treeKey = ref('id')
const treeRefNode = ref({})
const treeRefData = ref({})
const isMenus = ref(props.isMenu)
const autoExpandKeys = ref(getStoreValue('autoExpandKeys') || [])
const isShowTree = ref(true)

//监听
watch(() => [
    props.isMenu,
], ([isMenu]) => {
    isMenus.value = isMenu
})

//数据格式
const treeProps = {
    label: 'areaName',
    children: 'children',
    isLeaf:'notExsitChild',
}



//懒加载的数据
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let id = ''
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await getLazyTree({
        projectId: projectId.value || '',
        id,
    })
    resolve(getArrValue(data))
}
//树被点击
const treeNodeClick = async ({ node, data, keys }) => {
    treeRefNode.value = node
    treeRefData.value = data
    emit('nodeTap', { node, data })
    autoExpandKeys.value = keys
    setStoreValue('autoExpandKeys', keys)
}

//标题的鼠标右键
const treeMenu = ref([])
const contextMenuRef = ref(null)
const treeLabelContextMenu = async (e, data, node) => {

    if (!isMenus.value) {
        return
    }
    e.preventDefault()
    treeRefNode.value = node
    treeRefData.value = data
    if (node.level === 1) {
        treeMenu.value = [{ icon: 'add-circle', label: '新增节点', key: 'add' }]
    } else {
        treeMenu.value = [
            { icon: 'add-circle', label: '新增节点', key: 'add' },
            { icon: 'draft', label: '编辑节点', key: 'edit' },
            { icon: 'delete-bin', label: '删除节点', key: 'del' },
        ]
    }
    node.showTreeMenu = true
    contextMenuRef.value?.showMenu(e)
}


const handleMenuClosed = () => {
    const node = treeRefNode.value
    if (!isNullES(node)) {
        treeRefNode.value['showTreeMenu'] = false
    }
}

//弹窗
const rowModal = ref(false)
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    areaName: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
}


//鼠标右键菜单被点击
const handleMenuSelect = async ({ key }) => {
    const node = treeRefNode.value
    if (key === 'add') {
        formModel.value = {}
        formModel.value.parentId = node?.data.id
        formModel.value.projectId = node?.data.projectId
        rowModal.value = true
    } else if (key === 'edit') {
        formModel.value = node?.data
        rowModal.value = true
    } else if (key === 'del') {
        delModalClick(node?.data.id)
    }
    console.log(key)
}
//重新加载树
const rerfeshTree = ()=>{
    isShowTree.value = false
    setTimeout(() => {
        isShowTree.value = true
    }, 100)
}
const submitLoading = ref(false)
//保存
const rowModalSave = async () => {
    const res = await formValidate(formRef.value)
    if (res) {
        console.log( formModel.value, ' formModel.value')
        submitLoading.value = true
        //发起请求
        const form = formModel.value
        const { error, code, msg } = await addOrUpdateTree(form)
        //判断状态
        submitLoading.value = false
        if (!error && code === 200) {
            window.$message?.success(msg)
            rowModal.value = false
            rerfeshTree()
            
        } 
        
    }
}
//删除节点
const delModalClick = (id) => {
    delMessageV2(async (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
             removeTreeNode(id)
            instance.confirmButtonLoading = false
            done()
        } else {
            done()
        }
 })
}
const removeTreeNode = async (id)=>{
    const { error, code } = await deleteTree({
        id: id,
    }, false)
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        rerfeshTree()
    } else {
        window.$message?.error('删除失败')
    }
}
//关闭弹窗
const rowModalClose = () => {
    rowModal.value = false
    formModel.value = {}
}



//处理自动展开的节点KEY
const getAutoKeys = async (node) => {
    let autoKeysArr = []
    await getNodeExpandKeys(node, autoKeysArr)
    return autoKeysArr.reverse()
}
const getNodeExpandKeys = async ({ parent, data }, newKeys) => {
    const nodeKey = data[treeKey.value] ?? ''
    if (nodeKey) {
        newKeys.push(nodeKey)
        await getNodeExpandKeys(parent, newKeys)
    }
}
</script>

<style lang="scss">
.data-custom-tree-node {
    .menu-icon1 {
        position: relative;
        vertical-align: bottom;
        display: inline-block;
        width: 0;
        right: -45px;
        border-radius: 2px;
        pointer-events: none;
        background: rgba(255, 255, 255, 0.25);
        transition: width 0.2s;
        .cu-tree-node-popover-menu-icon {
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
    &:hover {
        .menu-icon1 {
            right: 0;
            width: 24px;
            pointer-events: all;
            cursor: context-menu;
        }
    }
    .menu-icon1.show {
        right: 0;
        width: 24px;
        pointer-events: all;
        cursor: context-menu;
    }
}
</style>
