import { MovableModalForm } from '@/components';
import ExamPlanController from '@/services/apis/ExamPlanController';
import { EducationStage } from '@/services/enums';
import { FormInstance, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { App, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';

/** 创建/修改监测计划 */
const ExamPlanEditModal: React.FC<{
    data: Partial<API.ExamPlanOutput>;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ data, onFinish, onClose }) => {
    const formRef = useRef<FormInstance>();
    const { message } = App.useApp();

    const [open, setOpen] = useState(true);

    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };
    const isEdit = (data.id ?? 0) > 0;

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

    const { baseData, fetchBaseData } = useModel('useBaseData');
    useEffect(() => {
        (async () => {
            if (!baseData) {
                await fetchBaseData();
            }
            formRef.current?.setFieldsValue({
                semesterId: data.semesterId ? data.semesterId : undefined,
            });
        })();
    }, [baseData, formRef.current]);

    return (
        <MovableModalForm
            title={`${isEdit ? '修改' : '创建'}监测计划`}
            width={800}
            open={open}
            formRef={formRef}
            initialValues={{
                ...data,
                educationStage: data.educationStage !== undefined ? `${data.educationStage}` : undefined,
            }}
            modalProps={{
                centered: true,
                maskClosable: false,
                onCancel: () => {
                    formRef?.current?.resetFields();
                    handleClose();
                },
            }}
            onFinish={async (values: any) => {
                try {
                    const { educationStage, ...restValues } = values;
                    let p: API.AddExamPlanInput = {
                        educationStage: JSON.parse(educationStage),
                        ...restValues
                    };
                    if ((data.id ?? 0) > 0) {
                        const up = { id: data.id ?? 0, ...p } as API.UpdateExamPlanInput;
                        await ExamPlanController.update(up);
                    }
                    else {
                        await ExamPlanController.add(p);
                    }
                    message.success('操作成功！');
                    formRef?.current?.resetFields();
                    onFinish();
                    handleClose();
                    return true;
                } catch {
                    message.error('操作失败！');
                    return false;
                }
            }}
            onFieldsChange={(changedFields) => {
                if (!['semesterId', 'educationStage', 'examName'].includes(changedFields[0]?.name[0])) {
                    return;
                }

                let fsn = '';
                let sn = '';
                let short_sn = '';
                const sn_e = baseData?.semesters?.find(t => t.id === formRef.current?.getFieldValue('semesterId'));
                if (sn_e) {
                    fsn = `${sn_e.name}（${sn_e.nickShortName}）`;
                    sn = `${sn_e.shortName}（${sn_e.nickShortName}）`;
                    short_sn = `${sn_e.nickShortName}`;
                }

                let es = '';
                const es_e = getKeyDict('education_stage')?.[formRef.current?.getFieldValue('educationStage')]
                if (es_e && es_e.value !== EducationStage.NONE) {
                    es = es_e.name;
                }

                const examName = formRef.current?.getFieldValue('examName') ?? '';
                formRef.current?.setFieldsValue({
                    fullName: `${fsn}${es}${examName}`,
                    name: `${sn}${es}${examName}`,
                    shortName: `${short_sn}${es}${examName}`,
                });
            }}
        >
            <ProFormSelect
                label="监测学期"
                name="semesterId"
                options={(baseData?.semesters ?? []).map(t => ({
                    value: t.id,
                    label: (
                        <span>
                            {t.name}（{t.nickShortName}）
                            {t.isCurrent && <Tag color="success">当前学期</Tag>}
                        </span>
                    ),
                }))}
                required
                rules={[{ required: true }]}
            />
            <ProFormSelect
                label="监测学段"
                name="educationStage"
                valueEnum={getDictValueEnum('education_stage')}
                required
                rules={[{ required: true }]}
            />
            <ProFormText
                label="监测名称"
                name="examName"
                required
                rules={[{ required: true }]}
                fieldProps={{
                    maxLength: 50,
                    showCount: true,
                }}
            />
            <ProFormText label="全称" name="fullName" readonly />
            <ProFormText label="名称" name="name" readonly />
            <ProFormText label="简称" name="shortName" readonly />
            <ProFormTextArea
                label="备注"
                name="remark"
                fieldProps={{
                    maxLength: 200,
                    showCount: true,
                }}
            />
        </MovableModalForm >
    );
};

export default ExamPlanEditModal;
