import { MovableModalForm } from '@/components';
import ExamPaperQuestionMajorController from '@/services/apis/ExamPaperQuestionMajorController';
import { FormInstance, ProFormDigit, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { App, Col, Row, theme } from 'antd';
import { useRef, useState } from 'react';

/** 添加或修改大题 */
const ExamPaperQuestionMajorEditModal: React.FC<{
    data: Partial<API.ExamPaperQuestionMajorOutput>;
    totalScore: number;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ data, totalScore, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const { token } = theme.useToken();

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

    return (
        <>
            <MovableModalForm<{
                sequence: number;
                number: string;
                title: string;
                hint: string;
                score: number;
                remark: string;
            }>
                title={`${data.id !== 0 ? '修改' : '添加'}大题`}
                width={720}
                open={open}
                formRef={formRef}
                initialValues={{ ...data }}
                modalProps={{
                    centered: true,
                    maskClosable: false,
                    onCancel: handleClose,
                }}
                onFinish={async (values: any) => {
                    try {
                        const p: API.AddExamPaperQuestionMajorInput = {
                            ...values,
                            examPaperId: data.examPaperId,
                        };
                        if (data.id === 0) {
                            await ExamPaperQuestionMajorController.add(p);
                        } else {
                            let updateParams = { ...p, id: data.id } as API.UpdateExamPaperQuestionMajorInput;
                            await ExamPaperQuestionMajorController.update(updateParams);
                        }
                        message.success('操作成功！');
                        formRef?.current?.resetFields();
                        onFinish();
                        handleClose();
                        return true;
                    } catch {
                        message.error('操作失败！');
                        return false;
                    }
                }}
            >
                <Row gutter={[token.marginLG, 0]}>
                    <Col span={8}>
                        <ProFormDigit
                            label="显示顺序号"
                            name="sequence"
                            rules={[{ required: true }]}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormDigit
                            label="分值"
                            name="score"
                            fieldProps={{
                                min: 0,
                                max: totalScore,
                                precision: 2,
                                step: 1,
                            }}
                            rules={[
                                { required: true },
                                () => ({
                                    validator: (_, value) => {
                                        if (value === undefined || value === null || value === '' || (value > 0 && value <= totalScore)) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(`分值取值范围为：大于0，且小于等于${totalScore}`);
                                    },
                                }),
                            ]}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormText
                            label="题号"
                            tooltip="一般为中文数字"
                            name="number"
                            fieldProps={{
                                maxLength: 20,
                                showCount: true,
                            }}
                            rules={[{ required: true }]}
                        />
                    </Col>
                </Row>
                <ProFormText
                    label="标题"
                    name="title"
                    fieldProps={{
                        maxLength: 100,
                        showCount: true,
                    }}
                />
                <ProFormTextArea
                    label="提示语"
                    name="hint"
                    fieldProps={{
                        maxLength: 200,
                        showCount: true,
                    }}
                />

                <ProFormTextArea
                    label="备注说明"
                    name="remark"
                    fieldProps={{
                        maxLength: 200,
                        showCount: true,
                    }}
                />
            </MovableModalForm >
        </>
    );
};

export default ExamPaperQuestionMajorEditModal;
