<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <el-button type="primary" @click="handleAdd"> 添加 </el-button>
        </div>
        <ProTable
            ref="proTableRef"
            :formData="dataStore.formData"
            :columns="dataStore.columns"
            :request-api="getRoleListApi"
            :init-param="dataStore.initParam"
        >
            <template #operation="scope">
                <el-button size="small" type="primary" @click="handleBtnClick('编辑', scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleBtnClick('删除', scope.row)">删除</el-button>
            </template>
        </ProTable>
        <el-drawer
            v-model="dataStore.visible"
            :show-close="true"
            :size="600"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="handleBeforeClone"
            destroy-on-close
        >
            <template #header="{ titleId, titleClass }">
                <h4 :id="titleId" :class="titleClass">{{ dataStore.title }}</h4>
            </template>
            <div>
                <rulesForm
                    :ruleForm="dataStore.editRuleForm"
                    :formData="dataStore.editFormData"
                    :rules="dataStore.rules"
                    :indeterminate="dataStore.isIndeterminate"
                    ref="formRef"
                >
                </rulesForm>
                <div style="margin-left: 65px; font-size: 14px; color: #606266">
                    <div style="display: flex; align-items: center; margin-bottom: 10px">
                        <span style="margin-right: 10px">权限分配:</span>
                        <el-checkbox v-model="dataStore.allCheck" @change="handleAllCheckChange" label="全选" size="large" />
                    </div>
                    <el-tree
                        ref="treeRef"
                        style="max-width: 600px"
                        :data="dataStore.treeData"
                        show-checkbox
                        node-key="id"
                        highlight-current
                        :props="defaultProps"
                        @check-change="handleTreeCheckChange"
                    />
                </div>
            </div>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="handleResetClick">重置</el-button>
                    <el-button type="primary" @click="handleConfirmClick">确认</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup lang="ts" name="roleListIndex">
import ProTable from "@/components/ProTable/index.vue";
import rulesForm from "@/components/rulesForm/index.vue";
import { messageBox } from "@/utils/messageBox";
import { nextTick } from "vue";
import { useMsg } from "@/hooks/useMsg";
//列表接口
import {
    getRoleListApi,
    getRoleListDetailsApi,
    getRoleListDelApi,
    getRoleListEditUpApi,
    getRoleListSaveApi
} from "@/api/modules/roleList";
//getMenusListApi
import { getRoleMenusListApi } from "@/api/modules/webMenusList";
//深拷贝方法
import { cloneDeep } from "lodash-es";
//表格和搜索條件
import { RULE_FORM, FORM_DATA, COLUMNS, EDIT_FORM_DATA, EDIT_RULE_FORM, RULES } from "./constant/index";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref<any>(null);
const formRef: any = ref(null);
const treeRef: any = ref(null);
const defaultProps = {
    children: "children",
    label: "title"
};
// 数据源
const dataStore = reactive<any>({
    treeData: [], //权限
    allCheck: false,
    title: "添加角色", //抽屉标题
    columns: COLUMNS, //列表配置项
    rules: cloneDeep(RULES), //抽屉表单验证
    editRuleForm: cloneDeep(EDIT_RULE_FORM),
    editFormData: cloneDeep(EDIT_FORM_DATA), //抽屉表单配置项
    initParam: cloneDeep(RULE_FORM), // 初始化搜索条件|重置搜索条件
    ruleForm: cloneDeep(RULE_FORM), // 搜索參數
    formData: FORM_DATA, //搜索配置项
    selectedMenuIds: [], // 新增属性，用于保存选中的菜单 id
    isIndeterminate: false, //全选框样式控制
    visible: false, //抽屉控制
    selectRow: {} //当前选择的row
});

// 处理全选框状态变化
const handleAllCheckChange = (checked: any) => {
    const allNodeKeys = getAllNodeKeys(dataStore.treeData);
    if (checked) {
        treeRef.value.setCheckedKeys(allNodeKeys);
    } else {
        treeRef.value.setCheckedKeys([]);
    }
};

