/* eslint-disable no-param-reassign */
import { TASK_STATUS } from './static'
import Toast from '../toast'

export default {
  data() {
    return {
      tasks: [],
    }
  },
  methods: {
    findImage(key) {
      return this.images.find(item => item.key === key)
    },
    randomString(len) {
      const length = len || 32
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = chars.length
      let pwd = ''
      for (let i = 0; i < length; i += 1) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    addTasks(files) {
      const tasks = files.map(file => {
        const obj = file
        obj.key = obj.key || this.randomString(15)
        obj.xhr = new XMLHttpRequest()

        const image = this.findImage(obj.key)
        if (image) {
          image.orientation = obj.orientation
          image.naturalWidth = obj.naturalWidth
          image.naturalHeight = obj.naturalHeight
          image.content = obj.content
          image.status = TASK_STATUS.UPLOADING
        } else {
          const newImage = {
            key: obj.key,
            orientation: obj.orientation,
            naturalWidth: obj.naturalWidth,
            naturalHeight: obj.naturalHeight,
            content: obj.content,
            status: TASK_STATUS.UPLOADING,
          }
          if (this.isRow) {
            this.images.unshift(newImage)
          } else {
            this.images.push(newImage)
          }
        }
        this.emitChange(image)
        obj.status = TASK_STATUS.READY
        return obj
      })
      this.tasks.push(...tasks)
    },
    addSuccessImage(res) {
      const list = typeof res === 'string' ? [res] : res
      if (res.length) {
        if (this.staticKey) {
          const image = this.findImage(this.currentKey)
          const [url] = list
          if (!url) {
            return
          }
          image.url = url

          this.$emit('upload-success', {
            image,
            images: this.images,
          })
          this.dispatch('bxs-form-item', 'form.item.validate')
          this.emitChange(image)
        } else {
          if (list.length + this.images.length > this.maxAmount) {
            if (this.overAmount) {
              this.overAmount(this.maxAmount, list.length)
            } else {
              Toast(`最多可传${this.maxAmount}张`)
            }
            return
          }
          for (let i = 0; i < list.length; i += 1) {
            const url = list[i]
            if (url) {
              const image = {
                url: list[i],
                key: this.randomString(15),
              }
              if (this.isRow) {
                this.images.unshift(image)
              } else {
                this.images.push(image)
              }

              this.$emit('upload-success', {
                image,
                images: this.images,
              })
              this.dispatch('bxs-form-item', 'form.item.validate')
              this.emitChange(image)
            }
          }
        }
      }
    },
    taskStart(task) {
      task.status = TASK_STATUS.UPLOADING
      const image = this.findImage(task.key)
      if (image) {
        image.status = TASK_STATUS.UPLOADING
      }
      this.emitChange(image)
    },
    taskSuccess(task) {
      const image = this.findImage(task.key)
      if (image) {
        image.status = null
        image.url = task.imageUrl
        this.$emit('upload-success', {
          image,
          images: this.images,
        })
        this.dispatch('bxs-form-item', 'form.item.validate')
      }
      this.emitChange(image)
      this.removeTask(task.key)
    },
    taskFailed(task) {
      if (!task) {
        this.tasks.forEach(item => {
          if (item.status === TASK_STATUS.READY) {
            const img = this.findImage(item.key)
            if (img) {
              img.status = TASK_STATUS.FAILED
              this.emitChange(img)
              this.$emit('upload-failed', {
                img,
                images: this.images,
              })
              this.dispatch('bxs-form-item', 'form.item.validate')
            }
          }
        })
        this.tasks.forEach(item => {
          if (item.status === TASK_STATUS.READY) {
            this.removeTask(item.key)
          }
        })
      } else {
        const image = this.findImage(task.key)
        if (image) {
          image.status = TASK_STATUS.FAILED
          this.emitChange(image)
          this.$emit('upload-failed', {
            image,
            images: this.images,
          })
          this.dispatch('bxs-form-item', 'form.item.validate')
        }
        this.removeTask(task.key)
      }
    },
    removeTask(key) {
      for (let i = 0; i < this.tasks.length; i += 1) {
        const task = this.tasks[i]
        if (task.key === key) {
          if (task.xhr.readyState < 4) {
            task.xhr.abort()
          }
          this.tasks.splice(i, 1)
          return true
        }
      }
      return false
    },
    emitChange(image) {
      if (image) {
        const index = this.images.findIndex(item => item.key === image.key)
        if (index > -1) {
          this.$set(this.images, index, this.images[index])
        }
      }
      this.$emit('change', this.images)
    },
  },
}
