<template>
    <PageWrapper dense fixedHeight contentFullHeight contentClass="flex">
        <div class="w-1/5 xl:w-1/5 mr-2">
            <BasicTree title="角色权限列表" toolbar :treeData="treeData" :fieldNames="{ title: 'title', key: 'id' }" @select="handleSelect">
                <template #title="{ title, systemName, parentId }">
                    <div>{{ title }}</div>
                </template>
            </BasicTree>
        </div>
        <div class="w-4/5 xl:w-4/5">
            <BasicTable @register="registerTable" ref="tableRef" @row-dbClick="dbClickRow">
                <template #toolbar>
                    <template v-for="button in tableButtonConfig" :key="button.code">
                        <a-button v-if="button.isDefault" :type="button.type" @click="buttonClick(button.code)">
                            <template #icon>
                                <Icon :icon="button.icon" />
                            </template>
                            {{ button.name }}
                        </a-button>
                        <a-button v-else :type="button.type">
                            <template #icon>
                                <Icon :icon="button.icon" />
                            </template>
                            {{ button.name }}
                        </a-button>
                    </template>
                </template>
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'roleGroup'">
                        <div class="group-tags">
                            <a-space>
                                <a-tag v-for="(name, id) in record.roleGroup" :key="id" color="blue" @click.stop="handleGroupClick(id, name)" style="cursor: pointer">
                                    {{ name }}
                                </a-tag>
                            </a-space>
                        </div>
                    </template>
                    <template v-if="column.dataIndex === 'action'">
                        <TableAction :actions="getActions(record)" />
                    </template>
                </template>
            </BasicTable>
        </div>

        <!--查看成员弹框-->
        <AuthModal @register="registerModal" />

        <!--弹出角色选择框-->
        <RoleModal @register="registerRoleModal" @success="handleRoleSuccess" />

        <!--用户组人员弹框-->
        <AuthModal @register="registerAuthModal" />
    </PageWrapper>
</template>

