/**
 * 2019年9月27日
 * 钟是志
 * 文件上传组件
 * 通过设置一个隐藏的input的框 和一个覆盖在上面的P标签实现文件上传功能
 * */
import React, { Fragment } from 'react';
import { Button, Toast } from 'antd-mobile';
import { uploadFile } from './api';
import PropTypes from 'prop-types';
import FormArray from '@/H5Public/baseComponents/FormArray';

export default class UploadFile extends React.Component {
  constructor(props) {
    super(props);
  }

  /**
   * 图片压缩函数
   *
   * */
  zipImage = (file) => {
    let fileSizeMb = file.size / 1024 / 1024;
    let fileName = file.name;
    if (fileSizeMb < this.props.fileSizeMb) {  // 1MB 以下的图片不需要压缩。
      this.uploadImage(file);
      return false;
    }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      //这里的e.target.result就是转换后base64格式的图片文件
      let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
      image.src = e.target.result;
      return image.onload = () => {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        let imageWidth = image.width * 0.3;    //压缩后图片的大小
        let imageHeight = image.height * 0.3;
        let data = '';
        canvas.width = imageWidth;
        canvas.height = imageHeight;

        context.drawImage(image, 0, 0, imageWidth, imageHeight);
        data = canvas.toDataURL('image/jpeg');
        let zipFile = this.dataURLtoFile(data, fileName);
        this.uploadImage(zipFile);
        //压缩完成
      };
    };
  };

  dataURLtoFile = (dataurl, filename) => {//将base64转换为文件
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];

    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  };

  uploadImage = (file) => {
    Toast.loading('文件上传中', 1);
    uploadFile({ file }).then((res) => {
      Toast.hide();
      if (res && res.url) {
        Toast.success('上传成功!', 1);
        console.log(res);
        this.props.returnFile(
          {
            name: file.name,
            uid: res.id,
            status: 'done',
            previewType: res.previewType,
            url: res.url,
          },
        );
      }
    });
  };

  imgFileChange = (e) => {
    const file = this.fileInput.files[this.fileInput.files.length - 1];
    if (!file) {
      return false;
    }
    // console.log(file);
    this.zipImage(file);
  };

  render() {
    const { ShowComponent, accept } = this.props;
    return (
      <div style={{
        fontSize: '18px',
        paddingTop: '10px',
        paddingBottom: '10px',
        position: 'relative',
      }}>
        {ShowComponent ? ShowComponent : <p
          style={{
            position: 'absolute',
            top: 0,
            bottom: 0,
            left: 0,
            right: 0,
            textAlign: 'center',
            lineHeight: '46px',
            margin: 'auto',
          }}>
          上传
        </p>}

        <input type="file"
               accept={accept}
               id={'infoUpload'}
               style={{ opacity: 0 }}
               onChange={this.imgFileChange}
               ref={input => {
                 this.fileInput = input;
               }}
        />
      </div>

    );
  }

}
UploadFile.propTypes = {
  returnFile: PropTypes.func.isRequired,  //回调函数
  fileSizeMb: PropTypes.number.isRequired, // 图片如果超过了此值 则执行压缩操作  默认值最大1MB；
  // accept: PropTypes.string,
};
FormArray.defaultProps = {
  fileSizeMb: 1,
  accept: 'image/*',
};
