import VideoNews from '@/components/VideoNews';
import { getOssInfo } from '@/services/ant-design-pro/api';
import { getMD5 } from '@/utils';
import { InboxOutlined } from '@ant-design/icons';
import { request } from '@umijs/max';
import { message, Spin, Upload } from 'antd';
import { RcFile } from 'antd/lib/upload';
import React, { useState } from 'react';
import './index.less';

interface Props {
  value?: string;
  onChange?: (value?: string) => void;
}
/**
 * 视频上传
 * @returns
 */
const UploadVideo: React.FC<Props> = ({ value, onChange }) => {
  /** 变量START */
  const [videoFile, setVideoFile] = useState<string | undefined>(value);
  const [loading, setLoading] = useState<boolean>(false);
  /** 变量END */

  const beforeUpload = async (file: RcFile) => {
    console.log('file--->', file);
    const isZipOrRar = file.type === 'video/mp4';
    if (!isZipOrRar) {
      message.error('您只能上传MP4文件！');
    }
    const fileSizeM = file.size / 1024 / 1024;
    const isLt20M = fileSizeM < 20;
    if (!isLt20M) {
      message.error(`视频大小必须小于20MB！`);
    }
    return isZipOrRar && isLt20M;
  };

  return (
    <div className="myUploadVideo">
      <Upload.Dragger
        name="file"
        accept="video/mp4"
        className="avatar-uploader"
        beforeUpload={beforeUpload}
        maxCount={1}
        showUploadList={false}
        disabled={loading}
        customRequest={(options: any) => {
          setLoading(true);
          getOssInfo({ type: 'video/mp4', fileType: 'video' }).then(async (res) => {
            try {
              let formData = new FormData();
              Object.keys(res.data).forEach((key: string) => {
                if (key !== 'url') {
                  formData.append(key, res.data[key]);
                }
              });
              formData.append('file', options.file);
              const md5 = await getMD5(options.file);
              let urlData = await request(res?.data?.ossUrl, { method: 'POST', data: formData });
              setLoading(false);
              if (urlData?.data?.url) {
                setVideoFile(urlData?.data?.url);
                onChange?.(urlData?.data?.url);
              }
            } catch (error) {
              setLoading(false);
            }
          });
        }}
      >
        <Spin spinning={loading}>
          {videoFile ? (
            <div className="video-content">
              <VideoNews src={videoFile} />
            </div>
          ) : (
            <>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">单击或拖动视频到此区域进行上传</p>
              <p className="ant-upload-hint">素材大小：小于20M</p>
            </>
          )}
        </Spin>
      </Upload.Dragger>
    </div>
  );
};

export default React.memo(UploadVideo);
