<template>
  <div class="upload-files" v-loading="uploading">
    <input
      ref="file"
      type="file"
      style="display: none"
      @change="onFileChanged" />
    <div v-if="imageMode" class="images">
      <el-image
        v-for="item in files"
        :key="item.path"
        class="upload-files-img"
        :src="setimgUrl(item.path, { w: 80 })" />
      <i
        v-if="!(max > 0) || (files && files.length) < max"
        class="upload-files-add-icon el-icon-plus"
        @click="$refs.file.click()" />
    </div>
    <template v-else>
      <ul class="files">
        <li
          v-for="(item, i) in files"
          :key="item.path"
          class="upload-files-file">
          <span
            class="filename"
            @click="downloadFile(item)"
            :title="`点击下载 ${item.path} 文件`">
            {{ filename(item.path) }}
          </span>
          <i class="file-remove el-icon-close" @click="removeFile(i)"></i>
        </li>
      </ul>
      <el-button
        v-if="!(max > 0) || (files && files.length) < max"
        type="primary"
        @click="$refs.file.click()">
        {{ text }}
      </el-button>
    </template>
  </div>
</template>
<script>
import { baseURL } from '@/common/api/axios.js'
import Axios from 'axios'
import _ from 'lodash'
export default {
  name: 'UploadFile',
  props: {
    value: {
      type: [Array, String, Object],
    },
    max: {
      type: Number,
    },
    imageMode: {
      type: Boolean,
    },
    url: {
      type: String,
      default: 'upload/podFileUpload',
    },
    getFilePath: {
      type: String,
      default: 'imagePath',
    },
    text: {
      type: String,
      default: '选择文件',
    },
  },
  data() {
    return {
      uploading: false,

      files: [],
    }
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        if (this._lastValue === this.value) {
          this.emitValue()
          return
        }
        const val = []
        if (!Array.isArray(this.value)) {
          if (this.value) {
            val.push(
              typeof this.value === 'string'
                ? { path: this.value }
                : { ...this.value }
            )
          }
        } else {
          this.value.forEach((e) => {
            val.push(typeof e === 'string' ? { path: e } : { ...e })
          })
        }
        this.files = val.filter((e) => !!e.path)
      },
    },
  },
  methods: {
    onFileChanged() {
      const files = this.$refs.file.files
      const file = files[0]
      this.$refs.file.value = ''
      this.uploadFile(file)
    },
    async uploadFile(file) {
      const formData = new FormData()
      formData.append('file', file)
      try {
        const res = await Axios({
          method: 'post',
          url: baseURL + 'api/' + this.url,
          data: formData,
          headers: {
            'content-type': 'multipart/form-data',
            'jwt-token': localStorage.getItem('token'),
          },
        })

        this.files.push({ path: _.get(res.data, this.getFilePath) })
        this.emitValue()
      } catch (e) {
        console.error(e)
        this.$message.error('文件上传失败')
      } finally {
        this.uploading = false
      }
    },
    downloadFile(item) {
      window.open(
        // TODO 确认文件下载地址
        this.setimgUrl(item.path)
      )
    },
    async removeFile(i) {
      try {
        await this.$confirm('确认删除当前文件？', {
          type: 'warning',
          title: '提示',
        })
      } catch {
        return
      }
      this.files.splice(i, 1)
      this.emitValue()
    },
    filename(path) {
      if (!path) return ''
      const i = path.lastIndexOf('/')
      if (i === -1) return path
      return path.substring(i + 1)
    },
    emitValue() {
      let v
      if (this.max === 1) {
        v = this.files[0] && this.files[0].path
      } else {
        v = this.files.map((e) => e.path)
      }
      this._lastValue = v
      this.$emit('input', v)
    },
  },
}
</script>
<style scoped>
.upload-files {
  cursor: pointer;
}

.upload-files-add-icon {
  width: 58px;
  height: 58px;
  display: flex;
  border: 1px solid #ddd;
  justify-content: center;
  align-items: center;
  border: 1px solid #ddd;
}

.upload-files-img {
  width: 58px;
  height: 58px;
  object-fit: contain;
  border: 1px solid #ddd;
  margin-right: 10px;
}

.images {
  display: flex;
}

.upload-files-file {
  width: 100%;
  display: flex;
  align-items: center;
}

.upload-files-file .filename {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}
</style>
