import { toValueEnum } from '@/common/converter';
import { validateIdCard } from '@/common/validator';
import { MovableModalForm } from '@/components';
import ExamTeacherCourseController from '@/services/apis/ExamTeacherCourseController';
import { CertificateType } from '@/services/enums';
import { FormInstance, ProFormDigit, 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 ExamTeacherCourseEditModal: React.FC<{
    examPlanId: number;
    data: Partial<API.ExamTeacherCourseOutput>;
    gradeBranch: {
        examGrades: API.ExamGradeOutput[];
        branches: API.SysOrgLiteOutput[];
    };
    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 { getDictOptions } = useModel('useDict');
    const { baseData } = useModel('useBaseData');

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

    return (
        <>
            <MovableModalForm<API.ExamTeacherCourseOutput>
                title={`${data.id === 0 ? '添加' : '修改'}监测教师任教科目`}
                width={800}
                open={open}
                formRef={formRef}
                initialValues={{
                    ...data,
                    sysOrgBranchId: data.sysOrgBranchId !== undefined ? data.sysOrgBranchId : undefined,
                    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 { certificateType, examGradeId, ...restValues } = values;
                    const g = gradeBranch.examGrades.find(t => t.id === examGradeId);

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

                    onFinish();
                    handleClose();
                }}
            >
                <Row gutter={[24, 0]}>
                    {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
                                disabled={data.id !== 0}
                                rules={[{ required: true }]}
                            />
                        </Col>
                    }
                    <Col span={12}>
                        <ProFormSelect
                            label="年级"
                            name="examGradeId"
                            options={gradeBranch.examGrades?.sort((a, b) => a.grade.gradeNumber - b.grade.gradeNumber)?.map(t => ({ label: `${t.grade.name}（${t.gradeBeginName}）`, value: t.id }))}
                            required
                            rules={[{ required: true }]}
                        // disabled={data.id !== 0}
                        />
                    </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 ?? [])}
                            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 ExamTeacherCourseEditModal;
