<template>
  <div
    class="file-upload overflow-auto q-pa-xs row relative-position"
    :class="(fileIn?'file-in ':'')+(!items||!items.length?'relative-position items-center justify-center':'')"
    @drop="drop"
    @dragleave="dragleave"
    @dragenter="dragenter"
    @dragover="dragover"
  >
    <div
      v-if="(!items||!items.length)&&!showonly"
      class="select-file-btn row items-center justify-center"
    >
      <q-icon name="cloud_upload" size="3em" color="grey-5"></q-icon>
      <div class="text-grey-7 q-pa-sm">{{title}}</div>
    </div>
    <div
      v-if="(!items||!items.length)&&!showonly"
      class="absolute select-file-btn column items-center justify-center"
    >
      <input
        ref="btn"
        name="file"
        type="file"
        style="opacity:0.01"
        class="fit absolute cursor-pointer"
        :multiple="more"
        @input="addItems($event.target.files)"
      />
    </div>

    <transition-group
      @before-enter="handleBeforeEnter"
      @enter="handleEnter"
      @after-enter="handleAfterEnter"
      appear
      :class="noWrap?'row no-wrap':''"
    >
      <div
        key="add"
        class="file-item add float-left relative-position row items-center justify-center"
        icon="add"
        v-if="items&&items.length&&more&&(!uploading || items.length>1)&&!showonly"
      >
        <q-icon name="add" size="2em"></q-icon>
        <input
          ref="btn"
          class="fit absolute cursor-pointer"
          name="file"
          type="file"
          style="opacity:0.01"
          :multiple="more"
          @input="addItems($event.target.files)"
        />
      </div>
      <div
        class="file-item float-left cursor-pointer"
        :ref="'item_'+index"
        v-for="(item,index) in items"
        :key="'item_'+index"
        :style="{backgroundImage:item.isImage?'url(\''+__genImgUrl(item.fileUrl)+'\')':''}"
        @click.stop="showFile($event,index)"
      >
        <div class="title text-white row items-center q-pa-xs content-center">
          <div class="ellipsis col" v-text="item.name"></div>
          <q-btn icon="clear" flat dense size="0.85em" v-if="!showonly" @click.stop="del(index)">
            <q-tooltip>删除</q-tooltip>
          </q-btn>
        </div>
        <div v-if="!item.isImage" class="content column items-center justify-center">
          <q-icon name="list_alt" size="2em" color="grey-5"></q-icon>
          <div v-text="'('+sizeShow(item.size) +') '+ item.extendName+' 文件'" class="text-grey-9"></div>
        </div>

        <q-btn
          class="upload-btn"
          icon="cloud_upload"
          dense
          color="primary"
          size="0.85em"
          v-if="item.$needUpload&&!showonly"
          @click.stop="upload(index)"
        >
          <q-tooltip>上传文件 {{item.$needUpload}}</q-tooltip>
        </q-btn>
        <!-- <kyb-progress :percent="item.$uploadNum" v-if="item.$showProgress"></kyb-progress> -->
      </div>
    </transition-group>
    <!-- 显示和编辑图片 -->
    <kyb-img
      :items="imgList"
      :select-index="selectIndex+''"
      v-if="showImgCon"
      :src-target="selectTarget"
      @close="closeFile"
    />
    <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="20px"
        :value="progressNum"
        size="98px"
        :thickness="0.1"
        color="teal"
        track-color="grey-3"
        class
      >{{ progressNum }}%</q-circular-progress>
    </div>
  </div>
</template>
<style lang="stylus">
.file-upload {
  // min-height: 120px;
}

.file-in {
  border: 2px dashed red;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.select-file-btn {
  width: 100px;
  height: 100px;
  border: 0;
  border-radius: 4px;
  text-align: center;
  transition: all 0.5s;
  border: 1px dashed $grey-7;
}

.select-file-btn:hover {
  border: 1px dashed $negative;
  background-color: rgba(0, 0, 0, 0.1);
}

.file-item.add {
  border: 1px dashed $grey-4;
  font-size: 1.5em;
  color: $grey-5;
}

.file-item {
  position: relative;
  border-radius: 4px;
  box-shadow: 0 0 5px $grey-5;
  width: 140px;
  height: 100px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  margin: 5px;
  transition: all 0.5s;
  border: 1px solid $grey-6;
}

.file-item:hover {
  border: 1px solid $grey-6;
  box-shadow: 0 0 5px $grey-6;
}

.file-item>.title {
  border-radius: 4px 4px 0 0;
  background-color: #000;
  opacity: 0.5;
  top: 0;
  left: 0;
  right: 0;
  height: 30px;
}

.file-item >.upload-btn {
  transition: all 0.5s;
  position: absolute;
  bottom: 0;
  right: 0;
  opacity: 0.7;
  border-radius: 5px 0 5px 0;
}

.file-item >.upload-btn:hover {
  opacity: 1;
}

.file-item>.content {
  top: 34px;
  left: 0;
  right: 0;
  bottom: 0;
  position: absolute;
  overflow: hidden;
}
</style>

<script>
import _ from 'underscore'
import Velocity from 'velocity-animate'
import uploadFile from './upload-file'
// import KTest from 'components/k-test'
import { dom } from 'quasar'
// eslint-disable-next-line no-unused-vars
const { css, height, width, offset } = dom

let d = {
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    more: { type: Boolean, default: false },
    showonly: { type: Boolean, default: false },
    title: { type: String, default: '拖拽 或 单击选择文件' },
    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)
  },
  computed: {
    imgList() {
      return this.items.filter(item => item.isImage)
    }
  },
  mounted() {},
  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)
          }
        }
      })
    },
    sizeShow(size) {
      let u = 0
      while (size > 1024) {
        size = size / 1024
        u++
      }
      let us = ['', 'k', 'M', 'G', 'T']
      return size ? size.toFixed(1) + us[u] : ''
    },
    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)
      })
      this.$refs.btn && (this.$refs.btn.value = '')
    },
    handleBeforeEnter(el) {
      el.style.opacity = 0
    },
    handleEnter(el, done) {
      Velocity(
        el,
        {
          opacity: 1
        },
        {
          duration: 300,
          complete: done
        }
      )
    },
    handleAfterEnter(el) {},
    dragleave(e) {
      this.fileIn = false
      // console.log('console', e)
      e.preventDefault()
    },
    dragenter(e) {
      this.fileIn = true
      // console.log('dragenter', e)
      e.preventDefault()
    },
    dragover(e) {
      // console.log('dragover', e)
      e.preventDefault()
    },
    async del(index) {
      // let item = this.items[index]
      this.items.splice(index, 1)
      this.$q.showNotifi('删除成功')
      this.$emit(
        'input',
        this.items
          .filter(item => !item.$needUpload)
          .map(item => item._id)
          .join(',')
      )
      // if (item && item.$needUpload) {
      //   this.items.splice(index, 1)
      //   this.$q.showNotifi('删除成功')
      // } else {
      //   await this.$axios.post('/file/FileItem/del', { _id: item._id })
      //   this.$emit(
      //     'input',
      //     this.items.filter(item => !item.$needUpload).map(item => item._id)
      //   )
      // }
    },
    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 }
      }
    },
    closeFile($event) {
      this.showImgCon = false
    },
    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()
        }
      )
    },
    pick() {
      this.$refs.btn.click()
    },
    reset() {
      this.items.splice(0, this.items.length)
    }
  }
}
export default d
</script>
