import { validateIdCard } from '@/common/validator';
import { MovableModalForm } from '@/components';
import ExamSpecialStudentController from '@/services/apis/ExamSpecialStudentController';
import { CertificateType } from '@/services/enums';
import { FormInstance, ProFormDigit, 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';

export type GradeBranchData = {
    examGrades: API.ExamGradeOutput[];
    branches: API.SysOrgLiteOutput[];
};

/** 修改监测特殊学生信息 */
const ExamSpecialStudentEditModal: React.FC<{
    examPlanId: number;
    data: Partial<API.ExamSpecialStudentOutput>;
    gradeBranch: GradeBranchData;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ examPlanId, data, gradeBranch, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const formRef = useRef<FormInstance>();
    const { message } = App.useApp();

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

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

    return (
        <>
            <MovableModalForm<API.ExamSpecialStudentOutput>
                title={`${data.id === 0 ? '添加' : '修改'}监测学生信息`}
                width={800}
                open={open}
                formRef={formRef}
                initialValues={{
                    ...data,
                    examGradeId: data.examGradeId !== undefined ? data.examGradeId : undefined,
                    sysOrgBranchId: data.sysOrgBranchId !== undefined ? data.sysOrgBranchId : undefined,
                    certificateType: data.certificateType !== undefined ? data.certificateType : undefined,
                    gender: data.gender !== undefined ? `${data.gender}` : undefined,
                }}
                modalProps={{
                    centered: true,
                    maskClosable: false,
                    onCancel: () => {
                        formRef?.current?.resetFields();
                        handleClose();
                    },
                }}
                onFinish={async (values) => {
                    const { examGradeId, certificateType, gender, ...restValues } = values;
                    const grade = gradeBranch.examGrades.find(t => t.id === examGradeId);
                    if (!grade) {
                        return;
                    }

                    let p: API.AddExamSpecialStudentInput = {
                        ...restValues,
                        examPlanId,
                        examGradeId,
                        gradeId: grade.gradeId,
                        certificateType: JSON.parse(certificateType as any),
                        gender: JSON.parse(gender as any),
                    };
                    if (data.id !== 0) {
                        const up = { id: data.id ?? 0, ...p } as API.UpdateExamSpecialStudentInput;
                        await ExamSpecialStudentController.update(up);
                    }
                    else {
                        await ExamSpecialStudentController.add(p);
                    }
                    message.success('已保存');

                    onFinish();
                    handleClose();
                }}
            >
                <Row gutter={[24, 0]}>
                    <Col span={12}>
                        <ProFormSelect
                            label="年级"
                            name="examGradeId"
                            options={gradeBranch?.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 }]}
                            disabled={data.id !== 0}
                        />
                    </Col>
                    {gradeBranch.branches && gradeBranch.branches.length > 0 &&
                        <Col span={12}>
                            <ProFormSelect
                                label="校区"
                                name="sysOrgBranchId"
                                options={gradeBranch.branches.map(t => ({ label: t.name, 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}>
                        <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) => setCertType(JSON.parse(v as string))}
                        />
                    </Col>
                    <Col span={12}>
                        <ProFormText
                            label="证件号码"
                            name="idNumber"
                            dependencies={['certificateType']}
                            fieldProps={{
                                maxLength: 18,
                                showCount: true,
                            }}
                            required={certType !== 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="家长电话"
                            name="patriarchTel"
                            fieldProps={{
                                maxLength: 50,
                                showCount: true
                            }}
                            required
                            rules={[{ required: true, min: 8 }]}
                        />
                    </Col>
                </Row>
                <ProFormTextArea
                    label="特殊原因"
                    name="applyReason"
                    fieldProps={{
                        maxLength: 2000,
                        rows: 4,
                        showCount: true,
                    }}
                    required
                    rules={[{ required: true }]}
                />
                <ProFormTextArea
                    label="备注"
                    name="remark"
                    fieldProps={{
                        maxLength: 200,
                        rows: 2,
                        showCount: true,
                    }}
                />
            </MovableModalForm >
        </>
    );
};

export default ExamSpecialStudentEditModal;
