import { validateIdCard } from '@/common/validator';
import { MovableModalForm } from '@/components';
import ExamTeacherController from '@/services/apis/ExamTeacherController';
import { CertificateType, SchoolJobTitle } from '@/services/enums';
import { FormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { App, Col, Row } from 'antd';
import { useRef, useState } from 'react';

/** 修改监测教师信息 */
const ExamTeacherEditModal: React.FC<{
    examPlanId: number;
    data: Partial<API.ExamTeacherOutput>;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ examPlanId, data, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const formRef = useRef<FormInstance>();

    const { getDictValueEnum, } = useModel('useDict');

    const [certificateType, setCertificateType] = useState(data.certificateType);
    const { message } = App.useApp();

    return (
        <>
            <MovableModalForm<API.ExamTeacherOutput>
                title={`${data.id === 0 ? '添加' : '修改'}监测教师信息`}
                width={1080}
                open={open}
                formRef={formRef}
                initialValues={{
                    ...data,
                    certificateType: data.certificateType !== undefined ? `${data.certificateType}` : undefined,
                    schoolJobTitle: data.schoolJobTitle !== undefined ? `${data.schoolJobTitle}` : undefined,
                    gender: data.gender !== undefined ? `${data.gender}` : undefined,
                }}
                modalProps={{
                    centered: true,
                    maskClosable: false,
                    onCancel: () => {
                        formRef?.current?.resetFields();
                        handleClose();
                    },
                }}
                onFinish={async (values) => {
                    const { certificateType, gender, schoolJobTitle, ...restValues } = values;

                    let p: API.AddExamTeacherInput = {
                        ...restValues,
                        examPlanId,
                        certificateType: JSON.parse(certificateType as any),
                        gender: JSON.parse(gender as any),
                        schoolJobTitle: schoolJobTitle ? JSON.parse(schoolJobTitle as any) : SchoolJobTitle.UNKNOWN,
                    };
                    if (data.id !== 0) {
                        const up = { id: data.id ?? 0, ...p } as API.UpdateExamTeacherInput;
                        await ExamTeacherController.update(up);
                    }
                    else {
                        await ExamTeacherController.add(p);
                    }
                    message.success('已保存');

                    onFinish();
                    handleClose();
                }}
            >
                <Row gutter={[24, 0]}>
                    <Col span={12}>
                        <ProFormText
                            label="姓名"
                            name="name"
                            required
                            rules={[{ required: true, min: 2, max: 100 }]}
                            fieldProps={{
                                minLength: 2,
                                maxLength: 100,
                                showCount: true,
                            }}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormSelect
                            label="证件类型"
                            name="certificateType"
                            rules={[{ required: true }]}
                            valueEnum={getDictValueEnum('certificate_type')}
                            onChange={(v) => setCertificateType(JSON.parse(v as string))}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormText
                            label="证件号码"
                            name="idNumber"
                            dependencies={['certificateType']}
                            fieldProps={{
                                maxLength: 18,
                                showCount: true,
                            }}
                            required={certificateType !== CertificateType.NONE}
                            rules={[
                                ({ getFieldValue, setFieldsValue }) => ({
                                    validator: (_, value) => {
                                        const ct = JSON.parse(getFieldValue("certificateType"));
                                        if (ct === CertificateType.NONE) {
                                            return Promise.resolve();
                                        }
                                        if (ct === CertificateType.ID_CARD) {
                                            const idc = validateIdCard(value);
                                            if (idc.success) {
                                                setFieldsValue({ gender: `${idc.gender}` });
                                                return Promise.resolve();
                                            }
                                            else {
                                                return Promise.reject(`身份证号${idc.errorMessage}有误`);
                                            }
                                        }
                                        if (value.length > 0) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject('证件号码必须输入');
                                    },
                                }),
                            ]}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormRadio.Group
                            label="性别"
                            name="gender"
                            valueEnum={getDictValueEnum('gender')}
                            required
                            rules={[{ required: true }]}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormSelect
                            label="校内职务"
                            name="schoolJobTitle"
                            valueEnum={getDictValueEnum('school_job_title')}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormText
                            label="手机号码"
                            name="mobile"
                            fieldProps={{
                                maxLength: 50,
                                showCount: true
                            }}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormText
                            label="电子邮箱"
                            name="email"
                            fieldProps={{
                                maxLength: 200,
                                showCount: true
                            }}
                        />
                    </Col>
                </Row>
                <ProFormTextArea
                    label="备注"
                    name="remark"
                    fieldProps={{
                        maxLength: 200,
                        rows: 4,
                        showCount: true,
                    }}
                />
            </MovableModalForm >
        </>
    );
};

export default ExamTeacherEditModal;
