/**
 * imui.Upload
 * @author jero
 * @date 2016-9-7
 */
import React from 'react';
import PropTypes from 'prop-types';
import RcUpload from 'rc-upload';
import assign from 'object-assign';
import classnames from 'classnames';
// @require '../style/index.scss'

class Upload extends React.Component {
  static propTypes = {
    // type: PropTypes.oneOf(['card']),
    action: PropTypes.string,
    data: PropTypes.object,
    // accept: PropTypes.string,
    disabled: PropTypes.bool,
    onChange: PropTypes.func,
    beforeUpload: PropTypes.func,
    className: PropTypes.string,
    getImgInfo: PropTypes.func,
  };

  static defaultProps = {
    // type: 'card', // 样式
    action: '', // cgi
    className: '', // 额外的类名
    data: null, // 参数
    // accept: '',
    disabled: false,
    onChange() {}, // change 回调
    beforeUpload() {},  // 上传前回调
    // 平台现有接口的返回值
    // {"retcode":0,
    //    "result": {
    //        "w":1711,
    //        "retcode":0,
    //        "color":"#688080",
    //        "url":"//10.url.cn/VdicfNvLModjKO7VkeV44caSbJKnLuU0ic9swhlSxN5qmoiaryCibH8HXKY/",
    //        "h":964}}
    getImgInfo(response) { // format 上传成功返回的字段，默认按照现网接口处理
      const ret = response && response.result;

      return ret ? {
        name: '',
        src: ret.url,
      } : null;
    },
  };

  constructor(props) {
    super(props);

    this.fileObj = {}; // 至始至终的文件对象

    this.state = {
      uploaded: false, // 是否成功上传过图片
      imgName: '',
      src: '', // 上传后的图片 url
    };

    ['beforeUpload', 'onStart', 'onSuccess', 'onError', 'onChange'].forEach(funcKey => {
      let func = this[funcKey];

      if (func) {
        this[funcKey] = func.bind(this);
      }
    });
  }

  beforeUpload(...params) {
    return this.props.beforeUpload(params);
  }

  onStart(file) {
    assign(this.fileObj, file, {
      status: 'uploading',
    });
    this.onChange(this.fileObj);
  }

  onError(error, response) {
    this.fileObj.status = 'error';
    this.fileObj.error = error;
    this.fileObj.response = response;
    this.onChange(this.fileObj);
  }

  onSuccess(response) {
    let info = this.props.getImgInfo(response);

    if (!info) {
      return console.warn('获取图片信息失败');
    }

    if (typeof info === 'string') {
      try {
        info = JSON.parse(info);
      } catch (ex) {
        console.warn('parse 返回信息失败', ex);
      }
    }

    info.uploaded = true;
    this.fileObj.status = 'done';
    this.fileObj.response = response;
    this.setState(info);
    this.onChange(this.fileObj);
  }

  // onProgress(...params) {
  //   console.log('progress', params);
  // }

  onChange(file) {
    this.props.onChange.call(this, file);
  }

  getValue() {
    return this.state.src;
  }

  componentWillReceiveProps(nextProps) {
    const { src } = nextProps;
    if (src !== undefined && src !== null && src !== this.props.src) {
      this.setState({ src, uploaded: !!src });
    }
  }

  componentDidMount() {
    const { src, imageName = '' } = this.props;
    if (src !== undefined && src !== null) {
      // eslint-disable-next-line react/no-did-mount-set-state
      this.setState({ src, imageName, uploaded: !!src });
    }
  }

  render() {
    // im-upload--success
    const p = assign({}, this.props, {
      onStart: this.onStart,
      onError: this.onError,
      // onProgress: this.onProgress,
      onSuccess: this.onSuccess,
      beforeUpload: this.beforeUpload,
      component: 'div',
    });
    const { desc, className, ...props } = p;
    const { uploaded, src, imageName } = this.state;
    const clsUpload = classnames({
      'im-upload': 1,
      'im-upload--success': uploaded,
      'im-upload--disabled': this.props.disabled,
      'im-upload--desc': !!desc,
    }, className);

    const clsWrap = classnames({
      'im-upload-wrap': 1,
      'im-upload-wrap--desc': !!desc,
    });

    return (
      <div className={clsWrap}>
        <RcUpload {...props}>
          <div className={clsUpload}>
            {uploaded ? null : (
              <div className="im-upload-replace">
                <i className="im-upload-icon">+</i>
                <span className="im-upload-text">点击上传图片</span>
              </div>
            )}
            {uploaded ?
              <img className="im-upload-img" src={src} alt={imageName} width="222" height="125" /> :
              null}
            <div className="im-upload-again">重新上传图片</div>
          </div>
        </RcUpload>
        {desc ? <div className="im-upload-intro">
          {desc}
        </div> : null}
      </div>
    );
  }
}

export default Upload;
