/**
 * @function 上传图片组件
 * @author Lyq
 */
import React, { Component } from 'react';
// import st from 'styled-components';
import {
  Upload,
  Button,
  Icon,
  message 
} from 'antd';
import moment from 'moment';
import {
  publicCommonFileUploadFile
} from '../../../services/api';
import $loading from '../../../utils/loading';
export default class Uploader extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      fileList: [],  //列表
      suffix: []  //后缀名，用于判断文件格式
    }
  }
  componentWillMount() {

  }
  componentWillReceiveProps(props) {   
    const values = this._getValues(props);
    // 检查新旧内容是否一样
    let isDiff = false;
    for(let i = 0; i < values.length; i++) {
      if(!this.state.fileList.some(({url}) => url == values[i])) {
        isDiff = true;
        break;
      }
    }
    
    if(isDiff) {
      const fileList = values.map((item, index) => ({
        url: item,
        name: item,
        status: 'done',
        uid: moment().valueOf()+index
      }));
      this.setState({fileList});
    }
  }

  componentDidMount() {

  }

  // 获取值的数组
  _getValues = (props) => {
    props = props || this.props;
    const { value } = props;
    if(this._getType(value) == 'Array') {
      return value;
    }else if(this._getType(value) == 'String') {
      return value.split(',');
    }else {
      return [];
    }
  }
  // 设置值
  _setFormVal = (values) => {
    let { suffix } = this.props;
    if(this._getType(suffix) == 'Array') {
      this.props.onChange(values); 
    }else if(this._getType(suffix) == 'String') {
      this.props.onChange(values.join(',')); 
    }
  }
  // 获取数据类型
  _getType = obj => Object.prototype.toString.call(obj).slice(8, -1)
  // 获取后缀名数组，正则，提示语
  _getSuffixInfo = () => {
    let { suffix } = this.props;
    const suffixInfo = {
      arr: []
    };
    if(suffix) {
      if(this._getType(suffix) == 'Array') {
        suffixInfo.arr = suffix;
      }else if(this._getType(suffix) == 'String') {
        suffixInfo.arr = suffix.split(',');
      }
    }
    const regs = [];
    const msgs = [];
    
    suffixInfo.arr.forEach(item => {
      regs.push(`(\.${item})`);
      msgs.push(`.${item}`);
    });
    suffixInfo.reg = new RegExp(regs.join('|'));
    suffixInfo.msg = msgs.join('\\');
    return suffixInfo;
  }

  render() {
    const { fileList } = this.state;
    const {num = 1} = this.props;
    return (
      <Upload
        showUploadList={true}
        fileList={fileList}
        beforeUpload={(file) => {
          let canUpload = true;
          const { reg, msg } = this._getSuffixInfo();
          if(!(file.name + '').toLocaleLowerCase().match(reg)) {
            message.error(`请上传拓展名为${msg}的文件!`);
            canUpload = false;
          }
          const { fileList } = this.state;
          const { num = 1 } = this.props;
          if(num != 1 && fileList.length >= num) {
            message.error(`最多上传${num}个文件!`);
            canUpload = false;
          }
          return canUpload;
        }}
        onRemove={(file) => {
          this.setState(state => {
            // const index = state.fileList.indexOf(file);
            const index = state.fileList.findIndex(item => item.url == file.url);
            const newFileList = state.fileList.slice();
            newFileList.splice(index, 1);
            return {
              fileList: newFileList,
            };
          });
        }}
        customRequest={({file}) => {
          const formData = new FormData();
          formData.append('xfile', file);
          $loading.open('文件上传中,请稍后。。。');
          publicCommonFileUploadFile(formData, false).then(res => {
            $loading.close();
            let { fileList } = this.state;
            const info = {
              url: res.data,
              name: res.data,
              status: 'done',
              uid: moment().valueOf() + fileList.length
            };
            const { num = 1 } = this.props;
            
            if(num > 1) {
              fileList.push(info);
            }else {
              fileList = [info];
            }
            this.setState({ fileList }, () => {
              const values = fileList.map(({url}) => url);
              this._setFormVal(values);
            });

          }).catch(ex => {
            $loading.close();
            console.log(ex);
          });
        }}
      >
        <Button style={{ marginLeft: 10 }} ><Icon type="upload" />上传文件</Button>{
          num>1&&
          <em 
          style={{marginLeft: 10}}
          >{`最多上传${num}个文件,`}</em>
        }
        <span style={{ marginLeft: 10 }}>支持拓展名：{this._getSuffixInfo().msg}
        </span>
      </Upload>
    );
  }
}

