import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Upload, Message } from 'amos-antd';
import { OltSerUrl } from './../../../../consts/urlConsts';
import { message } from 'amos-framework';
import Icon from 'amos-icon';
import { editSubviewImgAction } from './../../../../services/topoService';

const HEXSIZE = 1024;

/**
 *
 *
 * @class UploadSinglePicModal
 * @extends {Component}
 */
class UploadSinglePicModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      file: undefined,
      imageUrl: undefined,
      previewVisible: false
    };
  }
  componentWillMount() {}

  componentDidMount() {}

  componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {}

  /**
   *
   *图片加载到浏览器
   * @memberof UpLoadIcon
   */
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  /**
   *监听
   *
   * @memberof UpLoadIcon
   */
  handleChange = info => {
    this.setState({ file: info.file });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false
        })
      );
      this.imgFile = info.file.originFileObj;
    }
  };

  /**
   *
   *图片校验
   * @memberof UpLoadIcon
   */
  beforeUpload = file => {
    var pattern = /image\/(gif|jpeg|png|jpg|bmp)$/;
    const isImg = pattern.test(file.type);
    if (!isImg) {
      Message.error('请选择符合格式的图片！（gif|jpeg|png|jpg|bmp）');
    }
    const isLt2M = file.size / HEXSIZE < 500;
    if (!isLt2M) {
      Message.error('图片最大为 500Kb!');
    }
    return isImg && isLt2M;
  };

  handleCancel = () => this.setState({ previewVisible: false });

  uploadSUbgraphPics = () => {
    this.setState({ visible: true });
  };

  /**
   * 关闭新增对话框
   */
  handCancel = () => {
    this.setState({
      visible: false,
      loading: false,
      file: undefined,
      imageUrl: undefined,
      previewVisible: false
    });
    this.imgFile = undefined;
  };

  /**
   *
   *保存图片
   * @memberof UpLoadImg
   */
  saveSubGraphImgAction = () => {
    const reader = new FileReader();
    reader.addEventListener('load', () => this.upLoadImgToSave(reader.result));
    let imgFile = this.imgFile;
    if (JSON.stringify(imgFile) === '{}') {
      let imgInfo = { binaryImg: null, imgName: 'default.png' };
      this.saveSubGraphImg(imgInfo);
    } else {
      if (imgFile !== undefined) {
        reader.readAsBinaryString(this.imgFile);
      } else {
        message.danger('请选择要替换的背景图片！');
      }
    }
  };

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  upLoadImgToSave = binaryImg => {
    let name = `${this.imgFile.uid}-${this.imgFile.name}`; //使用name+uid作为图片名，以防图片名冲突
    let imgInfo = { binaryImg: binaryImg, imgName: name };
    this.saveSubGraphImg(imgInfo);
  };

  saveSubGraphImg = imgInfo => {
    let { subviewId } = this.props;
    Object.assign(imgInfo, { id: subviewId });
    editSubviewImgAction(imgInfo).then(data => {
      message.success('操作成功');
      this.props.chooseBackground(imgInfo.imgName);
      this.props.updateBkImg(imgInfo.imgName);
      this.handCancel();
    });
  };

  render() {
    let { style, imgName } = this.props;
    const uploadButton = (
      <div className="upload-icon-panel">
        {this.state.loading ? (
          <Icon type={'loading'} />
        ) : imgName !== null ? (
          <img src={`${OltSerUrl.fetchDeviceImg}/graph/${imgName}`} alt="" style={style} />
        ) : (
          <img src={require('./../../../../assets/iot/deviceManage/add_template.png')} alt="" style={{ paddingTop: '60px' }} />
        )}
      </div>
    );
    const imageUrl = this.state.imageUrl;
    const url = OltSerUrl.addDevice;
    return (
      <div className="single-upload-img-root">
        <div className="single-upload-img-icon" onClick={this.uploadSUbgraphPics} title="上传背景图片">
          <img src={require('./../../../../assets/iot/topo/bk.png')} style={{ width: '30px', height: '26px' }} alt="" />
        </div>
        <Modal
          className="background-modal"
          maskClosable={false}
          title="上传背景图片"
          closable
          visible={this.state.visible}
          footer={null}
          onCancel={this.handCancel}
          width={367}
        >
          <div className="single-upload-pics-content">
            <Upload name="avatar" listType="picture-card" showUploadList={false} action={url} beforeUpload={this.beforeUpload} onChange={this.handleChange}>
              {imageUrl ? <img src={imageUrl} alt="" style={style} /> : uploadButton}
            </Upload>
            <div className="modal-operate-root">
              <div className="modal-operate-clone" onClick={this.handCancel}>
                取消
              </div>
              <div className="modal-operate-view" onClick={this.saveSubGraphImgAction}>
                确定
              </div>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

UploadSinglePicModal.propTypes = {
  setImgFile: PropTypes.func,
  style: PropTypes.object,
  defaultImg: PropTypes.string,
  subviewId: PropTypes.string,
  imgName: PropTypes.string,
  chooseBackground: PropTypes.func,
  updateBkImg: PropTypes.func
};

UploadSinglePicModal.defaultProps = {
  style: { position: 'relative', top: '-10px' }
  // defaultImg: `${OltSerUrl.fetchDeviceImg}/device_default.png`
};

export default UploadSinglePicModal;
