import { CardStepTitle } from '@/components';
import ExamPaperController from '@/services/apis/ExamPaperController';
import { AuditStatus } from '@/services/enums';
import { DrawerForm, ProFormTextArea } from '@ant-design/pro-components';
import { App } from 'antd';
import { useState } from 'react';

/** 问题建议撰写 */
const SuggestionEditDrawer: React.FC<{
    data: API.ExamPaperOutput;
    onFinish: () => void;
    onClose?: () => void;
}> = ({ data, onFinish, onClose }) => {
    const [open, setOpen] = useState<boolean>(true);
    const handleClose = () => { setOpen(false); setTimeout(() => onClose?.(), 300); };

    const { message } = App.useApp();
    // 未提交状态
    const unsubmit = [AuditStatus.UNSUBMIT, AuditStatus.REJECTED].includes(data?.suggestionStatus ?? AuditStatus.UNSUBMIT);

    return (
        <DrawerForm<{
            questions: string;
            suggestions: string;
        }>
            title={`撰写【${data.grade?.fullName}${data.course?.name}】问题建议`}
            width={1080}
            open={open}
            drawerProps={{
                onClose: handleClose,
                maskClosable: false,
            }}
            readonly={!unsubmit}
            requiredMark={unsubmit}
            {...(unsubmit ? {} : { submitter: false })}
            initialValues={{
                questions: data.questions,
                suggestions: data.suggestions,
            }}
            onFinish={async (values: any) => {
                try {
                    const p: API.SaveExamPaperSuggestion = {
                        ...values,
                        id: data.id,
                    };
                    await ExamPaperController.saveSuggestion(p);
                    message.success('保存成功！');
                    onFinish();
                    handleClose();
                    return true;
                } catch {
                    message.error('保存失败！');
                    return false;
                }
            }}
        >
            <ProFormTextArea
                label={<CardStepTitle>主要问题</CardStepTitle>}
                name="questions"
                fieldProps={{
                    showCount: true,
                    maxLength: 4000,
                    rows: 12,
                }}
                rules={[
                    { required: true, message: '请输入主要问题' },
                ]}
            />
            <ProFormTextArea
                label={<CardStepTitle>改进建议</CardStepTitle>}
                name="suggestions"
                fieldProps={{
                    showCount: true,
                    maxLength: 4000,
                    rows: 12,
                }}
                rules={[
                    { required: true, message: '请输入改进建议' },
                ]}
            />
        </DrawerForm>
    );
};

export default SuggestionEditDrawer;
