import { SuperTable } from '@/components';
import ExamPaperController from '@/services/apis/ExamPaperController';
import ExamPlanController from '@/services/apis/ExamPlanController';
import { ExamPaperWriterType } from '@/services/enums';
import { RightOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns } from '@ant-design/pro-components';
import { history, useModel, useParams } from '@umijs/max';
import { useRequest } from 'ahooks';
import { App, Space, theme } from 'antd';
import { useRef, useState } from 'react';
import AssignWriterModal from './components/AssignWriterModal';

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

    const typeRef = useRef<ExamPaperWriterType>();
    const actionRef = useRef<ActionType>();
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

    const [assignWriterOpen, setAssignWriterOpen] = useState(false);

    const { getDictValueEnum } = useModel('useDict');
    const { token } = theme.useToken();
    const { message } = App.useApp();

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

    const columns: ProColumns<API.ExamPaperLiteOutput>[] = [
        {
            title: '年级',
            dataIndex: ['grade', 'name'],
            width: 120,
            align: 'center',
        },
        {
            title: '科目',
            dataIndex: ['course', 'name'],
            width: 96,
            align: 'center',
        },
        {
            title: '总分',
            dataIndex: 'score',
            width: 96,
            align: 'center',
        },
        {
            title: '双向细目表编制人',
            dataIndex: ['twclSysUser', 'name'],
            width: 144,
            align: 'center',
        },
        {
            title: '双向细目表编制状态',
            dataIndex: 'twclStatus',
            valueEnum: getDictValueEnum('audit_status', true),
            width: 160,
            align: 'center',
        },
        {
            title: '问题建议撰写人',
            dataIndex: ['suggestionSysUser', 'name'],
            width: 144,
            align: 'center',
        },
        {
            title: '问题建议撰写状态',
            dataIndex: 'suggestionStatus',
            valueEnum: getDictValueEnum('audit_status', true),
            width: 160,
            align: 'center',
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            valueType: 'option',
            width: 80,
            align: 'center',
            fixed: 'right',
            render: (_, r) => {
                return (
                    <a onClick={() => history.push(`/exam-c/ep/course/detail/${r.id}`)}>
                        去管理
                        <RightOutlined style={{ marginLeft: token.marginXXS }} />
                    </a>
                );
            },
        },
    ];

    const handleAssignWriter = (type: ExamPaperWriterType) => {
        if (!selectedRowKeys || selectedRowKeys.length === 0) {
            message.error('至少选择一个科目');
            return;
        }
        typeRef.current = type;
        setAssignWriterOpen(true);
    }

    return (
        <PageContainer
            title={`${data?.fullName ?? ''} - 双向细目表管理`}
            onBack={() => history.back()}
            loading={loading}
        >
            <SuperTable<API.ExamPaperLiteOutput>
                toolbar={{
                    title: '科目列表',
                }}
                actionRef={actionRef}
                columns={columns}
                search={false}
                columnEmptyText=""
                request={async () => {
                    const res = await ExamPaperController.getListByExamPlanId({ examplanid: reqParams.examPlanId });
                    return {
                        data: res,
                        success: true,
                    };
                }}
                rowSelection={{
                    alwaysShowAlert: true,
                    selectedRowKeys,
                    onSelect: (record, selected, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                    onSelectAll: (_, selectedRows) => {
                        setSelectedRowKeys(selectedRows.map((t) => t.id) || []);
                    },
                }}
                tableAlertRender={({ selectedRowKeys, onCleanSelected }) => {
                    return (
                        <Space size="large">
                            <span>已选 {selectedRowKeys.length} 项</span>
                            <a onClick={() => {
                                setSelectedRowKeys([]);
                                onCleanSelected();
                            }}>取消选择</a>
                        </Space>
                    );
                }}
                tableAlertOptionRender={() => {
                    return (
                        <Space size="large">
                            <a onClick={() => handleAssignWriter(ExamPaperWriterType.TWCL)}>分配双向细目表编制人</a>
                            <a onClick={() => handleAssignWriter(ExamPaperWriterType.SUGGESTION)}>分配问题建议撰写人</a>
                        </Space>
                    );
                }}
            />

            {assignWriterOpen && selectedRowKeys && selectedRowKeys.length > 0 && typeRef.current &&
                <AssignWriterModal
                    ids={selectedRowKeys}
                    type={typeRef.current}
                    onFinish={() => {
                        setSelectedRowKeys([]);
                        actionRef.current?.reload();
                        typeRef.current = undefined;
                    }}
                    onClose={() => setAssignWriterOpen(false)}
                />
            }
        </PageContainer>
    );
};

export default ExamPaperCourseList;
