import { CardStepTitle, FileIcon } from "@/components";
import ExamScoreImportController from "@/services/apis/ExamScoreImportController";
import { SendOutlined, UploadOutlined } from "@ant-design/icons";
import { ProCard } from "@ant-design/pro-components";
import { App, Button, Card, Space, Typography, Upload, UploadFile, UploadProps, theme } from "antd";
import { RcFile } from "antd/es/upload";
import { useCallback, useState } from 'react';

/** 监测结果管理 */
const ExamResultList: React.FC<{ examPlanId: number, semesterId: number }> = ({ examPlanId, semesterId }) => {
    const { token } = theme.useToken();
    const { modal, message } = App.useApp();

    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const [uploadStatus, setUploadStatus] = useState<{ success: boolean; message: string }>();

    const uploadProps: UploadProps = {
        onRemove: () => {
            setFileList([]);
        },
        beforeUpload: (file) => {
            setFileList([file]);
            return false;
        },
        listType: 'picture',
        disabled: uploading,
        fileList,
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        iconRender: () => <FileIcon type=".xlsx" />
    };

    const handleUploadImportWithoutStudentTotalScore = useCallback(async () => {
        const onConfirm = () => new Promise((resolve) => {
            modal.confirm({
                title: '导入提示',
                content: '初始成绩导入会删除当前计划内所有已存在学生和成绩数据，删除后不能恢复，确定开始导入吗？',
                okText: '确定',
                cancelText: '取消',
                centered: true,
                onOk: () => resolve(true),
                onCancel: () => resolve(false),
            });
        });
        const confirm = await onConfirm();
        if (!confirm) { return; }
        try {
            setUploading(true);
            const formData = new FormData();
            formData.append('examPlanId', `${examPlanId}`);
            formData.append('file', fileList[0] as RcFile);
            await ExamScoreImportController.uploadImportWithoutStudentTotalScore(formData, { timeout: 600000 });
            message.success('已导入');
            setFileList([]);
            setUploadStatus({ success: true, message: '导入成功' });
        }
        catch (ex) {
            setUploadStatus({ success: false, message: `导入失败（${JSON.stringify(ex)}）` });
        }
        finally {
            setUploading(false);
        }
    }, [fileList]);

    if (semesterId < 20232) {
        return (
            <ProCard
                style={{ marginTop: token.margin }}
                title={<CardStepTitle>结果管理</CardStepTitle>}
            >
                <Typography.Paragraph>
                    <Typography.Title level={5}>初始成绩导入</Typography.Title>
                    <Typography.Text>适用于前未上报学生和抽样的批量学生成绩导入。</Typography.Text>
                </Typography.Paragraph>
                <Card>
                    <Space direction="vertical" size="large" style={{ width: '100%' }}>
                        <Upload {...uploadProps}>
                            <Button icon={<UploadOutlined />} disabled={uploading}>选择文件...</Button>
                        </Upload>
                        <Space>
                            <Button
                                type="primary"
                                disabled={fileList.length === 0}
                                loading={uploading}
                                icon={<SendOutlined />}
                                onClick={handleUploadImportWithoutStudentTotalScore}
                            >{uploading ? '正在导入，请稍候' : '开始导入'}</Button>
                            {uploadStatus && <Typography.Text type={uploadStatus.success ? 'success' : 'danger'}>{uploadStatus?.message}</Typography.Text>}
                        </Space>
                    </Space>
                </Card>
            </ProCard>
        );
    }
    return null;
    // return (
    //     <ProCard
    //         style={{ marginTop: token.margin }}
    //         title={<CardStepTitle>结果管理</CardStepTitle>}
    //     >
    //         <Typography.Paragraph>
    //             <Typography.Title level={5}>成绩导入</Typography.Title>
    //             <Typography.Text>适用于前未上报学生和抽样的批量学生成绩导入。</Typography.Text>
    //         </Typography.Paragraph>
    //         <Card>
    //             <Space direction="vertical" size="large" style={{ width: '100%' }}>
    //                 <Upload {...uploadProps}>
    //                     <Button icon={<UploadOutlined />} disabled={uploading}>选择文件...</Button>
    //                 </Upload>
    //                 <Space>
    //                     <Button
    //                         type="primary"
    //                         disabled={fileList.length === 0}
    //                         loading={uploading}
    //                         icon={<SendOutlined />}
    //                         onClick={handleUploadImportWithoutStudentTotalScore}
    //                     >{uploading ? '正在导入，请稍候' : '开始导入'}</Button>
    //                     {uploadStatus && <Typography.Text type={uploadStatus.success ? 'success' : 'danger'}>{uploadStatus?.message}</Typography.Text>}
    //                 </Space>
    //             </Space>
    //         </Card>
    //     </ProCard>
    // );
}

export default ExamResultList;
