import { toValueEnum } from "@/common/converter";
import { CardStepTitle, SuperTable } from "@/components";
import ReportButton from "@/components/ReportButton";
import ExamGradeController from "@/services/apis/ExamGradeController";
import ExamOrgDataReportController from "@/services/apis/ExamOrgDataReportController";
import ExamTeacherCourseController from "@/services/apis/ExamTeacherCourseController";
import SysOrgController from "@/services/apis/SysOrgController";
import { DataReportStatus, DataReportType, ExamStatus } from "@/services/enums";
import { BulbOutlined, PlusOutlined, UploadOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProCard, ProColumns, ProDescriptions } from "@ant-design/pro-components";
import { history, useModel, useParams } from "@umijs/max";
import { useRequest } from "ahooks";
import { App, Badge, Button, Drawer, Space, Tag, Typography, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import ExamTeacherCourseEditModal from "./components/ExamTeacherCourseEditModal";

/** 监测教师任教科目上报 */
const OrgExamTeacherCourseReport: React.FC = () => {
    const reqParams = useParams() as unknown as { examPlanId: number };

    const { token } = theme.useToken();
    const { getDictValueEnum, getKeyDict } = useModel('useDict');
    const examStatusDict = getKeyDict('exam_status');
    const dataReportStatusDict = getKeyDict('data_report_status');
    const dataReportTypeDict = getKeyDict('data_report_type');

    const [remarkOpen, setRemarkOpen] = useState(false);
    const [editOpen, setEditOpen] = useState(false);
    const actionRef = useRef<ActionType>();
    const currentRef = useRef<Partial<API.ExamTeacherCourseOutput>>();

    const { initialState } = useModel('@@initialState');
    const { currentUser } = initialState ?? {};

    const { baseData } = useModel('useBaseData');

    const totalCountRef = useRef(0);

    const { message, modal } = App.useApp();

    // 加载上报数据
    const { data: reportData, run: loadReport } = useRequest(() => {
        return ExamOrgDataReportController.getByTypeExamPlanId({ type: DataReportType.TEACHER_COURSE, examplanid: reqParams.examPlanId });
    });

    const { data: gradeBranchData } = useRequest(async () => {
        const res1 = await ExamGradeController.getListByExamPlanId({ examplanid: reqParams.examPlanId });
        const res2 = await SysOrgController.getOrgBranchByOrgId({ orgid: currentUser?.sysOrgId ?? 0 });
        return {
            examGrades: res1 ?? [],
            branches: res2 ?? [],
            hasBranch: (res2?.length ?? 0) > 0,
        };
    });

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

    // 清空
    const handleClear = useCallback(() => {
        modal.confirm({
            title: '谨慎操作',
            content: '确定立即清空所有教师任教科目信息吗',
            okText: '确定',
            cancelText: '取消',
            centered: true,
            onOk: async () => {
                await ExamTeacherCourseController.clear({ examPlanId: reqParams.examPlanId });
                message.success('已清空');
                actionRef.current?.reload();
            },
        });
    }, []);

    // 上报
    const handleSubmit = useCallback(async () => {
        return new Promise<void>((resolve, reject) => {
            let content = `共 ${totalCountRef.current} 个任教科目信息，上报后不能再修改，确定立即上报吗？`;
            modal.confirm({
                title: '重要提醒',
                content,
                okText: '确定',
                cancelText: '取消',
                centered: true,
                onOk: async () => {
                    try {
                        await ExamOrgDataReportController.submit({ examPlanId: reqParams.examPlanId, type: DataReportType.TEACHER_COURSE })
                        message.success('已上报');
                        loadReport();
                        resolve();
                    }
                    catch {
                        reject();
                    }
                },
                onCancel: async () => {
                    resolve();
                },
            });
        });
    }, []);

    const reportable = (reportData?.examDataReport?.status === ExamStatus.ACTIVE && reportData?.isExpired === false &&
        (reportData?.examOrgDataReport?.status === DataReportStatus.UNREPORT ||
            reportData?.examOrgDataReport?.status === DataReportStatus.REJECTED));

    let detailActions = [];
    if (reportable) {
        detailActions.push(
            <Button
                key="import"
                type="primary"
                disabled={!reportable}
                icon={<UploadOutlined />}
                onClick={() => history.push(`/exam-s/t-course/import/${reqParams.examPlanId}`)}
            >批量导入</Button>
        );
        detailActions.push(
            <Button
                key="add"
                disabled={!reportable}
                icon={<PlusOutlined />}
                onClick={() => {
                    currentRef.current = { id: 0 };
                    setEditOpen(true);
                }}
            >添加教师任教科目</Button>
        );
        detailActions.push(
            <Button
                key="clear"
                disabled={!reportable}
                onClick={handleClear}
            >清空数据</Button>
        );
    }
    // detailActions.push(
    //     <Button
    //         key="download"
    //     >批量导出</Button>
    // );

    const columns: ProColumns<API.ExamTeacherCourseOutput>[] = [
        ...(gradeBranchData?.hasBranch ? [{
            title: '校区',
            dataIndex: 'sysOrgBranchId',
            width: 96,
            align: 'center',
            hideInSearch: !gradeBranchData?.hasBranch,
            valueEnum: toValueEnum(gradeBranchData?.branches ?? []),
        } as ProColumns] : []),
        {
            title: '年级',
            dataIndex: 'gradeId',
            width: 144,
            align: 'center',
            valueEnum: toValueEnum(gradeBranchData?.examGrades?.map(t => ({ id: t.gradeId, name: `${t.grade.name}（${t.gradeBeginName}）` })) ?? []),
        },
        {
            title: '班级号',
            dataIndex: 'classNumber',
            valueType: 'digit',
            width: 64,
            align: 'center',
            render: (_, r) => `${r.classNumber}班`,
        },
        {
            title: '科目',
            dataIndex: 'courseId',
            width: 120,
            align: 'center',
            valueEnum: toValueEnum(baseData?.courses ?? []),
        },
        {
            title: '教师姓名',
            dataIndex: 'name',
            width: 120,
            align: 'center',
        },
        {
            title: '证件类型',
            dataIndex: 'certificateType',
            valueEnum: getDictValueEnum('certificate_type'),
            width: 120,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '证件号码',
            dataIndex: 'idNumber',
            width: 180,
            align: 'center',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            hideInSearch: true,
            className: 'minw-64',
        },
        {
            title: '操作',
            valueType: 'option',
            width: 112,
            align: 'center',
            fixed: 'right',
            hideInTable: !reportable,
            render: (_, r) => {
                return (
                    <>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                currentRef.current = r;
                                setEditOpen(true);
                            }}
                        >修改</Button>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => handleDelete(r.id)}
                        >删除</Button>
                    </>
                );
            },
        }
    ];

    return (
        <PageContainer
            title={`${reportData?.examPlan?.fullName ?? ''} - 教师任教科目上报`}
            onBack={() => history.back()}
            extra={
                <Button
                    type="link"
                    icon={<BulbOutlined />}
                    onClick={() => {
                        window.scrollTo({ top: 0 });
                        // setTourOpen(true);
                    }}
                >查看操作指引</Button>
            }
        >
            <ProCard
                title={<CardStepTitle>基本情况</CardStepTitle>}
                extra={reportData?.examOrgDataReport?.status &&
                    <Space>
                        <Tag
                            style={{ marginRight: 0 }}
                            color={dataReportStatusDict[reportData.examOrgDataReport.status].antColor}
                        >
                            {dataReportStatusDict[reportData.examOrgDataReport.status].name}
                        </Tag>
                        {reportable &&
                            <>
                                <span>离上报结束还有</span>
                                <ReportButton
                                    showIcon
                                    expireTime={reportData?.examDataReport?.endTime}
                                    onSubmit={handleSubmit}
                                    onTimerFinish={() => loadReport()}
                                />
                            </>
                        }
                    </Space>
                }
            >
                <ProDescriptions>
                    <ProDescriptions.Item label="上报类型">
                        {reportData?.examDataReport?.type ? dataReportTypeDict[reportData?.examDataReport?.type].name : ''}
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="监测上报">
                        {reportData?.examDataReport?.status &&
                            <Badge
                                status={examStatusDict[reportData.examDataReport.status].antStatus as any}
                                text={examStatusDict[reportData.examDataReport.status].name}
                            />
                        }
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="截止时间">
                        <Typography.Text strong>
                            {reportData?.examDataReport?.endTime}
                            {reportData?.isExpired && reportData.examDataReport?.status === ExamStatus.ACTIVE &&
                                <Typography.Text type="danger">（已截止）</Typography.Text>
                            }
                        </Typography.Text>
                    </ProDescriptions.Item>
                    <ProDescriptions.Item label="上报人员">{reportData?.examOrgDataReport?.reportSysUser?.name}</ProDescriptions.Item>
                    <ProDescriptions.Item label="上报时间">{reportData?.examOrgDataReport?.reportTime}</ProDescriptions.Item>
                    <ProDescriptions.Item label="备注说明">{reportData?.examOrgDataReport?.remark}</ProDescriptions.Item>
                    <ProDescriptions.Item label="上报说明" span={3}>
                        <Typography.Text ellipsis>{reportData?.examDataReport?.remark || '无'}</Typography.Text>
                        {reportData?.examDataReport?.remark && <Button type="link" size="small" onClick={() => setRemarkOpen(true)}>详情</Button>}
                    </ProDescriptions.Item>
                </ProDescriptions>
                <Drawer open={remarkOpen} title="上报说明" width={720} maskClosable onClose={() => setRemarkOpen(false)}>
                    <pre>{reportData?.examDataReport?.remark || '无'}</pre>
                </Drawer>
            </ProCard>

            <SuperTable<API.ExamTeacherCourseOutput>
                headerTitle={<CardStepTitle>教师任教科目明细</CardStepTitle>}
                style={{ marginTop: token.margin }}
                actionRef={actionRef}
                scroll={{ x: 'max-content' }}
                rowKey="id"
                columns={columns}
                search={{ showHiddenNum: false }}
                options={{ setting: false, fullScreen: false }}
                toolbar={{
                    actions: detailActions,
                }}
                request={async (params, sort) => {
                    return SuperTable.requestPageAgent({ params, sort }, async (p) => {
                        const res = await ExamTeacherCourseController.queryPageList({ ...p, examPlanId: reqParams.examPlanId });
                        totalCountRef.current = res?.totalCount ?? 0;
                        return res;
                    });
                }}
            // rowSelection={reportable ? {} : false}
            />
            {editOpen && currentRef.current && gradeBranchData &&
                <ExamTeacherCourseEditModal
                    examPlanId={reqParams.examPlanId}
                    data={currentRef.current}
                    gradeBranch={gradeBranchData}
                    onFinish={() => actionRef.current?.reload()}
                    onClose={() => setEditOpen(false)}
                />
            }
        </PageContainer>
    );
}

export default OrgExamTeacherCourseReport;
