<!-- 预授信申述 -->
<template>
  <div>
    <el-upload
      :class="{ hidden: limitHidden }"
      :file-list="fileList"
      :list-type="listType"
      :multiple="multiple"
      :limit="limit"
      :show-file-list="showFileList"
      action="#"
      :accept='accept'
      :before-upload="handleBeforeUpload"
      :http-request='(params) => handleUpload(params)'
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
    >
      <i v-if="listType === 'picture-card'" slot="default" class="el-icon-plus"></i>
      <el-button v-else size="small" icon="el-icon-upload" type="primary">点击上传</el-button>
      <div slot="file" slot-scope="{ file }">
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.url" :alt="file.name"
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <div slot="tip" class="el-upload__tip">{{ tip }}</div>
    </el-upload>
    <file-list-item v-if="!showFileList" :file-list="fileList" :disabled="disabled" @preview="handlePreview" @download="handleDownload" @delete="handleRemove"></file-list-item>
    <el-image-viewer v-if="imgViewerVisible" :url-list="urlList" :on-close="handleClose"></el-image-viewer>
  </div>
</template>

<script>
import _ from 'lodash'
import ListItem from './ListItem'
import useOSS from '@/utils/useOSS'
const { uploadFile } = useOSS()

export default {
  name: 'MUpload',
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer'),
    'file-list-item': ListItem,
  },
  props: {
    /**
     * 上传文件列表 value.sync 绑定
     * @type {Array}
     */
    value: {
      type: [String, Array],
      require: true,
      default: () => []
    },
    /**
     * 上传文件列表类型
     * @type {String} text/picture-card
     */
    listType: {
      type: String,
      require: false,
      default: 'text'
    },
    multiple: {
      type: Boolean,
      require: false,
      default: false
    },
    /**
     * 是否显示文件列表 - TODO listType 为 picture-card 时显示 showFileList 需设置为 true
     * @type {Boolean}
     * @default false
     */
    showFileList: {
      type: Boolean,
      require: false,
      default: false
    },
    /**
     * 上传文件类型
     * @type {String}
     */
    accept: {
      type: String,
      require: false,
      default: '.jpeg, .jpg, .png, .bmp, .gif'
    },
    limit: {
      type: Number,
      require: false
    },
    /**
     * 上传文件路径
     * @type {String} YDT-CRM-FRONT
     */
    path: {
      type: String,
      require: false
    },
    /**
     * 上传提示
     * @type {String}
     */
    tip: {
      type: String,
      require: false
    },
    /**
     * 是否禁用
     * @type {Boolean}
     * @default false
     */
    disabled: {
      type: Boolean,
      require: false,
      default: false
    },
  },
  data() {
    return {
      // 上传文件列表
      fileList: [],
      imgViewerVisible: false,
      urlList: [],
    }
  },
  computed: {
    limitHidden() {
      return this.limit && this.fileList.length >= this.limit
    }
  },
  watch: {
    value(newVal) {
      if (newVal) {
        const newList = _.compact(newVal)
        this.fileList = Array.isArray(newList) ? newList.map(item => ({ name: item.name, url: item.url })) : []
      } else {
        this.fileList = []
      }
    }
  },
  methods: {
    handlePreview(file) {
      if(this.listType === 'picture-card') {
        this.urlList = [file.url]
        this.imgViewerVisible = true
      } else {
        window.open(file.url)
      }
    },
    handleDownload(file) {
      window.open(file.url)
    },
    handleClose() {
      this.imgViewerVisible = false
      this.urlList = []
    },
    // 上传前
    handleBeforeUpload(file) {
      const type = file.type
      return true
    },

    // 上传
    async handleUpload(file) {
      try {
        const res = await uploadFile(file.file, this.path)
        this.$notify({
          title: '成功',
          message: `${file.file.name} 上传成功`,
          type: 'success',
          duration: 2000
        });
        if (this.limit === 1) {
          this.fileList = [...res]
        } else {
          this.fileList.push(...res)
        }
        this.updateValue(this.fileList)
      } catch (err) {
        console.log(err)
      }
    },

    updateValue(fileList) {
      this.$emit('update:value', fileList);
      this.$emit('change', fileList)
    },
    // 上传成功
    handleSuccess(res, file) {
      this.$notify({ title: '成功', message: file.name + ",上传成功", type: 'success' });
    },

    // 删除
    handleRemove(file) {
      this.$confirm(`是否删除 <a target="_blank">${file.name}</a> ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }).then(() => {
        const cacheFileList = _.cloneDeep(this.fileList)
        this.fileList = cacheFileList.filter(item => {
          if (item.url !== file.url) {
            return item
          }
        })
        this.updateValue(this.fileList)
      })
    },

    // 超出限制
    handleExceed() {
      this.$notify({
        title: '提示',
        message: `当前限制上传最多 ${this.limit} 个文件`,
        type: 'warning',
        duration: 2000
      });
    },
  }
}
</script>
<style lang='less' scoped>

.hidden {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }

    .el-upload__tip {
      line-height: normal;
      margin-top: 0;
    }
  }
}

</style>
