<template>
  <div class="UploadFile-container">
    <el-upload
      :action="define.comUploadUrl"
      :headers="uploadHeaders"
      :on-success="handleSuccess"
      :multiple="limit !== 1"
      :show-file-list="false"
      :accept="accept"
      :before-upload="beforeUpload"
      :on-exceed="handleExceed"
      :disabled="disabled"
      :limit="limit"
    >
      <el-button size="small" icon="el-icon-upload" :disabled="disabled">{{ buttonText }}</el-button>
      <div slot="tip" class="el-upload__tip" v-show="showTip">只能上传不超过{{ fileSize }}{{ sizeUnit }}的{{ accept }}文件</div>
    </el-upload>
    <template v-if="allFileList.length">
      <transition-group class="el-upload-list el-upload-list el-upload-list--text" tag="ul" name="el-list">
        <li class="el-upload-list__item is-success" v-for="(file, index) in allFileList" :key="file.id">
          <a class="el-upload-list__item-name" @click="handleClick(file)"> <i class="el-icon-document"></i>{{ file.fileName }} </a>
          <i class="el-icon-edit-outline" style="display: block;position: absolute;right: 25px;top:1px;line-height: inherit;cursor: pointer" @click="handleUpdate(file, index)"></i>
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-circle-check"></i>
          </label>
          <i class="el-icon-close" v-if="!disabled" @click="handleRemove(file, index)"></i>
        </li>
      </transition-group>
    </template>
    <el-dialog title="文件名称修改" :visible.sync="updateDialogVisible" width="300px" append-to-body>
      <el-form ref="updateForm" :model="updateForm" label-width="80px">
        <el-form-item label="文件名称">
          <el-input v-model="updateForm.fileName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateFileName">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {delBySerialNumber, getBySerialNumber, getFileById, updateFileName} from '@/api/common'
const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024
}
import { getDownloadUrl } from '@/api/common'
export default {
  name: 'UploadFile',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'annex'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 0
    },
    accept: {
      type: String,
      default: '*'
    },
    buttonText: {
      type: String,
      default: '选择文件'
    },
    sizeUnit: {
      type: String,
      default: 'MB'
    },
    fileSize: {
      default: 2
    }
  },
  data() {
    return {
      fileList: [],
      uploadHeaders: { 'Blade-Auth': 'bearer ' + getToken() },
      allFileList: [],
      updateDialogVisible: false,
      updateForm:{
        id: '',
        fileName: '',
      }
    }
  },
  mounted() {
    if(!this.value) return;
    getFileById(this.value).then((res) => {
      this.allFileList = Object.values(res.data.data)
    })
  },
  watch: {
    value: {
      handler(val) {
        let value = []
        try {
          value = val.map((o) =>{return o.id ?  o.id : o})
        }catch (e) {
          value = val
        }
        getFileById(value).then((res) => {
          this.allFileList = Object.values(res.data.data)
        })
      },
      deep: true
    }
  },
  methods: {
    beforeUpload(file) {
      const unitNum = units[this.sizeUnit]
      if (!this.fileSize) return true
      let isRightSize = file.size / unitNum < this.fileSize
      if (!isRightSize) {
        this.$message.error(`文件大小超过${this.fileSize}${this.sizeUnit}`)
      }
      // let isAccept = new RegExp(this.accept).test(file.type)
      // if (!isAccept) {
      //   this.$message.error(`应该选择${this.accept}类型的文件`)
      // }
      return isRightSize
    },
    handleSuccess(res, file, fileList) {
      // 如果数组类型
      if (res.code == 200) {
        this.fileList.push({
          name: res.data.fileName,
          fileId: res.data.id,
          url: res.data.filePath,
          ...res.data
        })
        this.$emit('input', this.fileList)
        this.$emit('change', this.fileList)
      } else {
        // fileList.filter((o) => o.uid != file.uid)
        // this.$emit('input', this.fileList)
        this.$message({ message: '上传失败', type: 'error', duration: 1500 })
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传${this.limit}个文件`)
    },
    handleRemove(file, index) {
      this.fileList.splice(index, 1)
      this.$emit('input', this.fileList)
      // this.$confirm(`确定移除${file.name}？`, '提示').then(() => {
      // }).catch(() => { })
    },
    handleClick(file) {
      // 点击下载文件
      if (!file.filePath) return
      let ImgUrl = ''
      if (process.env.NODE_ENV === 'development') {
        ImgUrl = this.define.comUrl
      } else {
        ImgUrl = document.location.origin
      }
      window.open(ImgUrl + '/' + file.filePath)
      // getDownloadUrl(this.type, file.fileId).then((res) => {
      //   if (res.data.url) window.location.href = this.define.comUrl + res.data.url
      // })
    },
    handleUpdate(file,index){
      this.updateForm = {
        id: '',
        fileName: ''
      }
      this.updateDialogVisible = true
      this.$nextTick(() => {
        this.updateForm.id = file.id
        this.updateForm.fileName = file.fileName
      })
    },
    updateFileName(){
      let params = {
        id: this.updateForm.id,
        fileName: this.updateForm.fileName
      }
      updateFileName(params).then(res => {
        if ( res.data.code === 200 ) {
          this.$message({ message: res.data.msg, type: 'success', duration: 1500 })
          getFileById(this.value.map((o) => o.id)).then((res) => {
            this.allFileList = Object.values(res.data.data)
          })
          this.updateDialogVisible = false
        }
      })
    },
  }
}
</script>
