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

/** 修改监测学生信息 */
const ExamStudentImportEditModal: React.FC<{
    isRequiredSelfExamNumber?: boolean;
    selfExamNumberLength?: number;
    data: Partial<API.UploadExamStudentOutput>;
    hasNceeCourseComb?: boolean;
    onFinish: (values: API.UploadExamStudentOutput) => void;
    onClose?: () => void;
}> = ({ data, isRequiredSelfExamNumber, selfExamNumberLength, hasNceeCourseComb, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const formRef = useRef<FormInstance>();

    const { getDictValueEnum } = useModel('useDict');
    const { baseData } = useModel('useBaseData');

    const [certificateType, setCertificateType] = useState(data.certificateType);

    useEffect(() => { formRef.current?.validateFields(); }, []);

    return (
        <MovableModalForm<API.UploadExamStudentOutput>
            title="修改导入学生信息"
            width={800}
            open={open}
            formRef={formRef}
            initialValues={{
                ...data,
                certificateType: data.certificateType !== undefined ? `${data.certificateType}` : undefined,
                gender: data.gender !== undefined ? `${data.gender}` : undefined,
                nceeCourseCombId: data.nceeCourseCombId !== undefined ? data.nceeCourseCombId : undefined,
            }}
            modalProps={{
                centered: true,
                maskClosable: false,
                onCancel: () => {
                    formRef?.current?.resetFields();
                    handleClose();
                },
            }}
            onFinish={async (values) => {
                const { name, idNumber, examNumber, roomNumber, seatNumber, remark, nceeCourseCombId, ...restValues } = values;
                const cmb = baseData?.nceeCourseCombs?.find(t => t.id === nceeCourseCombId);
                onFinish({
                    ...data,
                    ...restValues,
                    name: name.replaceAll(/\s/g, ''),
                    idNumber: idNumber?.replaceAll(/\s/g, ''),
                    examNumber: examNumber?.replaceAll(/\s/g, ''),
                    roomNumber: roomNumber?.replaceAll(/\s/g, ''),
                    seatNumber: seatNumber?.replaceAll(/\s/g, ''),
                    remark: remark?.replaceAll(/\s/g, ''),
                    nceeCourseCombId,
                    nceeCourseCombName: cmb?.shortName,
                    isSuccess: true,
                    errorMessage: [],
                });
                handleClose();
            }}
        >
            <Row gutter={[24, 0]}>
                <Col span={12}>
                    <ProFormDigit
                        label="班级"
                        tooltip="班级最小1，最大35"
                        name="classNumber"
                        min={1}
                        max={35}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <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}>
                    <ProFormText
                        label={`自编监测号${isRequiredSelfExamNumber ? `（当前年级必录，长度为${selfExamNumberLength}位）` : ''}`}
                        // label={`自编监测号`}
                        // tooltip={`（当前年级必录，长度为${selfExamNumberLength}位）`}
                        name="examNumber"
                        fieldProps={{
                            maxLength: isRequiredSelfExamNumber ? selfExamNumberLength : 20,
                            showCount: true
                        }}
                        required={isRequiredSelfExamNumber}
                        rules={[
                            // { required: isRequiredSelfExamNumber, message: '当前年级必录' },
                            () => ({
                                validator: (_, value) => {
                                    if (!isRequiredSelfExamNumber) {
                                        return Promise.resolve();
                                    }
                                    if ((value ?? '').length !== selfExamNumberLength) {
                                        return Promise.reject(`当前年级必录，长度为${selfExamNumberLength}位`);
                                    }
                                    return Promise.resolve();
                                },
                            }),
                        ]}
                    />
                </Col>
                {hasNceeCourseComb &&
                    <Col span={12}>
                        <ProFormSelect
                            label="选科组合"
                            name="nceeCourseCombId"
                            options={baseData?.nceeCourseCombs?.map(t => ({ label: t.shortName, value: t.id }))}
                        />
                    </Col>
                }
                <Col span={12}>
                    <ProFormText
                        label="考场号"
                        name="roomNumber"
                        fieldProps={{
                            maxLength: 20,
                            showCount: true
                        }}
                    />
                </Col>
                <Col span={12}>
                    <ProFormText
                        label="座位号"
                        name="seatNumber"
                        fieldProps={{
                            maxLength: 20,
                            showCount: true
                        }}
                    />
                </Col>
            </Row>
            <ProFormTextArea
                label="备注"
                name="remark"
                fieldProps={{
                    maxLength: 200,
                    rows: 4,
                    showCount: true,
                }}
            />
        </MovableModalForm >
    );
};

export default ExamStudentImportEditModal;
