import React from 'react';
import { Modal, Button } from 'antd';

import Service from '@/common/js/service';
import { randomString } from '@/domains/basic-domain/utils';

let cutFlag = false;

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

  componentDidUpdate(prevProps) {
    const {
      visible,
      cutWidth = 550,
      cutHeight = 283,
      imageFile,
      bizCode = 'HOMEWORK_FILE'
    } = 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: (dataUrl) => {
            const { name } = imageFile;
            const fileName = randomString(16) + name.slice(name.lastIndexOf('.'));
            const { instId } = window.currentUserInstInfo;
            const params = {
              instId,
              bizCode: bizCode,
              accessTypeEnum: 'PUBLIC',
              resourceName: fileName
            }
            const cutImage = this.convertBase64UrlToBlob(dataUrl);
            Service.Hades("public/apollo/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 window.PhotoClip('#imgCutModalNew', options);
          _photoclip.load(imageFile);
          this.setState({ photoclip: _photoclip });
        } else {
          photoclip.clear();
          photoclip.load(imageFile);
        }
      }, 0);
    }
  }
  
  // base64转换成blob
  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 {
      title,
      visible,
      onClose, 
      reUpload,
      cutContentWidth,
      cutContentHeight,
      width = 550,
      needReUpload = false,
    } = this.props;
    return (
      <Modal
        title={title}
        width={width}
        visible={visible}
        onCancel={onClose}
        maskClosable={false}
        footer={[
          <Choose>
            <When condition={!needReUpload}>
              <Button
                key="back"
                onClick={onClose}
              >取消</Button>
            </When>
            <Otherwise>
              <Button
                key="back"
                onClick={reUpload}
              >重新上传</Button>
            </Otherwise>
          </Choose>,
          <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>
    )
  }
}

export default ImgCutModal;