import React from 'react';
import PropTypes from 'prop-types';
import { Modal, Button } from 'antd';
import Service from '@/common/js/service';
import User from '@/common/js/user';
import PhotoClip from 'photoclip'
let cutFlag = false;

class ImgCutModalNew extends React.Component {
  state = {
    photoclip: null,
    imgAddress: null
  }

  componentDidUpdate(prevProps) {
    const { visible, cutWidth, cutHeight, imageFile, width, bizCode = 'HOMEWORK_FILE', compress, compressSize = 1024 } = this.props;
    if (visible && imageFile) {
      setTimeout(() => {
        const { photoclip } = this.state;
        const okBtnDom = document.querySelector('#clipBtn');
        const options = {
          size: [cutWidth, cutHeight],
          rotateFree: false,
          ok: okBtnDom,
          maxZoom: 1,
          style: {
            jpgFillColor: 'transparent'
          },
          done: async (dataUrl) => {
            const { name } = imageFile;
            const fileName = window.random_string(16) + name.slice(name.lastIndexOf('.'));

            const params = {
              accessTypeEnum:"PUBLIC",
              bizCode:'CLOUD_CLASS_COMMON',
              instId:User.getStoreId(),
              resourceName:name
            }
            // 压缩
            if (compress) {
              const compressSizeByte = compressSize * 1024;
              dataUrl = this.getBase64Size(dataUrl) > compressSizeByte ? await this.handleCompressImg(dataUrl, compressSizeByte, cutWidth) : dataUrl;
            }
            const cutImage = this.convertBase64UrlToBlob(dataUrl);
            Service.Hades('public/hades/commonOssAuthority', params).then((res) => {
              const { resourceId, accessId, policy, callback, signature,key, host } = res.result;
              const localUrl = URL.createObjectURL(cutImage);
              // 构建上传的表单
              const xhr = new XMLHttpRequest();
              const formData = new FormData();
              formData.append("OSSAccessKeyId", accessId);
              formData.append("policy", policy);
              formData.append("callback", callback);
              formData.append("Signature", signature);
              formData.append("key", key);
              formData.append("file", cutImage);
              formData.append("success_action_status", 200);
              xhr.open("POST", host);
              xhr.onload = () => {
                this.props.onOk(localUrl, resourceId);
                setTimeout(() => {
                  cutFlag = false;
                }, 2000)
              };
              xhr.send(formData);
              this.setState({ xhr })
            })
          }
        };
        if (!photoclip) {
          const _photoclip = new PhotoClip('#imgCutModalNew', options);
          _photoclip.load(imageFile);
          this.setState({ photoclip: _photoclip });
        } else {
          photoclip.load(imageFile);
        }
      }, 0);
    }
  }

  // 压缩图片
  handleCompressImg(dataUrl, compressSize, cutWidth) {
    const that = this;
    return new Promise((resolve, reject) => {
      const newImage = new Image();
      newImage.src = dataUrl;
      newImage.setAttribute("crossOrigin", 'Anonymous');	//url为外域时需要
      newImage.onload = function () {
        let imgWidth = this.width;
        let imgHeight = this.height;
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        canvas.width = cutWidth;
        canvas.height = cutWidth * imgHeight / imgWidth;
        let quality = 0.92;//压缩系数0-1之间
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
        let base64 = canvas.toDataURL("image/jpeg", quality);
        while (that.getBase64Size(base64) > compressSize) {
          quality -= 0.01;
          base64 = canvas.toDataURL("image/jpeg", quality);
        }
        resolve(base64);
      }
    })
  }

  // 获取base64文件大小
  getBase64Size(baseStr) {
    const eqTagIndex = baseStr.indexOf("=");
    baseStr = eqTagIndex != -1 ? baseStr.substring(0, eqTagIndex) : baseStr;
    const strLen = baseStr.length;
    const fileSize = strLen - (strLen / 8) * 2;
    return fileSize;
  }

  // base64转换成blol
  convertBase64UrlToBlob(urlData) {
    const bytes = window.atob(urlData.split(",")[1]);
    const ab = new ArrayBuffer(bytes.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], { type: "image/png" });
  }

  handleImgCutDone = () => {
    if (!cutFlag) {
      cutFlag = true;
      this.refs.hiddenBtn.click();
    }
  }


  render() {
    const {
      visible, onClose, needReUpload, reUpload,
      title, width, cutWidth, cutHeight,
      cutContentWidth, cutContentHeight
    } = this.props;
    return (
      <Modal
        title={title}
        width={width}
        visible={visible}
        onCancel={onClose}
        maskClosable={false}
        footer={[
          !needReUpload ?
            <Button
              key="back"
              onClick={onClose}
            >取消</Button> :
            <Button
              key="back"
              onClick={reUpload}
            >重新上传</Button>,
          <Button
            key="submit"
            type="primary"
            onClick={this.handleImgCutDone}
          >确定</Button>
        ]}>
        <div
          id="imgCutModalNew"
          style={{
            width: `${cutContentWidth || 620}px`,
            height: `${cutContentHeight || 420}px`
          }}
        ></div>
        <div
          id="clipBtn"
          style={{ display: 'none' }}
          ref="hiddenBtn"
        />
      </Modal>
    )
  }
}

ImgCutModalNew.propTypes = {
  visible: PropTypes.bool,
  needReUpload: PropTypes.bool,   // 是否需要重新上传
  title: PropTypes.string,
  width: PropTypes.number,
  cutWidth: PropTypes.number,
  cutHeight: PropTypes.number,
  imageFile: PropTypes.object
};
ImgCutModalNew.defaultProps = {
  width: 550,
  cutWidth: 502,
  cutHeight: 283,
  needReUpload: false,
};

export default ImgCutModalNew;