<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item prop="name">
                        <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable style="width: 240px"
                                  @keyup.enter="handleQuery"/>
                    </el-form-item>
<!--                    <el-form-item prop="enabled">-->
<!--                        <el-select v-model="queryParams.enabled" clearable @change="handleQuery">-->
<!--                            <el-option :value="true">是</el-option>-->
<!--                            <el-option value="false">否</el-option>-->
<!--                        </el-select>-->
<!--                    </el-form-item>-->
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>

        <Table ref="roleTable"
               :tableParams="tableParams"
               :btnRole="leftBtn"
               @handleAdd="handleAdd"
               @handleEdit="handleUpdate"
               @selectionChange="handleSelectionChange"
        >

        </Table>
    </el-card>
    <!-- 添加或修改角色管理对话框 -->
    <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="角色名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入角色名称"/>
            </el-form-item>
            <el-form-item label="角色描述" prop="desc">
                <el-input v-model="form.desc" placeholder="请输入角色描述"/>
            </el-form-item>

            <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" disabled @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-item label="是否启用" prop="enabled">
                <!--                <el-input v-model="form.enabled" placeholder="请输入是否启用" />-->
                <el-switch
                    v-model="form.enabled"
                    inline-prompt
                    :active-icon="Check"
                    :inactive-icon="Close"
                />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注"/>
            </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>


    <!-- 添加或修改角色管理对话框 -->
    <el-dialog :title="authDialog.title" v-model="authDialog.visible" width="600px" append-to-body>
        <el-form ref="dataScopeRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="角色名称" >
                <el-input v-model="form.name" disabled placeholder="请输入角色名称"/>
            </el-form-item>
            <el-form-item label="角色描述" disabled >
                <el-input v-model="form.desc" disabled placeholder="请输入角色描述"/>
            </el-form-item>
            <el-form-item label="权限范围" prop="dataScope">
                <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
                    <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="数据权限" v-show="form.dataScope == '自定义'">
                <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
                <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选
                </el-checkbox>
                <el-checkbox v-model="deptCheckStrictly" disabled @change="handleCheckedTreeConnect($event, 'dept')">
                    父子联动
                </el-checkbox>
                <el-tree
                    class="tree-border"
                    :data="deptOptions"
                    show-checkbox
                    default-expand-all
                    ref="deptRef"
                    node-key="treeId"
                    :check-strictly="!deptCheckStrictly"
                    empty-text="加载中，请稍候"
                    :props="{ label: 'title', children: 'children' }"
                ></el-tree>
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonDataLoading" type="primary" @click="submitDataScope">提交</el-button>
                <el-button @click="cancelDataScope">取 消</el-button>
            </div>
        </template>
    </el-dialog>

    <AuthUser @ok="handleQuery"  ref="selectUserRef"></AuthUser>
    <MobileAuth ref="mobileAuthRef"></MobileAuth>
</template>

<script setup name="Role" lang="ts">
import {
    listRole,
    delRole,
    addRole,
    updateRole,
    getRoleMenuTreeselect,
    bindDeptRole,
    getDeptsByRole, enableRole
} from '@/api/system/role';
import {allMenuList, listResTree} from '@/api/system/menu';
import {listDept} from "@/api/system/dept";
import {RoleVO, RoleQuery, RoleForm} from '@/api/system/role/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import AuthUser from './AuthUser.vue'
import {tableTypes} from '@/components/Table/types'
import {Check, Close} from '@element-plus/icons-vue'
import {MenuFormEntity, MenuQuery, MenuTreeOption, RoleMenuTree, DeptTreeOption} from '@/api/system/menu/types';
import {DeptQuery} from "@/api/system/dept/types";
import MobileAuth from './MobileAuth.vue'
const roleList = ref<RoleVO[]>([]);
const buttonLoading = ref(false);
const buttonDataLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
// 展开/折叠
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[]>([])

const mobileAuthRef = ref()
//所有的菜单 1级 2级 3级
const menuFormEntity = ref<MenuFormEntity[]>([])
const openDataScope = ref(false)

