import { toSelectOptions } from "@/common/converter";
import { MovableModalForm } from "@/components";
import ExamCourseController from "@/services/apis/ExamCourseController";
import { ExamScoreRangeType } from "@/services/enums";
import { ProFormDependency, ProFormDigit, ProFormSelect, ProFormTextArea } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { App, Col, FormInstance, Row, theme } from "antd";
import { useRef, useState } from "react";

/** 监测科目编辑对话框 */
const ExamCourseEditModal: React.FC<{
    /** 监测年级信息 */
    data: Partial<API.ExamCourseOutput>;
    /** 监测年级 */
    examGrades: API.ExamGradeOutput[];
    /** 监测科目列表 */
    examCourses: API.ExamCourseOutput[];
    /** 保存成功回调 */
    onOk: () => void;
    /** 关闭回调 */
    onClose: () => void;
}> = ({ examCourses, examGrades, data, onOk, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(onClose, 300); };

    const formRef = useRef<FormInstance>();
    const { message } = App.useApp();
    const { baseData } = useModel('useBaseData');
    const { getDictValueEnum } = useModel('useDict');

    const { token } = theme.useToken();

    return (
        <MovableModalForm<{
            examGradeId: number;
            courseId: number;
            totalScore: number;
            examScoreRangeType: ExamScoreRangeType;
            scoreReportConfig: API.ExamCourseScoreReportConfig;
        }>
            title="监测年级科目设置"
            width={880}
            open={open}
            modalProps={{
                // centered: true,
                maskClosable: false,
                onCancel: handleClose,
            }}
            initialValues={{
                examGradeId: data.examGradeId,
                courseId: data.courseId,
                totalScore: data.totalScore,
                examScoreRangeType: data.examScoreRangeType !== undefined ? `${data.examScoreRangeType}` : undefined,
                scoreReportConfig: {
                    headerRowIndex: 0,
                    minorQuestionColumnIndex: 7,
                    ...(data.scoreReportConfig || {})
                },
            }}
            formRef={formRef}
            onFinish={async (values) => {
                const { examGradeId, examScoreRangeType, ...restValues } = values;
                const grade = examGrades.find(t => t.id === examGradeId);
                if (!grade) {
                    return;
                }

                try {
                    const p: API.AddExamCourseInput = {
                        examPlanId: data.examPlanId ?? 0,
                        examGradeId,
                        gradeId: grade.gradeId,
                        examScoreRangeType: JSON.parse(`${examScoreRangeType}`),
                        ...restValues,
                    };
                    if (data.id === 0) {
                        await ExamCourseController.add(p);
                    } else {
                        let updateParams = {
                            ...p,
                            id: data.id
                        } as API.UpdateExamCourseInput;
                        await ExamCourseController.update(updateParams);
                    }
                    message.success('操作成功！');
                    onOk();
                    handleClose();
                }
                catch { }
            }}
        >
            <Row gutter={[token.paddingLG, 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 }]}
                        disabled={data.id !== 0}
                        fieldProps={{
                            onChange: () => {
                                formRef.current?.setFieldsValue({ courseId: undefined });
                            },
                        }}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDependency name={['examGradeId']}>
                        {({ examGradeId }) => {
                            const egcs = examCourses?.filter(t => t.examGradeId === examGradeId && t.courseId !== data?.courseId)?.map(t => t.courseId) ?? [];
                            const bcs = baseData?.courses?.filter(t => !egcs.includes(t.id)) ?? [];
                            return (
                                <ProFormSelect
                                    label="监测科目"
                                    name="courseId"
                                    options={toSelectOptions(bcs)}
                                    disabled={data.id !== 0}
                                    required
                                    rules={[{ required: true }]}
                                />
                            );
                        }}
                    </ProFormDependency>
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="模板标题行号（0表示第1行）"
                        name={['scoreReportConfig', 'headerRowIndex']}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="小题分开始列（0表示第1列）"
                        name={['scoreReportConfig', 'minorQuestionColumnIndex']}
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormDigit
                        label="总分"
                        name="totalScore"
                        required
                        rules={[{ required: true }]}
                    />
                </Col>
                <Col span={12}>
                    <ProFormSelect
                        label="分数段类型"
                        name="examScoreRangeType"
                        required
                        rules={[{ required: true }]}
                        valueEnum={getDictValueEnum('exam_score_range_type')}
                    />
                </Col>
            </Row>
            <ProFormSelect
                label="模板标题列名（从A列开始，以逗号分隔，显示的顺序即为表格中的顺序，可从EXCEL直接复制粘贴到此，可用逗号连续输入）"
                name={['scoreReportConfig', 'headerColumnNames']}
                mode="tags"
                fieldProps={{
                    tokenSeparators: [',', '，', '\t'],
                }}
                allowClear
            />
            <ProFormTextArea
                label="模板说明"
                name={['scoreReportConfig', 'remark']}
            />
        </MovableModalForm>
    );
}

export default ExamCourseEditModal;
