import { useState,useEffect } from 'react';
import { Button, message, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { getExamFileName,uploadFile } from '@/apis/data';
import { logger} from '@/apis/auth';
import styles from './index.less';


const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel', // .xls
    'application/zip', // .zip
    'application/x-zip-compressed' // .zip
];
const allowedExtensions = ['.xlsx', '.xls', '.zip'];


const UploadScore = (props) => {


    const {examId='',onChange=()=>{}} = props;


    const [fileList,setFileList] = useState([]);



    useEffect(() => {
        getExamFileNameInit();
    }, []);

    const getExamFileNameInit = async () => {
        if(!examId){
            return;
        }   
        try {
            const res = await getExamFileName({examId,});
            
            if(res.code === 200){   
                if(!res.data?.studentSubjectDetailFileName){
                    setFileList([]);
                    onChange(null);     
                    return;

                }
                setFileList([{
                    uid: res?.data?.nsId,
                    name: res.data?.studentSubjectDetailFileName,
                    status: 'done',
                }]);
                onChange(res.data?.studentSubjectDetailFileName);     
                return;
            }
            message.error(res.msg);
            
            
            
        } catch (error) {
            console.log(error,'getExamFileNameInit-error');
            
        }
    }

    const checkFileType = (file) => {
        const isAllowedType = allowedTypes.includes(file.type);
        const fileName = file.name.toLowerCase();
        const isAllowedExtension = allowedExtensions.some(ext => fileName.endsWith(ext));

        return isAllowedType || isAllowedExtension;
    };


    const handleBeforeUpload = (file) => {
        if (!checkFileType(file)) {
            message.error('只能上传 Excel (.xlsx, .xls) 或 ZIP (.zip) 格式的文件!');
            return Upload.LIST_IGNORE;
        }
        const isLt2M = file.size / 1024 / 1024 < 2000;
        if (!isLt2M) {
            message.error('文件不能超过 2000MB!');
            return Upload.LIST_IGNORE;
        }
        return true;
    };

    const handleCustomRequest = async({ file, onSuccess, onError}) => {
        try {
            let percent = 0;
            const formData = new FormData();
            formData.append('file', file);
            formData.append('examId', examId);
            const  res = await uploadFile(formData,{
                onUploadProgress: ({ loaded, total }) => {
                    percent = Math.floor((loaded / total) * 100);
                },
            });
            if(res?.code === 200){
                onSuccess('上传成功');
                message.success('文件上传成功');
                onChange(file?.name);
                setFileList([
                    {
                        uid: examId,
                        name: file?.name,
                        status: 'done',
                        percent,
                    },
                ]);
                await logger({description:"上传原始成绩"});
                return;
            }
            message.error(res?.msg);
        } catch (error) {
            onError(error);
            message.error('文件上传失败');
            console.log(error,'upload-error');
            
        }
        
        
    };      



    const handleRemove = (file) => {
        onChange(null);       
        setFileList((prev)=>{
            return prev.filter(item=>item.uid !== file.uid);
        }) 
    };


    const originProps = {
        name: "file",
        multiple: false,
        accept: '.xlsx,.xls,.zip',
        maxCount: 1,
        beforeUpload: handleBeforeUpload,
    };

    return (
        <div>
            <Upload {...originProps} customRequest={handleCustomRequest}  onRemove={handleRemove} fileList={fileList}>
                <Button type='primary' icon={<UploadOutlined />}>上传原始成绩</Button>
            </Upload>
            <p className={styles.upload_tips}>请上传原始成绩文件，请按照固定的excel表格格式进行上传，勿修改表格结构及固定文案，文件大小限制2000MB以内</p>
        </div>
    )
};

export default UploadScore;