import { PERMISSIONS } from '@/common/constant';
import { getParentPath } from '@/common/converter';
import { IconFont, SuperTable } from '@/components';
import SysMenuController from '@/services/apis/SysMenuController';
import { MenuType } from '@/services/enums';
import {
    CheckCircleFilled,
    CloseCircleFilled,
    CopyOutlined,
    DeleteOutlined,
    EditOutlined,
    EllipsisOutlined,
    FolderFilled,
    MenuOutlined,
    PlusOutlined,
    YoutubeFilled,
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { useAccess, useModel } from '@umijs/max';
import { Button, Dropdown, Modal, Typography, message } from 'antd';
import type { ItemType } from 'rc-menu/lib/interface';
import { useRef, useState } from 'react';
import { buildPermissionConstant } from '../utils';
import CopyPermissionCodeDrawer from './components/CopyPermissionCodeDrawer';
import MenuEditDrawer from './components/MenuEditDrawer';

const IconTag = (enabled: boolean) => {
    if (enabled) {
        return <CheckCircleFilled size={10} style={{ color: '#52c41a' }} />;
    } else {
        return <CloseCircleFilled size={10} style={{ color: '#f5222d' }} />;
    }
};

type MenuItemType = ItemType & { icon?: JSX.Element };

/** 功能菜单管理 */
const MenuList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const dataRef = useRef<API.SysMenuOutput[]>();
    const currentRef = useRef<Partial<API.SysMenuOutput> | undefined>();
    const [editVisible, setEditVisible] = useState(false);
    const [copyCodeVisible, setCopyCodeVisible] = useState(false);
    const permissionCodeRef = useRef<string | undefined>(undefined);

    const { hasPermission } = useAccess();

    const { getDictValueEnum } = useModel('useDict');
    const menuTypeValueEnum = getDictValueEnum('menu_type');

    const columns: ProColumns<API.SysMenuOutput>[] = [
        {
            title: '名称',
            dataIndex: 'name',
            tip: '显示文本',
            fixed: true,
            render: (v, r) => {
                const menus: MenuItemType[] = [];
                if ([MenuType.FOLDER, MenuType.MENU].includes(r.menuType)) {
                    if (hasPermission(PERMISSIONS.SYS.MENU.OP_ADD)) {
                        menus.push({ key: 'add', label: '添加子项', icon: <PlusOutlined /> });
                    }
                }
                if (r.id > 0) {
                    if (menus.length > 0) {
                        menus.push({ type: 'divider' });
                    }
                    if (hasPermission(PERMISSIONS.SYS.MENU.OP_EDIT)) {
                        menus.push({ key: 'edit', label: '编辑', icon: <EditOutlined /> });
                    }
                    if (hasPermission(PERMISSIONS.SYS.MENU.OP_DEL)) {
                        menus.push({ key: 'delete', label: '删除', icon: <DeleteOutlined /> });
                    }
                }

                return (
                    <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                        {r.menuType === MenuType.FOLDER && <FolderFilled style={{ color: '#faad14' }} />}
                        {r.menuType === MenuType.MENU && <MenuOutlined style={{ color: '#1890ff' }} />}
                        {r.menuType === MenuType.BUTTON && (
                            <YoutubeFilled style={{ color: '#1890ff' }} />
                        )}
                        <div style={{ marginLeft: 4, flex: 1 }}>{v}</div>
                        <Dropdown
                            menu={{
                                onClick: (e) => {
                                    let menu_type = MenuType.FOLDER;

                                    if (menu_type === MenuType.FOLDER) {
                                        menu_type = MenuType.MENU;
                                    } else if (menu_type === MenuType.MENU) {
                                        menu_type = MenuType.BUTTON;
                                    }

                                    if (e.key === 'add') {
                                        currentRef.current = {
                                            id: 0,
                                            pid: r.id,
                                            visible: true,
                                            menuType: menu_type,
                                        };
                                        setEditVisible(true);
                                    } else if (e.key === 'edit') {
                                        currentRef.current = r;
                                        setEditVisible(true);
                                    } else if (e.key === 'delete') {
                                        Modal.confirm({
                                            title: '警告',
                                            content: '删除后不能恢复，是否立即删除？',
                                            okText: '是',
                                            cancelText: '否',
                                            centered: true,
                                            onOk: async () => {
                                                try {
                                                    await SysMenuController.del({
                                                        id: r.id,
                                                    });
                                                    message.success('删除成功！');
                                                    actionRef.current?.reload();
                                                } catch { }
                                            },
                                        });
                                    }
                                },
                                items: menus,
                            }}
                        >
                            <EllipsisOutlined style={{ cursor: 'pointer' }} />
                        </Dropdown>
                    </div>
                );
            },
        },
        {
            title: '类型',
            dataIndex: 'menuType',
            valueEnum: menuTypeValueEnum,
            width: 48,
            align: 'center',
            fixed: true,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 56,
            align: 'center',
        },
        {
            title: '图标',
            dataIndex: 'icon',
            width: 160,
            render: (v, r) => {
                if (r.icon) {
                    return (
                        <div style={{ display: 'inline-flex', alignItems: 'center' }}>
                            <IconFont icon={r.icon} style={{ lineHeight: 1, marginRight: 4 }} />
                            {v}
                        </div>
                    );
                }
                return v;
            },
        },
        {
            title: '国际化名称',
            dataIndex: 'code',
            width: 160,
        },
        {
            title: '地址',
            dataIndex: 'router',
        },
        {
            title: '权限标识',
            dataIndex: 'permission',
            className: 'minw-80',
            renderText: (v) => v && <Typography.Text copyable>{v}</Typography.Text>,
        },
        // {
        //     title: 'iframe',
        //     dataIndex: 'is_frame',
        //     width: 56,
        //     align: 'center',
        //     render: (_, r) =>
        //         r.type != MenuType.menu.id || r.is_frame === undefined ? null : IconTag(r.is_frame),
        // },
        {
            title: '显示',
            dataIndex: 'visible',
            width: 48,
            align: 'center',
            render: (_, r) => (r.visible === undefined ? null : IconTag(r.visible)),
        },
    ];

    return (
        <PageContainer title={false} childrenContentStyle={{ paddingTop: 0 }}>
            <SuperTable<API.SysMenuOutput>
                actionRef={actionRef}
                search={false}
                bordered
                headerTitle="目录菜单按钮树"
                columns={columns}
                pagination={false}
                request={async () => {
                    const res = (await SysMenuController.getAllTreeList({})) ?? [];
                    const resMenus = res ?? [];
                    dataRef.current = resMenus;

                    const ms: API.SysMenuOutput[] = [];
                    const flattenMenu = (menus: API.SysMenuOutput[]) => {
                        menus?.filter((t) => t.menuType !== MenuType.BUTTON)
                            ?.forEach((m) => {
                                const { children, ...restMenu } = m;
                                ms.push(restMenu);
                                if (children) {
                                    flattenMenu(children);
                                }
                            });
                    };
                    flattenMenu(resMenus);
                    return {
                        success: true,
                        data: resMenus,
                    };
                }}
                postData={(rows: API.SysMenuOutput[]) => {
                    return [
                        {
                            id: 0,
                            name: '全部',
                            children: rows,
                            menuType: MenuType.FOLDER,
                            visible: true,
                        },
                    ];
                }}
                expandable={{
                    defaultExpandedRowKeys: [0],
                }}
                toolbar={{
                    actions: [
                        <Button
                            key="copy-permssion"
                            icon={<CopyOutlined />}
                            onClick={() => {
                                let pcode = buildPermissionConstant(dataRef.current ?? []);
                                pcode = `/** 权限标识 */\nexport const PERMISSIONS = {${pcode}\n};`;
                                console.log(pcode);
                                permissionCodeRef.current = pcode;
                                setCopyCodeVisible(true);
                            }}
                        >
                            输出权限代码
                        </Button>,
                    ],
                }}
            />
            {editVisible && currentRef.current && (
                <MenuEditDrawer
                    parentMenus={
                        getParentPath(
                            dataRef.current ?? [],
                            `${currentRef.current.pid}`,
                            'id',
                            'pid',
                        ) as API.SysMenuOutput[]
                    }
                    data={{ ...currentRef.current }}
                    onOk={() => actionRef.current?.reload()}
                    onClose={() => setEditVisible(false)}
                />
            )}
            {copyCodeVisible && permissionCodeRef.current && (
                <CopyPermissionCodeDrawer
                    code={permissionCodeRef.current}
                    onClose={() => setCopyCodeVisible(false)}
                />
            )}
        </PageContainer>
    );
};

export default MenuList;