// 获取所有节点的 key
const getAllNodeKeys = (data: any[]) => {
    let keys: number[] = [];
    data.forEach(item => {
        keys.push(item.id);
        if (item.children && item.children.length > 0) {
            keys = keys.concat(getAllNodeKeys(item.children));
        }
    });
    return keys;
};

// 处理树节点选中状态变化
const handleTreeCheckChange = () => {
    const allNodeKeys = getAllNodeKeys(dataStore.treeData);
    const checkedKeys = treeRef.value.getCheckedKeys();
    if (checkedKeys.length === allNodeKeys.length) {
        dataStore.allCheck = true;
        dataStore.isIndeterminate = false;
    } else if (checkedKeys.length === 0) {
        dataStore.allCheck = false;
        dataStore.isIndeterminate = false;
    } else {
        dataStore.allCheck = false;
        dataStore.isIndeterminate = true;
    }
    // 更新选中的菜单 id
    dataStore.selectedMenuIds = checkedKeys.map((id: any) => ({ menu_id: id }));
};

//抽屉确认
const handleConfirmClick = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef!.validate((valid: any) => {
        if (valid) {
            console.log("submit!");
            dataStore.title === "添加角色" ? getRoleListSave() : getRoleListEditUp();
        } else {
            console.log("error submit!");
            return false;
        }
    });
};
//重置验证状态
const resetFields = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef.resetFields();
};
//抽屉重置
const handleResetClick = () => {
    if (dataStore.title === "添加角色") {
        resetFields();
    } else {
        getRoleListDetails(dataStore.editRuleForm.id);
    }
};
//添加
const handleAdd = () => {
    dataStore.title = "添加角色";
    dataStore.visible = true;
};
//抽屉关闭前的钩子
const handleBeforeClone = () => {
    dataStore.selectedMenuIds = [];
    treeRef.value.setCheckedKeys([]);
    dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
    resetFields();
    dataStore.visible = false;
};
//按钮点击事件
const handleBtnClick = (type: any, row: any) => {
    dataStore.selectRow = row;
    //编辑
    if (type === "编辑") {
        dataStore.visible = true;
        dataStore.title = "编辑角色";
        getRoleListDetails(row.id);
        return;
    }
    //删除
    if (type === "删除") {
        getRoleListDel(row.id);
    }
};

//删除
const getRoleListDel = (id: any) => {
    messageBox("你确定要删除?", async () => {
        const result = await getRoleListDelApi(id);
        if (result?.code === 0) {
            const { msg } = result;
            useMsg("success", msg);
            proTableRef?.value?.getTableList();
        }
    });
};
//详情
const getRoleListDetails = async (id: any) => {
    const result = await getRoleListDetailsApi(id);
    if (result?.code === 0) {
        dataStore.editRuleForm = result?.data;
        const menuIds = dataStore.editRuleForm.authorities.map((item: any) => item.menu_id);
        // 设置树组件的默认选中节点
        nextTick(() => {
            if (treeRef.value) {
                treeRef.value.setCheckedKeys(menuIds);
            }
        });
    }
};
//保存
const getRoleListSave = async () => {
    const result = await getRoleListSaveApi({
        ...dataStore.editRuleForm,
        menu_permission: JSON.stringify(dataStore.selectedMenuIds)
    });
    if (result?.code === 0) {
        const { msg } = result;
        useMsg("success", msg);
        dataStore.visible = false;
        dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
        proTableRef?.value?.getTableList();
    }
};
//更新
const getRoleListEditUp = async () => {
    const result = await getRoleListEditUpApi({
        ...dataStore.editRuleForm,
        menu_permission: JSON.stringify(dataStore.selectedMenuIds)
    });
    if (result?.code === 0) {
        const { msg } = result;
        useMsg("success", msg);
        dataStore.visible = false;
        dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
        proTableRef?.value?.getTableList();
    }
};
//权限管理
const getMenusList = async () => {
    const result = await getRoleMenusListApi();
    if (result?.code === 0) {
        dataStore.treeData = result?.data;
    }
};
getMenusList();
</script>

<style scoped></style>
