<template>
    <el-dialog v-model="dialogVisible" :before-close="handleClose" style="width: 650px; padding-bottom: 20px" :title="title" :destroy-on-close="true">
        <el-form ref="FormDataRef" :model="form" label-width="100" :rules="formRules">
            <el-form-item label="岗位名称" prop="name" v-if="isTrue">
                <el-input v-model="form.name" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-row v-if="isTrue">
                <el-col :span="24">
                    <el-form-item label="菜单权限">
                        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠 </el-checkbox>
                        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll"> 全选/全不选 </el-checkbox>
                        <div class="border w-full py-1 max-h-[300px] overflow-y-auto">
                            <el-tree
                                ref="menuRef"
                                :data="treeData"
                                :default-expand-all="false"
                                :props="{ label: 'name' }"
                                node-key="id"
                                show-checkbox
                                style="width: 100%"
                            />
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="岗位描述" prop="description">
                <el-input maxlength="100" v-model="form.description" placeholder="请输入岗位描述" :rows="2" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="submitting" type="primary" @click="onClickSave">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { getCurrentInstance, reactive, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { savePositionMenu, menuListByRoleId } from '~/api/sys.js';
import { useUserStore } from '../../store/user';

const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const emits = defineEmits(['success']);

const menuRef = ref(null);
const dialogVisible = ref(false);
const submitting = ref(false);
const FormDataRef = ref(null);
const roleId = ref('');
const treeData = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const title = ref('');
const isTrue = ref(true);

const form = reactive({
    id: '',
    name: '',
    description: '',
    type: '',
    menuIds: [],
});
const formRules = reactive({
    name: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '岗位描述不能为空', trigger: 'blur' }],
});
// 展开/折叠
function handleCheckedTreeExpand(value) {
    if (!menuRef.value || !treeData.value || !Array.isArray(treeData.value)) {
        return;
    }
    
    const treeList = treeData.value;
    for (let i = 0; i < treeList.length; i++) {
        if (menuRef.value.store && menuRef.value.store.nodesMap && menuRef.value.store.nodesMap[treeList[i].id]) {
            menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
        }
    }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
    if (!menuRef.value) {
        return;
    }
    
    // 确保treeData是数组
    const menuData = Array.isArray(treeData.value) ? treeData.value : [];
    menuRef.value.setCheckedNodes(value ? menuData : []);
}

const handleClose = () => {
    if (FormDataRef.value) {
        FormDataRef.value.clearValidate();
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    submitting.value = false;
    
    // 强制关闭对话框
    dialogVisible.value = false;
    
    // 重置表单数据
    form.id = '';
    form.name = '';
    form.description = '';
    form.type = '';
    form.menuIds = [];
    
    // 清空树数据
    treeData.value = [];
};

function getMenuAllCheckedKeys() {
    // 确保menuRef存在
    if (!menuRef.value) {
        return [];
    }
    
    // 目前被选中的菜单节点
    const checkedKeys = menuRef.value.getCheckedKeys();
    // 半选中的菜单节点
    const halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
}

const onClickSave = () => {
    if (FormDataRef.value) {
        FormDataRef.value.validate((valid) => {
            if (valid) {
                submitting.value = true;
                const params = { ...form };
                params.menuIds = getMenuAllCheckedKeys();
                savePositionMenu(params)
                    .then((res) => {
                        submitting.value = false;
                        if (res.code === 200) {
                            ElMessage.success('保存成功');
                            // 使用 nextTick 确保消息显示后再关闭对话框
                            nextTick(() => {
                                handleClose();
                                emits('success');
                            });
                        } else {
                            ElMessage.warning(res.msg || '保存失败');
                        }
                    })
                    .catch((error) => {
                        submitting.value = false;
                        ElMessage.error('保存失败，请重试');
                    });
            }
        });
    }
};

const open = async (row) => {
    dialogVisible.value = true;
    
    // 等待DOM更新完成
    await nextTick();
    
    if (row) {
        roleId.value = row.id;
        title.value = `${row.name}分配菜单`;
        isTrue.value = false;
        form.id = row.id;
        form.name = row.name;
        const { data } = await menuListByRoleId(row.id);
        treeData.value = data.menuList || [];
        
        // 确保menuRef存在后再调用
        if (menuRef.value) {
            menuRef.value.setCheckedKeys([]);
            // 触发一次树形结构的更新
            setTimeout(() => {
                if (menuRef.value) {
                    menuRef.value.setCheckedKeys([]);
                }
            }, 10);
        }
    } else {
        // 新增岗位的情况
        roleId.value = '';
        title.value = '新增岗位';
        isTrue.value = true;
        form.id = '';
        form.name = '';
        form.description = '';
        const { data } = await menuListByRoleId(null);
        treeData.value = data.menuList || [];
        
        // 确保menuRef存在后再调用
        if (menuRef.value) {
            menuRef.value.setCheckedKeys([]);
        }
    }
};

defineExpose({
    open,
});
</script>
<style lang="less" scoped>
.border {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}
</style>
