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

/** 修改监测教师任教科目 */
const ExamTeacherCourseImportEditModal: React.FC<{
    data: Partial<API.UploadExamTeacherCourseOutput>;
    examGrades: API.ExamGradeOutput[];
    onFinish: (values: API.UploadExamTeacherCourseOutput) => void;
    onClose?: () => void;
}> = ({ data, examGrades, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const formRef = useRef<FormInstance>();

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

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

    return (
        <>
            <MovableModalForm<API.UploadExamTeacherCourseOutput>
                title="修改导入教师任教科目"
                width={800}
                open={open}
                formRef={formRef}
                initialValues={{
                    ...data,
                    certificateType: data.certificateType !== undefined ? data.certificateType : undefined,
                    courseId: data.courseId !== undefined ? data.courseId : undefined,
                }}
                modalProps={{
                    centered: true,
                    maskClosable: false,
                    onCancel: () => {
                        formRef?.current?.resetFields();
                        handleClose();
                    },
                }}
                onFinish={async (values) => {
                    const { examGradeId, courseId, ...restValues } = values;
                    const eg = examGrades.find(t => t.id === examGradeId);
                    const cu = baseData?.courses?.find(t => t.id === courseId);
                    onFinish({
                        ...data,
                        ...restValues,
                        examGradeId,
                        gradeId: eg?.gradeId,
                        courseId,
                        courseName: cu?.name,
                        isSuccess: true,
                        errorMessage: [],
                    });
                    handleClose();
                }}
            >
                <Row gutter={[24, 0]}>
                    <Col span={12}>
                        <ProFormSelect
                            label="年级"
                            name="examGradeId"
                            options={examGrades?.sort((a, b) => a.grade.gradeNumber - b.grade.gradeNumber)?.map(t => ({ label: `${t.grade.fullName}（${t.gradeBeginName}）`, value: t.id }))}
                            required
                            rules={[{ required: true }]}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormDigit
                            label="班级"
                            tooltip="班级最小1，最大35"
                            name="classNumber"
                            min={1}
                            max={35}
                            required
                            rules={[{ required: true }]}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormSelect
                            label="科目"
                            name="courseId"
                            valueEnum={toValueEnum(baseData?.courses ?? [])}
                            options={baseData?.courses?.map(t => ({ label: t.name, value: t.id }))}
                            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 }]}
                            fieldProps={{ options: getDictOptions('certificate_type').filter(t => t.value !== 0) }}
                            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>
                </Row>
                <ProFormTextArea
                    label="备注"
                    name="remark"
                    fieldProps={{
                        maxLength: 200,
                        rows: 4,
                        showCount: true,
                    }}
                />
            </MovableModalForm >
        </>
    );
};

export default ExamTeacherCourseImportEditModal;
