import { CardStepTitle, FileLink } from "@/components";
import ReportButton from "@/components/ReportButton";
import ExamOrgDataReportController from "@/services/apis/ExamOrgDataReportController";
import ExamOrgScoreReportController from "@/services/apis/ExamOrgScoreReportController";
import { DataReportStatus, DataReportType, ExamStatus } from "@/services/enums";
import { BulbOutlined, ReloadOutlined } from "@ant-design/icons";
import { PageContainer, ProCard, ProDescriptions } from "@ant-design/pro-components";
import { history, useModel, useParams } from "@umijs/max";
import { useRequest } from "ahooks";
import { App, Badge, Button, Drawer, Space, Tag, Tour, Typography, theme } from "antd";
import { useCallback, useRef, useState } from "react";
import OrgSchoolExamScoreCourseReport from "./components/OrgSchoolExamScoreCourseReport";

const OrgSchoolExamScoreReport: React.FC = () => {
    const reqParams = useParams() as unknown as { examPlanId: number };

    const { token } = theme.useToken();
    const { 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 [tourOpen, setTourOpen] = useState(false);
    const tourAddRef = useRef(null);
    const tourDownloadRef = useRef(null);
    const tourUploadRef = useRef(null);
    const tourReportRef = useRef(null);

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

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

    const { data: list, run: loadList } = useRequest(() => {
        return ExamOrgScoreReportController.getListByExamPlanId({ examplanid: reqParams.examPlanId });
    });
    const totalCount = list?.length ?? 0;
    const uploadedCount = list?.filter(t => t.fileSize !== '0')?.length ?? 0;

    // 上报
    const handleSubmit = useCallback(() => {
        return new Promise<void>((resolve, reject) => {
            let content = `共需上传【${totalCount}】个小题成绩，已上传【${uploadedCount}】个，【${totalCount - uploadedCount}】个未上传，上报后不能再修改，确定立即上报吗？`;
            modal.confirm({
                title: '上报确认',
                content,
                okText: '确定',
                cancelText: '取消',
                centered: true,
                onOk: async () => {
                    try {
                        await ExamOrgDataReportController.submit({ examPlanId: reqParams.examPlanId, type: DataReportType.SCHOOL_EXAM_SCORE })
                        message.success('已上报');
                        loadReport();
                        resolve();
                    }
                    catch (ex) {
                        const exm = ex as any;
                        notification.error({
                            message: '上报失败',
                            description: exm?.info?.errorMessage ? `${exm?.info?.errorMessage}！请仔细检查缺测替补学生明细信息和佐证材料` : JSON.stringify(ex),
                        })
                        reject();
                    }
                },
                onCancel: () => reject(),
            });
        });
    }, [reportData, totalCount, uploadedCount]);

    // 是否可操作和上报
    const reportable = (reportData?.examDataReport?.status === ExamStatus.ACTIVE && reportData?.isExpired === false &&
        (reportData?.examOrgDataReport?.status === DataReportStatus.UNREPORT ||
            reportData?.examOrgDataReport?.status === DataReportStatus.REJECTED));


    return (
        <PageContainer
            title={`${reportData?.examPlan?.fullName ?? ''} - 校考成绩上报`}
            onBack={() => history.back()}
            extra={reportable &&
                <Button
                    type="link"
                    icon={<BulbOutlined />}
                    onClick={() => {
                        window.scrollTo({ top: 0 });
                        setTourOpen(true);
                    }}
                >查看操作指引</Button>
            }
        >
            <ProCard
                title={<CardStepTitle>基本情况</CardStepTitle>}
                direction="column"
                extra={reportData?.examOrgDataReport?.status &&
                    <Tag
                        style={{ marginRight: 0 }}
                        color={dataReportStatusDict[reportData.examOrgDataReport.status].antColor}
                    >
                        {dataReportStatusDict[reportData.examOrgDataReport.status].name}
                    </Tag>
                }
            >
                <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>
                <Typography.Title level={5}>小题成绩模板下载</Typography.Title>
                <Space direction="vertical" style={{ width: '100%' }}>
                    {reportData?.examDataReport?.attachmentList?.map((t, i) => (
                        <FileLink key={i} {...t} card />
                    ))}
                </Space>
                <Drawer open={remarkOpen} title="上报说明" width={720} maskClosable onClose={() => setRemarkOpen(false)}>
                    <pre>{reportData?.examDataReport?.remark || '无'}</pre>
                </Drawer>
            </ProCard>


            <ProCard
                title={<CardStepTitle>成绩上报</CardStepTitle>}
                style={{ marginTop: token.margin }}
                extra={reportable &&
                    <Space>
                        <span key="tooltip">离上报结束还有</span>
                        <ReportButton
                            key="time"
                            buttonRef={tourReportRef}
                            expireTime={reportData?.examDataReport?.endTime}
                            showIcon
                            onSubmit={handleSubmit}
                            onTimerFinish={() => loadReport()}
                        />
                    </Space>
                }
            >
                <Typography.Paragraph>
                    共需上传【{totalCount}】个小题成绩文件，已上传<Tag color="success" style={{ marginLeft: token.marginXS, fontWeight: 'bold', fontSize: token.fontSizeHeading5 }}>{uploadedCount}</Tag>个，
                    还有<Tag color="error" style={{ marginLeft: token.marginXS, fontWeight: 'bold', fontSize: token.fontSizeHeading5 }}>{totalCount - uploadedCount}</Tag>个未上传。
                </Typography.Paragraph>
            </ProCard>


            <ProCard
                title={<CardStepTitle>各年级各科目小题成绩上传</CardStepTitle>}
                direction="column"
                style={{ marginTop: token.margin }}
                bodyStyle={{ paddingTop: token.paddingLG }}
                extra={
                    <Space>
                        {/* <Button icon={<DownloadOutlined />}>下载小题成绩模板</Button> */}
                        <Button icon={<ReloadOutlined />} type="text" onClick={loadList} />
                    </Space>
                }
            >
                {list?.map((t, i) => (
                    <OrgSchoolExamScoreCourseReport
                        key={i}
                        sequence={i + 1}
                        data={t}
                        onUploaded={loadList}
                        reportable={reportable}
                    />
                ))}
            </ProCard>

            <Tour
                steps={[
                    {
                        title: '添加缺测替补学生信息',
                        description: '添加完缺测替补学生信息后，在列表中上传相应的佐证材料（一个学生最多3个图片或PDF）',
                        target: () => tourAddRef.current,
                    },
                    {
                        title: '下载打印表格文件',
                        description: '打印表格按年级分页，按文件要求签字和盖章',
                        target: () => tourDownloadRef.current,
                    },
                    {
                        title: '上传签字盖章文件',
                        description: '打印文件签字盖章后，扫描成电子文件（PDF或图片）上传，推荐PDF文件，最多上传6个文件',
                        target: () => tourUploadRef.current,
                    },
                    {
                        title: '上报缺测替补学生信息',
                        description: '确认无误后立即上报',
                        target: () => tourReportRef.current,
                    },
                ]}
                open={tourOpen}
                onClose={() => setTourOpen(false)}
            />
        </PageContainer >
    );
}

export default OrgSchoolExamScoreReport;