<script lang="ts" setup>
    import { ref, computed, onMounted, onUnmounted, createVNode, getCurrentInstance } from 'vue';
    import { Modal } from 'ant-design-vue';
    import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
    import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
    import { getRolePermissionPage, getMenuTree, updateRolePermission } from '/@/api/system/RolePermission';
    import { PageWrapper } from '/@/components/Page';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { usePermission } from '/@/hooks/web/usePermission';
    import { useFormConfig } from '/@/hooks/web/useFormConfig';
    import { useRouter } from 'vue-router';
    import { useModal } from '/@/components/Modal';
    import { formConfig, searchFormSchema, columns } from './components/config';
    import Icon from '/@/components/Icon/index';

    import { BasicTree, TreeItem } from '/@/components/Tree';
    import { apiConfigFunc } from '/@/utils/event/design';
    import useEventBus from '/@/hooks/event/useEventBus';
    import { cloneDeep } from 'lodash-es';
    import AuthModal from '../dataAuthority/components/AuthModal.vue';
    import RoleModal from '../user/components/RoleModal.vue';
    import { getRoleUser } from '/@/api/system/role';
    import { getGroupUser } from '/@/api/system/group';

    const { bus, CREATE_FLOW, FLOW_PROCESSED, FORM_LIST_MODIFIED } = useEventBus();

    const { notification } = useMessage();
    const { t } = useI18n();
    defineEmits(['register']);
    const { filterColumnAuth, filterButtonAuth } = usePermission();
    const { mergeColumns, mergeSearchFormSchema, mergeButtons } = useFormConfig();

    const filterColumns = cloneDeep(filterColumnAuth(columns));
    const customConfigColums = ref(filterColumns);
    const customSearchFormSchema = ref(searchFormSchema);

    const tableRef = ref();
    //所有按钮
    const buttons = ref([
        { isUse: true, name: '修改角色', code: 'editRole', icon: 'ant-design:usergroup-add-outlined', isDefault: true },
        { isUse: true, name: '查看角色人员', code: 'roleUser', isDefault: true }
    ]);
    //展示在列表内的按钮
    const actionButtons = ref<string[]>(['roleUser']);
    const buttonConfigs = computed(() => {
        return filterButtonAuth(buttons.value);
    });

    const tableButtonConfig = computed(() => {
        return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
    });

    const actionButtonConfig = computed(() => {
        return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
    });

    const btnEvent = {
        roleUser: handleRoleUser,
        editRole: handleEditRole
    };

    const { currentRoute } = useRouter();
    const router = useRouter();
    const formIdComputedRef = ref();
    formIdComputedRef.value = currentRoute.value.meta.formId;
    const schemaIdComputedRef = ref();
    schemaIdComputedRef.value = currentRoute.value.meta.schemaId;
    const selectId = ref('');

    const treeData = ref([]);

    const roleDatasource = ref<any[]>([]);

    const [registerModal, { openModal, setModalProps }] = useModal();
    const [registerRoleModal, { openModal: openRoleModal, setModalProps: setRoleModalProps }] = useModal();
    const [registerAuthModal, { openModal: openGroupUserModal, setModalProps: setGroupUserProps }] = useModal();

    const formName = '角色权限查看';
    const [registerTable, { reload }] = useTable({
        title: '' || formName + '列表',
        api: getRolePermissionPage,
        rowKey: 'id',
        columns: customConfigColums,
        formConfig: {
            rowProps: {
                gutter: 16
            },
            schemas: customSearchFormSchema,
            fieldMapToTime: [],
            showResetButton: false
        },
        beforeFetch: (params) => {
            if (!params.menuId) {
                params.menuId = selectId.value;
            }
            return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
        },
        afterFetch: (res) => {
            tableRef.value.setToolBarWidth();
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
            width: 220,
            title: '操作',
            dataIndex: 'action',
            slots: { customRender: 'action' }
        },
        tableSetting: {
            size: false,
            setting: false
        }
    });

    function dbClickRow(record) {}

    function handleGroupClick(groupId, groupName) {
        getGroupUser(groupId).then((res) => {
            openGroupUserModal(true, res);
            setGroupUserProps({ title: t('查看用户组成员') });
        });
    }

    function handleRoleUser(record) {
        getRoleUser(record.id).then((res) => {
            openModal(true, res);
            setModalProps({ title: t('查看成员') });
        });
    }

    function handleEditRole() {
        if (!selectId.value) {
            notification.warning({
                message: t('警告'),
                description: t('必须选中一个菜单！')
            });
            return false;
        }
        if (selectId.value === 'menu') {
            notification.warning({
                message: t('警告'),
                description: t('此选项无效！')
            });
            return false;
        }
        //弹出角色选择框
        openRoleModal(true, {
            roles: roleDatasource.value
        });
        setRoleModalProps({
            okText: '修改角色',
            title: '修改角色'
        });
    }

    const handleRoleSuccess = async (data) => {
        roleDatasource.value = data;
        let param = {
            menuId: selectId.value,
            roles: roleDatasource.value ? roleDatasource.value.map((e) => e.id) : []
        };
        let res = await updateRolePermission(param);
        if (res) {
            notification.success({
                message: t('成功'),
                description: t('更新成功！')
            });
        }
        await reload();
    };

    function buttonClick(code) {
        btnEvent[code]();
    }

    function handleSuccess() {
        reload();
    }

    async function handleSelect(selectIds) {
        selectId.value = selectIds[0];
        let res = await reload({ searchInfo: { menuId: selectIds[0] } });
        roleDatasource.value = res;
    }

    async function fetchTree() {
        treeData.value = await getMenuTree();
    }

    onMounted(() => {
        fetchTree();
        // 合并渲染覆盖配置中的列表配置，包括展示字段配置、搜索字段配置、按钮配置
        mergeCustomListRenderConfig();
    });

    onUnmounted(() => {
        /*if (schemaIdComputedRef.value) {
            bus.off(FLOW_PROCESSED, handleRefresh);
            bus.off(CREATE_FLOW, handleRefresh);
        } else {
            bus.off(FORM_LIST_MODIFIED, handleRefresh);
        }*/
    });

    function getActions(record: Recordable): ActionItem[] {
        const actionsList: ActionItem[] = actionButtonConfig.value?.map((button) => {
            if (!record.workflowData?.processId) {
                return {
                    icon: button?.icon,
                    tooltip: button?.name,
                    color: button.code === 'delete' ? 'error' : undefined,
                    onClick: btnEvent[button.code].bind(null, record),
                    label: button?.name,
                    code: button?.code
                };
            } else {
                if (button.code === 'view') {
                    return {
                        icon: button?.icon,
                        tooltip: button?.name,
                        onClick: btnEvent[button.code].bind(null, record),
                        label: button?.name,
                        code: button?.code
                    };
                } else {
                    return {};
                }
            }
        });
        return actionsList;
    }

    async function mergeCustomListRenderConfig() {
        if (formConfig.useCustomConfig) {
            let formId = currentRoute.value.meta.formId;
            //1.合并展示字段配置
            let cols = await mergeColumns(customConfigColums.value, formId);
            customConfigColums.value = cols;
            //2.合并搜索字段配置
            let sFormSchema = await mergeSearchFormSchema(customSearchFormSchema.value, formId);
            customSearchFormSchema.value = sFormSchema;
            //3.合并按钮配置
            let btns = await mergeButtons(buttons.value, formId);
            buttons.value = btns;
        }
    }
</script>

<style lang="less" scoped>
    :deep(.ant-table-selection-col) {
        width: 50px;
    }

    .show {
        display: flex;
    }

    .hide {
        display: none !important;
    }

    /*.ant-table-title {
        display: none !important;
    }*/
</style>
