<template>

    <!-- 添加或修改角色管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
        <el-form ref="roleFormRef" :model="form" :rules="rules" label-width="80px">


            <el-form-item label="菜单权限">
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
                </el-checkbox>
                <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
                </el-checkbox>
                <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" node-key="id"
                    :check-strictly="!menuCheckStrictly" empty-text="加载中，请稍候"
                    :props="{ label: 'title', children: 'children' }"></el-tree>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>


</template>

<script setup name="Role" lang="ts">
import {listWebH5ResTree} from '@/api/system/menu/'
import {MenuFormEntity,  MenuTreeOption,  DeptTreeOption} from '@/api/system/menu/types';
import { RoleVO } from '@/api/system/role/types';
import { bindAppRoleMenu, getH5RoleMenuId } from '@/api/system/role';
// 展开/折叠
const menuExpand = ref(false)
const deptExpand = ref(false)
const deptNodeAll = ref(false)
// 全选/全不选
const menuNodeAll = ref(false)
//菜单树是否关联显示
const menuCheckStrictly = ref(true)
//组织树是否父子关联
const deptCheckStrictly = ref(true)
//权限树
const menuOptions = ref<MenuTreeOption[]>([])
// 组织树
const deptOptions = ref<DeptTreeOption[]>([])

//所有的菜单 1级 2级 3级
const menuFormEntity = ref<MenuFormEntity[]>([])
const openDataScope = ref(false)
const reset = () => {
    form.value = {...roleItem.value}
    menuRef.value?.setCheckedKeys([]);
    menuNodeAll.value = false
    menuExpand.value = false
    // menuCheckStrictly.value = false
}
const roleItem = ref<RoleVO>({
    id: '',
    name: '',
    desc: '',
    dataScope: '',
    enabled: false,
})

const form = ref<any>({})
const rules = ref<any>({})
const leftBtn = ref([
    { type: 'add', hasPermi: 'system:role:add', },
    { type: 'edit', hasPermi:  'system:role:edit', },
    { type: 'remove', hasPermi:'system:role:remove', },
    { type: 'import', hasPermi:  'system:role:import',},
    { type: 'export', hasPermi: 'system:role:export', }
])

const dataScopeSelectChange = ()=> {


}
const buttonLoading = ref(false)

const cancel = () => {
    dialog.visible = false
}




const menuRef = ref<ElTreeInstance>();
const deptRef = ref<ElTreeInstance>();
const dataScopeRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const roleFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: '移动端权限'
});


const roleTable = ref()

/** 所有菜单节点数据 */
const getMenuAllCheckedKeys = (): any => {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value?.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value?.getHalfCheckedKeys();
    if (halfCheckedKeys) {
        checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    }
    return checkedKeys;
}

/** 提交按钮 */
const submitForm = () => {
    roleFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            let menuIds = await getMenuAllCheckedKeys()

            await bindAppRoleMenu({ roleId: roleItem.value.id, menuls: menuIds, isApp: 1 }).finally(() => buttonLoading.value = false);

            menuNodeAll.value = false
            menuExpand.value = false
            menuCheckStrictly.value = false
            ElMessage.success('修改成功')
            dialog.visible = false;
        }
    });
}
/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value: boolean, type: string) => {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
        if (menuRef.value) {
            menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
        }
    }
}
/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value: any, type: string) => {
    menuRef.value?.setCheckedNodes(value ? menuOptions.value as any : []);
}
/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value: any, type: string) => {
    menuCheckStrictly.value = value;
}
/** 取消按钮（数据权限）*/
const cancelDataScope = () => {
    dataScopeRef.value?.resetFields();
    // form.value = {...initFormData};
    // authDialog.visible = false;
}

const show = (column: any) => {
    dialog.visible = true
    roleItem.value = column
    // dialog.title = column.label
    reset()
    init()
}

const init = () => {
    listWebH5ResTree(1).then((res) => {
        console.log(res)
        menuOptions.value = res.result
        nextTick(async () => {
            const checkNode = await getH5RoleMenuId(roleItem.value.id);
            checkNode.result.forEach((v: number | string) => {
                nextTick(() => {
                    menuRef.value?.setChecked(v, true, false);
                })
            })
        })
    })

}
defineExpose({
    show
})
onMounted(() => {
});
</script>
