<template>
    <HcCard>
        <template #extra>
            <el-button type="primary" @click="isedit = true" size="large" v-if="!isedit">
                <span>编辑组织机构</span>
            </el-button>
            <el-button type="primary" @click="isedit = false" size="large" v-if="isedit">
                <span>返回上一级</span>
            </el-button>
        </template>
        <div class="h-full text-center" v-if="!isedit">
            <vue3-tree-org :data="deptTreeData" :horizontal="false" :collapsable="false" :node-draggable="false" draggable
                center :scalable="false" :default-expand-level="5" :define-menus="[]" disabled
            >
                <template v-slot="{node}">
                    <div class="hac-node-vue3-tree-org-label">{{ node.label }}</div>
                </template>
            </vue3-tree-org>
        </div>
        <div class="h-full" v-if="isedit">
            <el-scrollbar>
                <HcTreeData :datas="deptTreeData" @menuTap="treeMenuTap"/>
            </el-scrollbar>
        </div>

        <HcDialog bgColor="#ffffff" isToBody :show="formModal" :title="formModalTitle"
                  @save="formModalSave" @close="formModalClose" widths="26rem"
        >
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" size="large">
                <el-form-item label="组织节点名称:" prop="deptName">
                    <el-input v-model="formModel.deptName"/>
                </el-form-item>
                <el-form-item label="上级组织节点名称:">
                    <el-input v-model="formModel.parentDeptName" placeholder="已为顶级节点" disabled/>
                </el-form-item>
                <el-form-item label="组织节点类别:">
                    <el-select block v-model="formModel.deptType" disabled>
                        <el-option label="公司" :value="1"/>
                        <el-option label="部门" :value="2"/>
                        <el-option label="岗位" :value="3"/>
                    </el-select>
                </el-form-item>
            </el-form>
        </HcDialog>

        <HcDialog bgColor="#ffffff" isToBody isTable :show="authModal" title="权限配置" @save="authModalSave" @close="authModalClose" widths="40rem">
            <el-scrollbar>
                <HcDataTree treeKey="id" :h-props="treeProps" :datas="treeMenuNode" :defaultCheckedKeys="treeMenuKeys" showCheckbox @check="treeMenuNodeCheck">
                    <template #default="{node, data}">
                        <span class="hc-tree-menu-label">{{node.label}}</span>
                        <span class="hc-tree-menu-remark">{{data.remark}}</span>
                    </template>
                </HcDataTree>
            </el-scrollbar>
        </HcDialog>
    </HcCard>

</template>

<script setup>
import {onActivated, ref} from "vue";
import mainApi from "~api/system/organization";
import HcTreeData from "./components/HcTreeData.vue";
import {formValidate, getArrValue} from "js-fast-way";
import menuApi from "~api/system/menu";
import {delMessage} from "~uti/tools";

//显示模式
const isedit = ref(false)

//页面被激活时
onActivated(() => {
    getTreeData()
})

//获取树数据
const deptTreeData = ref({})
const getTreeData = async () => {
    const {error, code, data} = await mainApi.deptList()
    if (!error && code === 200) {
        const res = await setDeptTreeData(data)
        deptTreeData.value = res[0]
    } else {
        deptTreeData.value = {}
    }
}

//组织架构显示信息
const lavel1_style = {color: "#fff", background: "#108ffe", borderColor: "#108ffe", padding: '10px 15px'}
const lavel2_style = {background: "#E8E8E8", padding: '10px 15px'}
const lavel3_style = {
    background: "none", border: 'none', borderBottom: '1px solid #c8c8c8', borderRadius: '0',
    boxShadow: 'none', fontSize: '14px', padding: '6px 2px'
}

//遍历处理组织结构数据树
//公司1，部门2，岗位3
const setDeptTreeData = async (data) => {
    let res = [], arr = getArrValue(data)
    for (let i = 0; i < arr.length; i++) {
        const {deptName, deptType, children} = arr[i]
        const obj = {...arr[i], label: deptName, children: [],
            style: deptType === 1 ? lavel1_style : deptType === 2 ? lavel2_style : lavel3_style
        }
        if (children && children.length > 0) {
            obj.children = await setDeptTreeData(children)
        }
        res.push(obj)
    }
    return res
}

//树节点表单弹窗
const formModal = ref(false)
const formModalTitle = ref('')

//树节点表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    deptName: {required: true, trigger: 'blur', message: "请输入组织节点名称"}
}

//树节点的菜单点击事件
const treeMenuTap = ({key, node, data}) => {
    if (key === 'add') {
        formModel.value = {
            parentId: data.id,
            parentDeptName: data.deptName,
            //如果当前节点为顶级节点，则为部门类型，如果为部门节点，则为岗位类型
            deptType: node.level === 1 ? 2 : node.level === 2 ? 3 : 0
        }
        const type = node.level === 1 ? '部门' : node.level === 2 ? '岗位' : '未知'
        formModalTitle.value = '新增' + type + '信息'
        formModal.value = true
    } else if (key === 'edit') {
        if (node.level > 1) {
            const parent = node.parent.data;
            formModel.value = {
                parentDeptName: parent.deptName,
                ...data
            }
        } else {
            formModel.value = data
        }
        const type = node.level === 1 ? '公司' : node.level === 2 ? '部门' : node.level === 3 ? '岗位' :'未知'
        formModalTitle.value = '编辑' + type + '信息'
        formModal.value = true
    } else if (key === 'del') {
        delMessage(() => {
            delNodeClick(data)
        }, '您确定要删除【' + data.deptName + '】的机构信息吗？一旦注销数据将彻底清除，请谨慎操作')
    } else if (key === 'auth') {
        authModalShow(data)
    }
}

//保存数据
const formModalSave = async () => {
    const isForm = await formValidate(formRef.value)
    if (isForm) {
        const {error, code, msg} = await mainApi.submit(formModel.value)
        if (!error && code === 200) {
            window?.$message?.success(msg)
            getTreeData().then()
            formModalClose()
        } else {
            window?.$message?.error(msg)
        }
    }
}


//弹窗关闭
const formModalClose = () => {
    formModal.value = false
    formModalTitle.value = ''
    formModel.value = {}
}

//删除节点
const delNodeClick = async (data) => {
    const {error, code, msg} = await mainApi.remove(data.id)
    if (!error && code === 200) {
        window?.$message?.success(msg)
        getTreeData().then()
    } else {
        window?.$message?.error(msg)
    }
}

//权限配置
const authModal = ref(false)
const treeMenuNode = ref([])
const treeProps = ref({
    label: 'name',
    children: 'children'
})

const authModalShow = (data) => {
    treeMenuNode.value = []
    authModal.value = true
    getMenuData()
}

const getMenuData = async () => {
    const {error, code, data} = await menuApi.lazyList({})
    if (!error && code === 200) {
        treeMenuNode.value = getArrValue(data)
    } else {
        treeMenuNode.value = []
    }
}

//默认勾选的节点
const treeMenuKeys = ref([])

//树节点被选择
const treeMenuNodeCheck = (data, {checkedKeys, halfCheckedKeys}) => {
    console.log('全选', checkedKeys) //全选
    console.log('半选', halfCheckedKeys) //半选
}

//权限配置弹窗保存
const authModalSave = () => {

}

//权限配置弹窗关闭
const authModalClose = () => {
    authModal.value = false
}
</script>

<style lang="scss" scoped>
@import "~src/styles/system/organization.scss";
.hc-tree-menu-label {
    font-size: 16px;
}
.hc-tree-menu-remark {
    color: #858585;
    margin-left: 10px;
}
</style>