/** 数据范围选项*/
const dataScopeOptions = ref([
    {value: "全部", label: "全部"},
    {value: "本公司", label: "本公司"},
    {value: "仅自己", label: "仅自己"},
    {value: "本部门", label: "本部门"},
    {value: "自定义", label: "自定义"}
])


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 single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectUserRef = ref();

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 authDialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const tableParams = reactive<tableTypes<RoleForm, RoleVO>>({
    tableColumn: [
        {show: true, label: '角色ID', prop: 'id', sortable: false},
        {show: true, label: '角色名称', prop: 'name', sortable: false},
        {show: true, label: '角色描述', prop: 'desc', sortable: false},
        {show: true, label: '权限范围', prop: 'dataScope', sortable: false},
        {show: false, label: '备注', prop: 'remark', sortable: false},
        // {show: true, label: '创建者', prop: 'createBy', sortable: false},
        // {show: false, label: '拥有者', prop: 'ownerBy', sortable: false},
        {show: false, label: '创建时间', prop: 'createTime', sortable: false},
        {show: false, label: '更新者', prop: 'updateUserName', sortable: false},
        {show: false, label: '更新时间', prop: 'updateTime', sortable: false},
        {
            show: false, label: '是否删除', prop: 'isDelete', sortable: false, render: ({column}: { column: RoleVO }) => {
                return [
                    h(ElTag, {}, column.isDelete == 1 ? '是' : '否'),
                ]
            }
        },
        {
            show: true, label: '是否启用', prop: 'enabled', render: ({column}: { column: RoleVO }) => {
                return [
                    h(ElSwitch, {
                        modelValue: column.enabled, onChange: async (v) => {
                            enableChange({id: column.id, enable: v})
                            //TODO
                            column.enabled = v
                        }
                    }),
                ]
            }
        },

        {
            show: true,
            label: '操作',
            prop: 'operation',
            disabledMove: true,
            render: ({column}: { column: RoleVO }) => {
                return [
                    auth.hasPermi('system:role:dataAuth') ?
                        h(ElButton, {
                            link: true, type: 'primary', onclick: () => {
                                handleDataAuthUpdate(column)

                            }
                        }, '数据权限')
                        : '',
                    auth.hasPermi('system:role:authUser') ?
                        h(ElButton, {
                            link: true, type: 'primary', onclick: () => {
                                selectUserRef.value.show(column)
                            }
                        }, '分配用户')
                        : '',
                    auth.hasPermi('system:role:authUser') ?
                        h(ElButton, {
                            link: true, type: 'primary', onclick: () => {
                                mobileAuthRef.value.show(column)
                            }
                        }, '移动端权限')
                        : '',
                    auth.hasPermi('system:role:edit') ?
                        h(ElButton, {
                            link: true, type: 'primary', onclick: () => {
                                handleUpdate(column)
                            }
                        }, 'PC端权限')
                        : ''
                ]
            }
        },
    ],
    queryParams: {
        name: undefined,
        desc: undefined,
        dataScope: undefined,
        ownerBy: undefined,
        isDelete: undefined,
        enabled: undefined,
        sort: undefined,
    },
    keyId: 'id',
    listFn: listRole,
    delFn: delRole,
})


const initFormData: RoleForm = {
    id: undefined,
    name: undefined,
    desc: undefined,
    dataScope: undefined,
    remark: undefined,
    ownerBy: undefined,
    isDelete: undefined,
    enabled: undefined,
    sort: undefined,
    menus: undefined,
    depts: undefined
}

const data = reactive<PageData<RoleForm, RoleQuery>>({
    form: {...initFormData},
    rules: {
        id: [
            {required: true, message: "角色ID不能为空", trigger: "blur"}
        ],
        name: [
            {required: true, message: "角色名称不能为空", trigger: "blur"}
        ],
        desc: [
            {required: true, message: "角色描述不能为空", trigger: "blur"}
        ],
        dataScope: [
            {required: true, message: "权限范围不能为空", trigger: "blur"}
        ],
        remark: [
            {required: true, message: "备注不能为空", trigger: "blur"}
        ],
        isDelete: [
            {required: true, message: "是否删除不能为空", trigger: "blur"}
        ],
        enabled: [
            {required: true, message: "是否启用不能为空", trigger: "blur"}
        ],
        sort: [
            {required: true, message: "显示顺序不能为空", trigger: "blur"}
        ]
    }
});

const {form, rules} = toRefs(data);

