/*
 * @Author: welson
 * @Date: 2019-08-16 15:39:11
 * @Last Modified by: Mr.Welson
 * @Last Modified time: 2019-09-06 19:28:50
 */

/**
 *  @desc 原生 input 图片上传（支持多张上传）
 *  @params {string}    className   组件外层类名
 *  @params {boolean}   disabled  是否禁用
 *  @params {string}    multiple  多张上传开关, 默认false
 *  @params {number}    maxLength   单次最大上传数量, 默认100
 *  @params {number}    currentLength   已上传数量
 *  @params {number}    maxSize     单张图片大小限制，默认2, 即2M
 *  @params {function}  beforeUpload  准备上传之前的回调
 *  @params {function}  uploadDone  上传后的回调
 *  @params {function}  hasErrorCallback  上传失败回调
 *  @params {number}    expiretype  存储周期  0表示永久，1表示7天，2表示30天，3表示90天，默认为0
 *  @params {string}    uploadType  上传类型 默认remote,  local返回base64, remote返回羚羊地址
 *  @params {ReactElement}   children  接受子组件
 */

import React, { Component } from 'react'
import { message } from 'antd'
import { imageCompress, fileToBase64 } from '../utils/image'
import { uuid } from '@zenview/micro-utils'
class OriginUpload extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputKey: Math.random()
    }
    this.fileList = []
    this.inputRef = React.createRef()
  }
  // 本地上传
  localUpload = async fileList => {
    const result = await Promise.all(fileList.map(v => fileToBase64(v)))
    fileList.forEach((v, index) => {
      v.url = result[index]
      v.uploadType = 'local'
    })
    this.uploadDone(fileList)
  }

  // 远程上传
  remoteUpload = fileList => {
    this.uploadDone(fileList)
  }

  // 上传完成后的回调
  uploadDone = fileList => {
    const { customUpload } = this.props
    customUpload && customUpload(fileList)
  }

  //上传方法
  customRequest = fileList => {
    this.props.uploadType === 'remote' ? this.remoteUpload(fileList) : this.localUpload(fileList)
  }

  //上传之前
  beforeUpload = async files => {
    this.fileList = []
    const { maxSize = 2, maxLength = 100, currentLength = 0, beforeUpload } = this.props
    let fileList = files
    let is_fileLeng = true
    fileList = Array.prototype.slice.apply(fileList)
    if (currentLength + fileList.length > maxLength) {
      message.error(`最多选择${maxLength}张图片, 已选${currentLength}张`)
      is_fileLeng = false
    }
    beforeUpload && beforeUpload()
    for (let i = 0; i < fileList.length; i++) {
      let file = fileList[i]
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJPG) {
        message.error(`${file.name}:图片格式必须为JPG或者PNG!`)
      }

      const limitSize = file.size / 1024 / 1024 < maxSize
      if (!limitSize) {
        message.error(`${file.name}:图片大小不能超过${maxSize}M!`)
      }
      const fileSize = file.size
      if (!fileSize) {
        message.error(`${file.name}:图片文件错误!`)
      }
      let newFile = file
      if (file.type !== 'image/svg+xml') {
        newFile = await imageCompress(file)
      }
      if (isJPG && limitSize && fileSize && is_fileLeng) {
        newFile.uid = uuid()
        this.fileList.push(newFile)
      }
    }
    this.customRequest(this.fileList)
    this.setState({
      inputKey: Math.random()
    })
  }

  onClick = () => {
    this.inputRef.current.click()
  }
  onDrop = e => {
    this.onDragPrevent(e)
    let files = e.dataTransfer.files
    this.beforeUpload(files)
  }
  onDragPrevent = e => {
    e.stopPropagation()
    e.preventDefault()
  }

  onChange = e => {
    this.beforeUpload(e.target.files)
  }

  render() {
    const { className = '', multiple, disabled, children } = this.props

    return (
      <div
        className={`origin-input-upload-wrapper ${className} ${disabled ? 'disabled' : ''}`}
        onClick={this.onClick}
        style={{ position: 'relative' }}
        onDrop={this.onDrop}
        onDragOver={this.onDragPrevent}
        onDragLeave={this.onDragPrevent}
      >
        <input
          ref={this.inputRef}
          accept="image/png, image/jpeg, image/jpg"
          style={{ opacity: 0, position: 'absolute', left: 0, top: 0, width: '100%', height: '100%', display: 'none' }}
          type="file"
          key={this.state.inputKey}
          disabled={disabled}
          multiple={multiple}
          onChange={this.onChange}
        />
        {children}
      </div>
    )
  }
}

export default OriginUpload
