import { toExcelColumnName, toValueEnum } from '@/common/converter';
import { SuperTable } from '@/components';
import ExamCourseController from '@/services/apis/ExamCourseController';
import ExamGradeController from '@/services/apis/ExamGradeController';
import ExamPaperController from '@/services/apis/ExamPaperController';
import ExamPlanController from '@/services/apis/ExamPlanController';
import { ActionType, PageContainer, ProColumns } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { useRequest } from 'ahooks';
import { App, Button, Space, Typography, theme } from 'antd';
import { useCallback, useRef, useState } from 'react';
import ExamCourseEditModal from './components/ExamCourseEditModal';

/** 监测科目列表 */
const ExamCourseList: React.FC = () => {
    const reqParams = useParams() as unknown as { examPlanId: number; };

    const { token } = theme.useToken();
    const actionRef = useRef<ActionType>();
    const currentRef = useRef<Partial<API.ExamCourseOutput>>();

    const [editShow, setEditShow] = useState(false);
    const [examCourses, setExamCourses] = useState<API.ExamCourseOutput[]>([]);
    const { message, modal } = App.useApp();

    const { data: examGrades } = useRequest(async () => {
        const res = await ExamGradeController.getListByExamPlanId({ examplanid: reqParams.examPlanId });
        return res ?? [];
    });

    // 删除
    const handleDelete = useCallback((id: number) => {
        modal.confirm({
            title: '警告',
            content: '确定立即删除吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamPlanController.del({ id });
                message.success('已删除');
                actionRef.current?.reload();
            },
        });
    }, []);

    // 初始化双向细目表
    const handleInitPaper = useCallback(() => {
        modal.confirm({
            content: '确定立即初始化双向细目表吗？',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamPaperController.batchInit({ examPlanId: reqParams.examPlanId });
                message.success('初始完成');
            },
        });
    }, []);

    const columns: ProColumns<API.ExamCourseOutput>[] = [
        {
            title: '监测年级',
            dataIndex: ['examGrade', 'grade', 'name'],
            valueEnum: toValueEnum(examGrades?.map(t => t.grade) ?? []),
            width: 88,
            align: 'center',
            search: {
                transform: v => ({ gradeId: v }),
            },
        },
        {
            title: '科目',
            dataIndex: ['course', 'name'],
            width: 64,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '总分',
            dataIndex: 'totalScore',
            width: 64,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '分段类型',
            dataIndex: 'examScoreRangeType',
            // valueEnum: getDictValueEnum('exam_score_range_type'),
            width: 80,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '成绩模板',
            hideInSearch: true,
            children: [
                {
                    title: '标题行',
                    dataIndex: ['scoreReportConfig', 'headerRowIndex'],
                    width: 64,
                    align: 'center',
                },
                {
                    title: '小分列',
                    dataIndex: ['scoreReportConfig', 'minorQuestionColumnIndex'],
                    width: 64,
                    align: 'center',
                },
                {
                    title: '标题列名',
                    dataIndex: ['scoreReportConfig', 'headerColumnNames'],
                    render: (_, r) => {
                        return r.scoreReportConfig?.headerColumnNames?.map((t, i) => (
                            <Typography.Text key={i} style={{ marginRight: token.margin }}>
                                <Typography.Text type="secondary">[</Typography.Text>
                                <Typography.Text type="danger">{toExcelColumnName(i)}</Typography.Text>
                                <Typography.Text type="secondary">]</Typography.Text>
                                {t}
                            </Typography.Text>
                        ));
                    },
                },
                {
                    title: '备注',
                    dataIndex: ['scoreReportConfig', 'remark'],
                    width: 64,
                },
            ]
        },
        {
            title: '操作',
            valueType: 'option',
            width: 88,
            align: 'center',
            fixed: 'right',
            render: (_, r) => {
                return (
                    <Space>
                        <a onClick={() => { currentRef.current = r; setEditShow(true); }}>修改</a>
                        <a onClick={() => handleDelete(r.id)}>删除</a>
                    </Space>
                );
            },
        },
    ];

    return (
        <PageContainer
            title="监测科目管理"
            onBack={() => history.back()}
        >
            <SuperTable<API.ExamCourseOutput>
                actionRef={actionRef}
                columns={columns}
                pagination={false}
                toolbar={{
                    title: '监测科目列表',
                    actions: [
                        <Button
                            key="init"
                            onClick={handleInitPaper}
                        >初始化双向细目表</Button>,
                        <Button
                            key="add"
                            type="primary"
                            onClick={() => {
                                currentRef.current = {
                                    id: 0,
                                    examPlanId: reqParams.examPlanId,
                                };
                                setEditShow(true);
                            }}
                        >添加科目</Button>,
                    ],
                }}
                request={async (params) => {
                    try {
                        const res = await ExamCourseController.queryList({
                            examPlanId: reqParams.examPlanId,
                            ...params,
                        });
                        setExamCourses(res ?? []);
                        return {
                            data: res,
                            success: true,
                        };
                    }
                    catch (ex) { return {}; }
                }}

            />
            {editShow && currentRef.current &&
                <ExamCourseEditModal
                    examCourses={examCourses}
                    examGrades={examGrades ?? []}
                    data={currentRef.current}
                    onOk={() => actionRef.current?.reload()}
                    onClose={() => setEditShow(false)}
                />
            }
        </PageContainer>
    );
};

export default ExamCourseList;
