import * as React from 'react';
import { Modal, Spin, Form, Input, Select, message } from 'antd';
import { apis, CreateOrModifyUserApiParams } from '@/apis';
import { regex } from '@/utils';

const FormItem = Form.Item;
const { Option } = Select;

interface Props {
    id: string,
    open: boolean,
    onClickConfirm: (id: string, data: CreateOrModifyUserApiParams) => Promise<any>,
    onClickCancel: () => void,
};

const InfoModal: React.FC<Props> = (props: Props) => {
    const {
        id,
        open,
        onClickConfirm,
        onClickCancel
    } = props;

    const [form] = Form.useForm();

    const [loading, setLoading] = React.useState<boolean>(false);

    const getTitle = () => {
        if (id) {
            return '修改用户';
        } else {
            return '创建用户';
        }
    };

    const fetchDetail = async () => {
        try {
            const res = await apis.fetchUserDetail(props.id);
            form.setFieldsValue(res.data);
        } catch (error: any) {
            message.error(error.msg);
        }
    };

    const init = async () => {
        setLoading(true);
        if (props.id) {
            await fetchDetail();
        }
        setLoading(false);
    };

    React.useEffect(() => {
        init();
    }, []);

    // 检查手机号码
    const checkPhoneNumber = (rule: any, value: string) => {
        if (value) {
            const phoneNumberRegex = new RegExp(regex.phoneNumber);
            if (phoneNumberRegex.test(value)) {
                return Promise.resolve();
            } else {
                return Promise.reject(new Error('手机号码格式不正确'));
            }
        } else {
            return Promise.reject('手机号码不能为空');
        }
    };

    // 检查登录密码
    const checkPassword = (rule: any, value: string) => {
        if (value) {
            const passwordRegex = new RegExp(regex.password);
            if (passwordRegex.test(value)) {
                return Promise.resolve();
            } else {
                return Promise.reject('登录密码格式不正确');
            }
        } else {
            return Promise.reject('登录密码不能为空');
        }
    };

    // 点击确定
    const handleClickConfirm = () => {
        form.validateFields().then(async (values) => {
            const data = { ...values };
            await onClickConfirm(props.id, data);
        }).catch((error) => {
            console.error(error);
        });
    };

    return (
        <Modal
            width={600}
            title={getTitle()}
            destroyOnClose={true}
            maskClosable={false}
            centered={true}
            open={open}
            onOk={handleClickConfirm}
            onCancel={onClickCancel}
        >
            <div className='infoModal'>
                <Spin spinning={loading}>
                    <Form form={form} layout='vertical'>
                        <FormItem
                            label='姓名'
                            name='user_name'
                            rules={[{ required: true, message: '姓名不能为空', whitespace: true }]}
                        >
                            <Input
                                style={{ width: '100%' }}
                                placeholder='请输入姓名'
                            />
                        </FormItem>
                        <FormItem
                            label='手机号码'
                            name='phone_number'
                            rules={[{ validator: checkPhoneNumber, required: true }]}
                        >
                            <Input
                                style={{ width: '100%' }}
                                placeholder='请输入手机号码'
                                maxLength={11}
                            />
                        </FormItem>
                        <FormItem
                            label='登录密码'
                            name='password'
                            rules={[{ validator: checkPassword, required: true }]}
                        >
                            <Input.Password
                                style={{ width: '100%' }}
                                placeholder='6-16位字母或数字组合'
                            />
                        </FormItem>
                        <FormItem
                            label='角色'
                            name='role'
                            rules={[{ required: true, message: '角色不能为空' }]}
                        >
                            <Select
                                style={{ width: '100%' }}
                                placeholder='请选择角色'
                                allowClear={true}
                            >
                                <Option value='USER'>
                                    用户
                                </Option>
                                <Option value='ADMIN'>
                                    管理员
                                </Option>
                            </Select>
                        </FormItem>
                    </Form>
                </Spin>
            </div>
        </Modal>
    );
};

export default InfoModal;