const {queryParams} = toRefs(tableParams);
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
    roleFormRef.value?.resetFields();
}

const roleTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    roleTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

const enableChange = async (data) => {
    let res = await enableRole(data)
    handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RoleVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
    reset();

    const res = await listResTree();
    menuOptions.value = res.result;

    dialog.visible = true;
    dialog.title = "添加角色管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RoleVO) => {
    reset();
    const res = await listResTree();
    menuOptions.value = res.result;
    Object.assign(form.value, row);
    if (row?.id) {
        nextTick(async ()=>{
            const checkNode = await getRoleMenuTreeselect(row?.id);
            checkNode.result.forEach((v: number | string) => {
                nextTick(() => {
                    menuRef.value?.setChecked(v, true, false);
                })
            })
        })
    }
    dialog.visible = true;
    dialog.title = "修改角色管理";
}

/** 修改数据权限 */
const handleDataAuthUpdate = async (row?: RoleVO) => {
    reset();
    let typs: number[] = [10, 20, 30]

    if (row?.id) {
        authDialog.visible = true;

        Object.assign(form.value, row);
        const res = await listDept(typs, undefined);
        deptOptions.value = res.result;
        const deptRes = await  getDeptsByRole(row?.id);
        nextTick(() => {
            deptRes.result.forEach((v: number | string) => {
                let treeId = '30-'+ v
                deptRef.value?.setChecked(treeId, true, false);
            })
        })
    }

    authDialog.title = "分配数据权限";
}

const getList = () => {
    roleTable.value.getData()
}
/** 所有菜单节点数据 */
const getMenuAllCheckedKeys = (): any => {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value?.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value?.getHalfCheckedKeys();
    if (halfCheckedKeys) {
        checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    }
    return checkedKeys;
}
/** 所有部门节点数据 */
const getDeptAllCheckedKeys = (): any => {
    // 目前被选中的部门节点
    let checkedNodes = deptRef.value?.getCheckedNodes();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value?.getHalfCheckedNodes();
    if (!!!checkedNodes || checkedNodes.length == 0) return []
    // 半选中的菜单节点
    if (halfCheckedKeys) {
        checkedNodes?.unshift.apply(checkedNodes, halfCheckedKeys);
    }
    console.log(checkedNodes)
    let arry: Array<number> = []
     checkedNodes.forEach((item: any) => {
        if (item.type == 30) {
            arry.push(item.id)
        }
    })


    console.log(arry)
    return arry;

}
/** 提交按钮（数据权限） */
const submitDataScope = async () => {
    buttonDataLoading.value = true
    if (form.value.id) {
        form.value.depts = getDeptAllCheckedKeys();
        await bindDeptRole(form.value);
        proxy?.$modal.msgSuccess("修改成功");
        authDialog.visible = false;
        buttonDataLoading.value = false
        getList();
    }
}
/** 提交按钮 */
const submitForm = () => {
    roleFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            form.value.menus = await getMenuAllCheckedKeys()
            if (form.value.id) {
                await addRole(form.value).finally(() => buttonLoading.value = false);
            } else {
                await addRole(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("修改成功");
            dialog.visible = false;
            await getList();
        }
    });
}
/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value: boolean, type: string) => {
    if (type == "menu") {
        let treeList = menuOptions.value;
        for (let i = 0; i < treeList.length; i++) {
            if (menuRef.value) {
                menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
            }
        }
    } else if (type == "dept") {
        let treeList = deptOptions.value;
        for (let i = 0; i < treeList.length; i++) {
            if (deptRef.value) {
                deptRef.value.store.nodesMap[treeList[i].treeId].expanded = value;
            }
        }
    }
}
/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value: any, type: string) => {
    if (type == "menu") {
        menuRef.value?.setCheckedNodes(value ? menuOptions.value as any : []);
    } else if (type == "dept") {
        deptRef.value?.setCheckedNodes(value ? deptOptions.value as any : []);
    }
}
/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value: any, type: string) => {
    if (type == "menu") {
        menuCheckStrictly.value = value;
    } else if (type == "dept") {
        deptCheckStrictly.value = value;
    }
}
/** 取消按钮（数据权限）*/
const cancelDataScope = () => {
    dataScopeRef.value?.resetFields();
    form.value = {...initFormData};
    authDialog.visible = false;
}

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