import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Upload } from 'amos-designer';
import { request, payload, api } from '@gm/graphmod-utils';
import Tip from '../tip';
import './FormUpload.scss';

const { UrlConsts }  = api;
const { compleHeaders } = request;

/**
 * form表单文件上传
 *
 * @class FormUpload
 * @extends {Component}
 */
class FormUpload extends Component {
  static propTypes = {
    value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
    onChange: PropTypes.func,
    maxSize: PropTypes.number, // 每个大小最大值
    maxLength: PropTypes.number, // 最多上传多少个
    type: PropTypes.string, // 上传类型 图片img
    showPrefix: PropTypes.bool, // 上传图片的url中是否添加当前页面的IP和端口前缀。
    valueType: PropTypes.oneOf(['string', 'array']) // string表示值为string，多个图片用逗号隔开， array是数组
  };

  static defaultProps = {
    valueType: 'string'
  };

  constructor(props) {
    super(props);
    this.state = {
      fileList: []
    };
  }

  onRemove = (uid, d) => {
    let { fileList } = this.state;
    let { value, valueType } = this.props;
    if (valueType === 'array') {
      if (value && value.length > 0) {
        value = value.filter(e => e.url !== uid);
      }
    } else {
      // value = value.replace(`${uid},`, '');
      // value = value.replace(uid, '');
      fileList = fileList.filter(e => e.uid !== uid);
    }
    this.setState({ fileList: fileList });
    this.props.onChange(value);
  };

  getList = flag => {
    const { value, valueType } = this.props;
    const { fileList } = this.state;
    let list = [];
    if (valueType === 'string') {
      if (fileList.length > 0 && !flag) {
        list = fileList;
      } else {
        list = (value || '')
          .split(',')
          .filter(e => !!e)
          .map((e, index) => {
            console.log(e);
            return {
              uid: e,
              status: 'done',
              name: e.split('?name=')[1] || e.split('/')[1],
              url: e
            };
          });
      }
    } else {
      console.log(e);
      list = fileList.length > 0 && !flag ? fileList : (value || []).map((e, index) => ({ uid: e.url, status: 'done', ...e }));
    }
    return list;
  };
  /**
   * 调用上传接口前文件校验
   * @param {*} file
   * @param {*} item
   */
  handleBeforeUpload = info => {
    const oneMb = 1024;
    const { maxSize, maxLength } = this.props;
    if (maxLength) {
      if (maxLength < info.fileList.length) {
        Tip.warning(`最多上传${maxLength}个`);
        return false;
      }
    }
    if (maxSize) {
      const isLtM = info.file.size / oneMb / oneMb < maxSize;
      if (!isLtM) {
        Tip.warning(`大小不能超过${isLtM}M`);
        return false;
      }
    }
    return true;
  };

  handleChange = info => {
    const status = info.file.status;
    if (status !== 'uploading') {
      if (status === 'error') {
        Tip.error('服务器发生错误');
      } else {
        if (!this.handleBeforeUpload(info)) {
          return;
        }
        const response = info.file.response;
        payload(response)
          .then(d => {
            if (d) {
              let { value, valueType, showPrefix } = this.props;
              const prefix = showPrefix ? `${window.location.protocol}//${window.location.host}/` : '';
              const url = `${prefix}${Object.keys(d || {})[0]}`;
              const name = (d || {})[Object.keys(d || {})[0]];
              if (valueType === 'array') {
                if (value && value.length > 0) {
                  value.push({ url, name });
                } else {
                  value = [{ url, name }];
                }
              } else {
                value = `${value || ''}${value ? ',' : ''}${url}?name=${name}`;
              }
              this.setState({ fileList: [...this.state.fileList, { ...info.file, url }] });
              this.props.onChange(value);
            }
          })
          .catch(msg => {
            Tip.error(msg);
            this.setState({ fileList: [] });
          });
      }
    }
  };

  render() {
    const { type } = this.props;
    const { fileList } = this.state;
    console.log(fileList);
    return (
      <Upload
        className="mode-form-upload"
        action={UrlConsts.platFormUploadfileUrl()}
        onChange={this.handleChange}
        onRemove={this.onRemove}
        headers={compleHeaders()}
        fileList={fileList || []}
        name=""
        type={type}
      />
    );
  }
}

export default FormUpload;
