<template>
  <div class="fit absolute">
    <input
      ref="btn"
      name="file"
      type="file"
      style="opacity:0"
      class="fit absolute cursor-pointer"
      :multiple="more"
      @input="addItems($event.target.files)"
    />
    <div v-if="isStart" class="absolute-full row justify-center items-center" style="background:rgba(0,0,0,0.6)">
      <q-circular-progress
        show-value
        font-size="30px"
        :value="progressNum"
        size="220px"
        :thickness="0.1"
        color="teal"
        track-color="grey-3"
        class
      >{{ progressNum }}%</q-circular-progress>
    </div>
  </div>
</template>
<style lang="stylus"></style>

<script>
import _ from 'underscore'
import uploadFile from '../kyb-upload/upload-file'

let d = {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    more: { type: Boolean, default: false },
    acceptType: String,
    value: String,
    noWrap: Boolean
  },
  data: function() {
    return {
      isStart: false,
      progressNum: 0,
      fileIn: false,
      items: [],
      showImgCon: false,
      selectTarget: null,
      selectIndex: 0,
      uploading: false
    }
  },
  watch: {
    async value(old) {
      this.fixData(old)
    }
  },
  created() {
    this.fixData(this.value)
  },
  methods: {
    async fixData(old) {
      if (!old) old = ''
      if (!old.length) return
      old = old.split(',')
      let oldMap = this.items.reduce((re, item) => {
        re[item._id] = item
        return re
      }, {})

      old.forEach(async item => {
        if (!oldMap[item]) {
          let file = await this.getFileById(item)
          if (file) {
            this.items.push(file)
          }
        }
      })
    },
    drop(e) {
      this.fileIn = false
      let fileList = e.dataTransfer.files // 获取文件对象
      this.addItems(fileList)

      // console.log('drop', e)
      e.preventDefault()
    },
    async getFileById(_id) {
      let fileItem = await this.$loadEntity('file', 'FileItem', _id)
      if (!fileItem || !Object.keys(fileItem).length) {
        return null
      }
      fileItem.fileUrl = (window.fileApiBasePath || '') + '/api/file/FileItem/getFile?_id=' + _id
      fileItem.extendName = fileItem.name && fileItem.name.split('.').length > 1 ? fileItem.name.split('.')[1] : ''
      fileItem.isImage = fileItem.type && fileItem.type.indexOf('image') > -1
      fileItem.$needUpload = false

      return fileItem
    },
    addItems(items) {
      _.forEach(items, item => {
        console.log('file:', item)
        var fileUrl = window.URL.createObjectURL(item)
        let names = item.name.split('.').filter(v => v && v.length > 0)
        let extendName = names.length > 1 ? names[names.length - 1] : ''
        extendName = extendName.toLowerCase()
        // check file type
        if (this.acceptType && this.acceptType.length > 0) {
          if (!extendName || extendName.length === 0 || `,${this.acceptType},`.indexOf(`,${extendName},`) === -1) {
            this.$q.showNotifi(`文件类型不正确，仅支持：[${this.acceptType}]类型文件`)
            return true
          }
        }
        item.extendName = extendName
        this.items.push({
          _id: ''.genUUID(),
          fileUrl: fileUrl,
          updateTime: item.lastModified,
          name: item.name,
          extendName: extendName,
          size: item.size + '',
          isImage: item.type.indexOf('image') > -1,
          type: item.type,
          $needUpload: true,
          file: item
        })
        this.upload(this.items.length - 1)
      })
    },
    showFile($event, index) {
      let obj = this.items[index]
      if (obj.isImage) {
        this.showImgCon = true
        this.selectIndex = this.items.filter(item => item.isImage).findIndex(item => item === obj)
        // let item = this.items[index]
        let srcEl = this.$refs['item_' + index][0]
        this.selectTarget = { el: srcEl }
      }
    },
    upload(index) {
      this.isStart = true
      let item = this.items[index]
      console.log(item)
      item.$uploadNum = '1'
      item.$showProgress = true
      this.uploading = true
      this.$forceUpdate()
      let obj = this

      item.file.token = this.__genToken(!this.$route.path.startsWith('/admin') && '___front_token')
      uploadFile.bind(this)(
        item.file,
        res => {
          console.log('end upload')
          item.$uploadNum = '100'
          obj.$forceUpdate()
          setTimeout(() => {
            if (res && res._id) {
              Object.assign(item, res)
              item.file._id = res._id
            }
            item._id = item.file._id
            item.$showProgress = false
            item.$needUpload = false
            item.fileUrl = (window.fileApiBasePath || '') + '/api/file/FileItem/getFile?_id=' + item.file._id
            let v
            if (this.more) {
              v = this.items
                .filter(item => !item.$needUpload)
                .map(item => item._id)
                .join(',')
            } else {
              v = item._id
              this.items.splice(0, this.items.length, item)
            }
            this.uploading = false
            this.$emit('input', v)
            this.$emit('upload-end', v)
            obj.$forceUpdate()
            this.progressNum = 0
            this.isStart = false
          }, 2000)
        },
        progressNum => {
          // console.log('p--: ', num)
          this.progressNum = progressNum
          item.$uploadNum = progressNum + ''
          obj.$forceUpdate()
        },
        error => {
          if (error && error.status === 401) {
            this.$router.push('/login')
            return
          }
          item.$uploadNum = '100'
          item.$showProgress = false
          item.$needUpload = false
          this.uploading = false
          obj.$q.showNotifi(error)
          obj.$forceUpdate()
        }
      )
    }
  }
}
export default d
</script>
