import { SuperTable, TagStatus } from '@/components';
import ExamPaperController from '@/services/apis/ExamPaperController';
import ExamPlanController from '@/services/apis/ExamPlanController';
import { AuditStatus, ExamPaperWriterType } from '@/services/enums';
import { ActionType, PageContainer, ProColumns } from '@ant-design/pro-components';
import { history, useParams } from '@umijs/max';
import { useRequest } from 'ahooks';
import { App, Button, Typography } from 'antd';
import { useCallback, useRef, useState } from 'react';
import { ExamPaperLiteItem } from '../../typing';
import SuggestionEditDrawer from './components/SuggestionEditDrawer';

/** 问题建议试卷列表 */
const SuggestionCourseList: React.FC = () => {
    const reqParams = useParams() as unknown as { examPlanId: number };

    const { message, modal } = App.useApp();
    const currentRef = useRef<ExamPaperLiteItem>();
    const actionRef = useRef<ActionType>();
    const [editOpen, setEditOpen] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    const { data, loading } = useRequest(() => {
        return ExamPlanController.getById({ id: reqParams.examPlanId });
    });

    // 提交
    const handleSubmit = useCallback(async (examPaperId: number) => {
        modal.confirm({
            content: '提交后不能再修改，确定立即提交吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                try {
                    setSubmitting(true);
                    await ExamPaperController.submitSuggestion({ id: examPaperId });
                    message.success('已提交');
                    actionRef.current?.reload();
                }
                catch { }
                finally {
                    setSubmitting(false);
                }
            },
        });
    }, []);

    const columns: ProColumns<ExamPaperLiteItem>[] = [
        {
            title: '年级',
            dataIndex: ['grade', 'fullName'],
            width: 96,
            align: 'center',
        },
        {
            title: '科目',
            dataIndex: ['course', 'name'],
            width: 72,
            align: 'center',
        },
        {
            title: '总分',
            dataIndex: 'score',
            width: 72,
            align: 'center',
        },
        {
            title: '问题',
            dataIndex: 'questions',
            ellipsis: true,
            render: (v, r) => {
                if ((r.questions?.length ?? 0) < 200) {
                    return v;
                }
                return `${r.questions?.substring(0, 200)}...`;
            },
        },
        {
            title: '建议',
            dataIndex: 'suggestions',
            ellipsis: true,
            render: (v, r) => {
                if ((r.suggestions?.length ?? 0) < 200) {
                    return v;
                }
                return `${r.suggestions?.substring(0, 200)}...`;
            },
        },
        {
            title: '状态',
            dataIndex: 'submitted',
            width: 80,
            align: 'center',
            render: (_, r) => {
                if (r.submitted) {
                    return <TagStatus status="success">已提交</TagStatus>;
                }
                return <TagStatus status="error">未提交</TagStatus>;
            },
        },
        {
            title: '操作',
            valueType: 'option',
            width: 112,
            // align: 'center',
            fixed: 'right',
            render: (_, r) => {
                return (
                    <>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                currentRef.current = r; setEditOpen(true);
                            }}
                        >{r.submitted ? '查看' : '撰写'}</Button>
                        {!r.submitted &&
                            <Button
                                type="link"
                                size="small"
                                loading={submitting}
                                onClick={() => handleSubmit(r.id)}
                            >提交</Button>
                        }
                    </>
                );
            },
        },
    ];

    return (
        <PageContainer
            title={`${data?.fullName ?? ''} - 学科问题建议撰写`}
            onBack={() => history.back()}
            loading={loading}
        >
            <SuperTable<ExamPaperLiteItem>
                headerTitle="科目列表"
                actionRef={actionRef}
                columns={columns}
                search={false}
                columnEmptyText=""
                toolbar={{
                    actions: [
                        <Typography.Text key="tip" type="warning">撰写完成后，点击“提交”完成撰写。</Typography.Text>,
                    ],
                }}
                request={async () => {
                    const res = await ExamPaperController.getWriterListByExamPlanId({
                        examplanid: reqParams.examPlanId,
                        writertype: ExamPaperWriterType.SUGGESTION,
                    });
                    const data = res?.map(t => {
                        return {
                            ...t,
                            submitted: ![AuditStatus.UNSUBMIT, AuditStatus.REJECTED].includes(t.suggestionStatus),
                        } as ExamPaperLiteItem;
                    });
                    return {
                        data,
                        success: true,
                    };
                }}
            />
            {editOpen && currentRef.current &&
                <SuggestionEditDrawer
                    data={currentRef.current}
                    onClose={() => setEditOpen(false)}
                    onFinish={() => actionRef.current?.reload()}
                />
            }
        </PageContainer>
    );
};

export default SuggestionCourseList;
