import React from "react";
import { Upload, Icon, Button, message } from "antd";
import PropTypes from "prop-types";
import { uploadUrl } from "../../services/api";
import Immutable, { Map, is } from 'immutable';
import "./less/style.less";

/**w
 *
 * @desc    把 antd 组件的文件上传组件封装在一起，
 *          只需要关心初始化的值 init 以及 onchang 方法。支持多个文件
 * @param   {Array} init 初始化的地址
 * @param   {func} onResult(data)  返回文件上传结果。
 * @param   {Int} num  设置文件上传个数。
 * @param   {Int} disabled  设置文件是否禁止上传。
 * @param   {types} 限制上传文件的格式。
 * @param   {size} 限制上传文件的大小。 单位MB  2019-09-23
 * @return
 */

class PUpLodadFile extends React.Component {
  state = {
    fileList: [],
    ifInit: false //是否加载完成初始化
  };

  static propTypes = {
    init: PropTypes.array,
    onResult: PropTypes.func,
    num: PropTypes.number,
    disabled: PropTypes.bool
  };
  componentWillMount = () => {
    if (this.props.init) {
      if (Object.prototype.toString.call(this.props.init) == "[object Array]") {
        this.updataList(this.props.init);
      }
    }
  };

  componentWillReceiveProps = nextProps => {
    const nextInit = nextProps.init;
    const thisInit = this.props.init;
    if (this.state.ifInit) {
      return;
    }

    if (JSON.stringify(nextInit) !== JSON.stringify(thisInit)) {
      if (nextInit && nextInit.length !== 0) {
        this.updataList(nextInit);
      }
    }
  };

  shouldComponentUpdate = (nextProps = {}, nextState = {}) => {
    const thisProps = this.props || {},
      thisState = this.state || {};

    if (
      Object.keys(thisProps).length !== Object.keys(nextProps).length ||
      Object.keys(thisState).length !== Object.keys(nextState).length
    ) {
      return true;
    }
    for (const key in nextProps) {
      if (
        thisProps[key] !== nextProps[key] ||
        !is(thisProps[key], nextProps[key])
      ) {
        return true;
      }
    }
    for (const key in nextState) {
      if (
        thisState[key] !== nextState[key] ||
        !is(thisState[key], nextState[key])
      ) {
        return true;
      }
    }
    return false;
  };

  //刷新
  updataList = arr => {
    const newArr = arr.filter(val => val.trim() !== "");
    if (newArr.length !== 0) {
      let fileList = [];
      newArr.map((val, key) => {
        key = key + 1;
        fileList.push({
          name: "文件" + key,
          uid: key,
          url: val
        });
      });
      this.setState({ fileList, ifInit: true });
    }
  };

  handleChange = info => {
    let result = true;
    const { status } = info.file;

    const disabled = this.props.disabled ? this.props.disabled : false;
    if (disabled) {
      return;
    }

    //除了移除状态，上传过程中，判断是否符合上传规则
    if (status !== "removed") {
      result = this.beforeUpload(info.file);
    }
    if (!result) {
      return;
    }

    let fileList = [...this.state.fileList];
    fileList = info.fileList;
    this.setState({ fileList });

    if (status !== "uploading") {
    }
    if (status === "done") {
      if (info.file.response.retType !== "0") {
        /// 本地上传成功，但服务器返回上传错误
        this.state.fileList.map((item, index) => {
          if (item.uid === info.file.uid) {
            const removeErrFileList = [...this.state.fileList];
            removeErrFileList.splice(index, 1);
            this.setState({
              fileList: removeErrFileList
            });
            // this.state.fileList[index].status = "error";
          }
        });
        message.error(info.file.response.msg);
        return;
      }
      // this.props.result("done", info.file.response.data.filegroupid);
      message.success(`${info.file.name} 文件上传成功。`);

      if (this.props.onResult) {
        if (info.fileList.length === 0) {
          return;
        }
        const result = info.fileList.reduce((acc, elem) => {
          if (elem.response && elem.response.data) {
            acc.push(elem.response.data);
            return acc;
          }
          if (elem.url) {
            acc.push(elem.url);
            return acc;
          }
        }, []);
        this.props.onResult(result);
      }
    } else if (status === "error") {
      message.error(`${info.file.name} 文件上传失败。`);
    }
    if (info.file.status == "removed") {
      let result;
      //如果全部删除
      if (info.fileList.length === 0) {
        this.props.onResult([]);
        return;
      } else {
        //如果部分删除
        result = info.fileList.reduce((acc, elem) => {
          if (elem.url) {
            acc.push(elem.url);
            return acc;
          }
        }, []);
      }
      this.props.onResult(result);
    }
  };

  beforeUpload = file => {
    /**
     * 根据传进来的文件类型，在上传之前先判断
     */
    if (this.props.type.length > 0) {
      let type = false;
      this.props.type.forEach(element => {
        if ((file.name + '').toLocaleLowerCase().indexOf(element) > -1) {
          type = true;
        }
      });
      if (!type) {
        this.setState({
          loading: false
        });
        message.error("请上传" + this.props.type.toString() + "类型的文件!");
        return false;
      }
    }
    const size = this.props.size ? this.props.size : 8;
    const maxSize = file.size / 1024 / 1024 < size;
    if (!maxSize) {
      message.error(`文件应小于${size}MB!`);
      return false;
    }
    return true;
  };

  render() {
    const { fileList } = this.state;
    const num = this.props.num ? this.props.num : 1;
    const uploadButton = (
      <div>
        <Button disabled={this.props.disabled||fileList.length >= num}>
          <Icon type="upload" /> 上传文件
        </Button>
        <p>支持扩展名：{this.props.type.toString()}的文件</p>
      </div>
    );
    // const num = this.props.num ? this.props.num : 1;
    // const disabled = this.props.disabled ? this.props.disabled : false;
    return (
      <div className="clearfix">
        <Upload
          action={uploadUrl}
          name="xfile"
          fileList={fileList}
          onChange={this.handleChange}
          // disabled={disabled}
          // beforeUpload={this.beforeUpload}
        >
          {uploadButton}
          {/* {fileList.length >= num ? null : uploadButton} */}
        </Upload>
      </div>
    );
  }
}

export default PUpLodadFile;
