import React, { Component } from 'react';
import styles from './style.css';
import addimgIcon from './images/add_pic_bg@2x.png';
import delIcon from './images/delete_pic_btn@2x.png';
import { Toast } from 'antd-mobile';
class ImagePicker extends Component {
  constructor(props) {
    super(props);

    let canDom = document.getElementById('ksCanvasBox');
    if (!canDom) {
      canDom = document.createElement('canvas');
      canDom.id = 'ksCanvasBox';
      canDom.setAttribute('width', '590px');
      canDom.setAttribute('height', '334px');
      canDom.setAttribute('style', 'display: none');
      document.body.appendChild(canDom);
    }
    this.canvas = canDom;

    this.state = {
      aspectRatio: 590 / 334,
      done: false,
      hasValue:
        Object.keys(props).find(i => i === 'value') === -1 ? false : true,
      files: [],
    };
  }
  shouldComponentUpdate(nextProps) {
    const { value } = this.props;
    if (!nextProps.value && value) {
      this.deleteImage();
    }
    return true;
  }
  selectImage = () => {
    const { done } = this.state;
    const { showView } = this.props;
    if (done) {
      showView();
    } else {
      this.refs.input.dispatchEvent(new MouseEvent('click'));
    }
  };
  deleteImage = e => {
    e && e.stopPropagation();
    const { onChange } = this.props;
    console.log('del');
    this.refs.input.value = '';
    this.setState(() => ({
      files: [],
      done: false,
    }));
    if (onChange) {
      onChange(null);
    }
  };
  uploadImg = e => {
    const { onChange } = this.props;
    const filesList = e.target.files;
    // const fileUrl = this.createObjectURL(filesList[0]);
    this.resizeImg(filesList[0])
      .then(({ file, url }) => {
        this.setState(() => ({
          files: [url],
          done: true,
        }));
        if (onChange) {
          onChange({
            filesList: [file],
            url: url,
          });
        }
      })
      .catch(err => {
        Toast.fail(err);
      });
  };
  createObjectURL = blob => {
    if (window.URL) {
      return window.URL.createObjectURL(blob);
    } else if (window.webkitURL) {
      return window.webkitURL.createObjectURL(blob);
    }
    return null;
  };
  revokeObjectURL = url => {
    if (window.URL) {
      return window.URL.revokeObjectURL(url);
    } else if (window.webkitURL) {
      return window.webkitURL.revokeObjectURL(url);
    }
  };
  resizeImg = file =>
    new Promise((resolve, reject) => {
      const { aspectRatio } = this.state;
      const ctx = this.canvas.getContext('2d');
      const fileUrl = this.createObjectURL(file);
      ctx.clearRect(0, 0, 590, 334);
      const img = new Image();
      img.onload = () => {
        console.log(img.width, img.height);
        let imgRatio = img.width / img.height;
        let x, y;
        if (imgRatio > aspectRatio) {
          x = 590;
          y = 590 / imgRatio;
        } else {
          x = 334 * imgRatio;
          y = 334;
        }
        ctx.drawImage(img, (590 - x) / 2, (334 - y) / 2, x, y);
        this.canvas.toBlob(blob => {
          const dataURL = this.canvas.toDataURL('image/png');
          console.log(file.size, dataURL.length);
          resolve({ file: blob, url: dataURL });
        });
      };
      img.onerror = () => {
        reject('背景加载失败');
      };
      img.src = fileUrl;
    });
  render() {
    const { className } = this.props;
    const { files, done } = this.state;
    return (
      <div
        className={
          className ? `${className} ${styles.imageWrap}` : styles.imageWrap
        }
        onClick={this.selectImage}
      >
        {done ? (
          <img className={styles.innerImg} src={files[0]} alt="" />
        ) : (
          <img src={addimgIcon} alt="" />
        )}
        {done && (
          <img
            src={delIcon}
            className={styles.delBtn}
            alt=""
            onClick={this.deleteImage}
          />
        )}
        <input
          ref="input"
          type="file"
          accept="image/*"
          onChange={this.uploadImg}
          style={{ display: 'none' }}
        />
      </div>
    );
  }
}

export default ImagePicker;
