import React, { PureComponent, useState } from 'react';
import { Upload, message, Button } from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
import { takeRight } from 'lodash';
import axios from 'axios';
import { GetCosRequestURL } from "./services"

//页面 相当于 class
const PlanManage = () => {

  const [cosInfo, SetCosInfo] = useState({
    domain: "",
    fileUrl: "",
    param: "",
    allUrl: "",
    seeUrl:""
  });
  const uploadProps = {
    beforeUpload: (file) => {
      var index = file.name.lastIndexOf(".");
      var ext = file.name.substr(index + 1);
      GetCosRequestURL({ directory: "adv", fileExtension: ext,method:"PUT" }).then((r) => {
        SetCosInfo(r)
      });
    },
    name: 'file',
    showUploadList: false,
    multiple: false,
    accept: '.png, .jpg, .jpeg, .gif',
    action: cosInfo.fileUrl+'?'+cosInfo.param,
    // 这里需要指定文件上传的content-type
    headers: {
      'Content-Type': 'application/octet-stream',
    },
    // 自定文件上传的方法，覆盖组件的 onChange 方法，可以定义上传不同阶段的行为（由 axios 默认提供）
    onStart(file) {
      console.log('onStart', file, file.name);
    },
    onSuccess(ret, file) {
      console.log('onSuccess', ret, file);
      that.props.getData('/cos/bb/21aa1.jpg');
    },
    onProgress({ percent }, file) {
      console.log('onProgress', `${percent}%`, file.name);
    },
    onError(err) {
      console.log('onError', err);
    },
    customRequest({
      action,
      file,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {
      // 使用 FileReader 将上传的文件转换成二进制流，满足 'application/octet-stream' 格式的要求
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      let fileData = null;
      reader.onload = (e) => {
        // 在文件读取结束后执行的操作
        fileData = e.target.result;
        // 使用 axios 进行文件上传的请求
        axios.put(action, fileData, {
          withCredentials,
          headers,
          onUploadProgress: ({ total, loaded }) => {
            // 进行上传进度输出，更加直观
            onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
          },
        }).then(response => {
          onSuccess(response, file);
        })
          .catch(onError);
      };
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    },
  };
  return (
    <div>
      <Upload {...uploadProps}>
        <Button icon={<UploadOutlined />}>上传</Button>
      </Upload>
    </div>
  );
};
export default PlanManage;
