import { IconFont } from '@/components';
import SysMenuController from '@/services/apis/SysMenuController';
import { MenuType } from '@/services/enums';
import { RightOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
    DrawerForm,
    ProFormCheckbox,
    ProFormDigit,
    ProFormRadio,
    ProFormText,
} from '@ant-design/pro-form';
import { Col, Row, Select, message } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import { DefaultActionOptions } from '../../utils';

export interface MenuEditProps {
    parentMenus: API.SysMenuOutput[];
    data: Partial<API.SysMenuOutput>;
    onOk: () => void;
    onClose: () => void;
}

type FormDataType = Omit<API.SysMenuOutput, 'id'>;

/** 编辑菜单 */
const MenuEditDrawer: React.FC<MenuEditProps> = ({ parentMenus, data, onOk, onClose }) => {
    const [visible, setVisible] = useState<boolean>(true);
    const handleClose = () => {
        setVisible(false);
        setTimeout(onClose, 300);
    };

    const { getDictOptions } = useModel('useDict');

    const [menuType, setMenuType] = useState<number>(data.menuType ?? MenuType.FOLDER);
    const [icon, setIcon] = useState<string | undefined>(data.icon);
    const formRef = useRef<ProFormInstance>();

    const actions = data.permission?.split('.');
    let saction: string | undefined;
    if (actions && actions.length > 0) {
        saction = actions[actions.length - 1];
    }
    const [actionType, setActionType] = useState<string | undefined>(saction);

    const handleSubmit = async (values: FormDataType) => {
        try {
            if (data.id === 0) {
                const params = { ...values, pid: data.pid } as API.AddSysMenuInput;
                await SysMenuController.add(params);
            } else {
                const params = { ...data, ...values, id: data.id } as API.UpdateSysMenuInput;
                await SysMenuController.update(params);
            }
            message.success('保存成功！');
            onOk();
            handleClose();
        } catch { }
    };

    return (
        <DrawerForm<FormDataType>
            title={`${data.id === 0 ? '添加' : '修改'}功能菜单`}
            formRef={formRef}
            open={visible}
            drawerProps={{
                onClose: handleClose,
                headerStyle: { paddingLeft: 4 },
                width: 800,
                styles: {
                    body: { backgroundColor: '#f2f2f2' },
                },
            }}
            initialValues={data}
            onFinish={handleSubmit}
        >
            <Row gutter={[24, 0]}>
                <Col span={24}>
                    <ProFormText label="父级路径" readonly>
                        <strong>
                            全部
                            {parentMenus?.map((t) => (
                                <span key={`${t.id}`}>
                                    <RightOutlined style={{ margin: '0 4px' }} />
                                    {t.name}
                                </span>
                            ))}
                        </strong>
                    </ProFormText>
                </Col>
                <Col span={24}>
                    <ProFormRadio.Group
                        label="类型"
                        radioType="button"
                        readonly={data.id !== 0}
                        fieldProps={{
                            buttonStyle: 'solid',
                            onChange: (e) => {
                                const mt = e.target.value;
                                setMenuType(mt);
                            },
                        }}
                        name="menuType"
                        rules={[{ required: true }]}
                        options={getDictOptions('menu_type').map((t) => ({
                            ...t,
                            value: t.value,
                        }))}
                    />
                </Col>
                {menuType === MenuType.BUTTON && (
                    <Col span={24}>
                        <ProFormText
                            label="权限标识（根据父路径国际化标识名称和操作类型组合）"
                            name="permission"
                            addonBefore={
                                <Select
                                    value={actionType}
                                    options={DefaultActionOptions}
                                    style={{ width: 160 }}
                                    onChange={(authCode) => {
                                        setActionType(authCode);
                                        const ps = parentMenus.map((t) => t.name);
                                        ps.push(authCode);
                                        const form = formRef.current;
                                        if (form) {
                                            const name =
                                                DefaultActionOptions.find(
                                                    (t) => t.value === authCode,
                                                )?.label ?? '';
                                            form.setFieldsValue({
                                                permission: ps.join('.'),
                                                code: authCode,
                                                name,
                                            });
                                        }
                                    }}
                                />
                            }
                            // readonly
                            rules={[{ required: true, max: 1000 }]}
                            fieldProps={{ showCount: true, maxLength: 1000 }}
                        />
                    </Col>
                )}
                <Col span={24}>
                    <ProFormText
                        label="名称"
                        name="name"
                        rules={[{ required: true, max: 80 }]}
                        fieldProps={{ showCount: true, maxLength: 80 }}
                    />
                </Col>
                <Col span={24}>
                    <ProFormText
                        label="国际化标识名称（英文小写字母、中短横线，菜单和目录只填本级）"
                        name="code"
                        rules={[{ required: true, max: 160 }]}
                        fieldProps={{ showCount: true, maxLength: 160 }}
                    />
                </Col>
                {[MenuType.FOLDER, MenuType.MENU].includes(menuType) && (
                    <>
                        <Col span={12}>
                            <ProFormDigit
                                label="顺序"
                                name="sort"
                                tooltip="在每一级的排列顺序"
                                rules={[{ required: true }]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label="图标"
                                name="icon"
                                tooltip="自定义iconfont图标名称"
                                addonAfter={
                                    icon && (
                                        <IconFont
                                            icon={icon}
                                            style={{
                                                lineHeight: 1,
                                                fontSize: 22,
                                                display: 'block',
                                            }}
                                        />
                                    )
                                }
                                fieldProps={{
                                    onChange: (e) => setIcon(e.target.value),
                                    showCount: true,
                                    maxLength: 80,
                                }}
                                rules={[{ max: 80 }]}
                            />
                        </Col>
                    </>
                )}
                {menuType !== MenuType.BUTTON && (
                    <>
                        <Col span={24}>
                            <ProFormText
                                label="路由地址"
                                name="router"
                                fieldProps={{
                                    showCount: true,
                                    maxLength: 1000,
                                }}
                                rules={[{ required: menuType === MenuType.MENU, max: 1000 }]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormText
                                label="组件路径"
                                name="component"
                                fieldProps={{
                                    showCount: true,
                                    maxLength: 1000,
                                }}
                                rules={[{ max: 1000 }]}
                            />
                        </Col>
                    </>
                )}
                <Col span={12}>
                    <ProFormCheckbox label="是否显示" name="visible" />
                </Col>
            </Row>
        </DrawerForm>
    );
};

export default MenuEditDrawer;
