<template>
  <div class="upload">
    <el-upload
      ref="upload"
      :list-type="config.type==='image' ? 'picture-card' : 'text'"
      :class="showUploadButton ? 'uploader' : 'uploader hidden'"
      :action="uploadUrl"
      :data="config.data"
      :name="config.name"
      :disabled="config.isReadonly"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :multiple="config.multiple"
      :show-file-list="false"
      size="mini"
      :with-credentials="true">
      <i v-if="config.type ==='image'" class="el-icon-plus"></i>
      <el-button v-else-if="config.type ==='icon'" type="text" icon="el-icon-upload2" />
      <el-button v-else :type="btnType" :size="size" @click="btnClick">
        {{ config.buttonText }}
        <i :class="btnIcon" v-if="btnType === 'text'"></i>
        <i class="el-icon-upload el-icon--right" v-else></i>
      </el-button>
    </el-upload>
    <el-dialog :close-on-click-modal="false" class="imageDialog" v-if="config.type==='image'" :visible.sync="dialogVisible" append-to-body top="5vh">
      <div class="preview">
        <img class="img" :src="imageUrl">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'

const defaultOptions = {
  name: 'file',
  url: `${process.env.VUE_APP_HOST_URL}${process.env.VUE_APP_BASE_URL}/soa/resource/upload`,
  fileSize: 60,
  limit: 1,
  buttonText: '上传',
  fileList: [],
  isReadonly: false,
  multiple: false
}
const { mapGetters, mapMutations } = createNamespacedHelpers('app')

export default {
  name: 'Upload',

  props: {
    options: {
      type: Object,
      default() {
        return {}
      }
    },
    fileList: {
      type: Array,
      default() {
        return []
      }
    },

    beforeRemove: {
      type: Function
    },

    size: {
      type: String,
      default: 'mini'
    },

    btnType: {
      type: String,
      default: 'primary'
    },

    btnIcon: {
      type: String,
      default: ''
    },

    fileType: {
      type: String,
      default: 'wsdl'
    }
  },

  computed: {
    ...mapGetters(['projectID', 'projectName']),
    imageStyle() {
      const { width, height } = this.config
      return {
        width: `${width}px`,
        height: `${height}px`,
        lineHeight: `${height}px`
      }
    }
  },
  created() {
    this.setProjectID(localStorage.getItem('projectID'))
    this.setProjectName(localStorage.getItem('projectName'))
  },
  watch: {
    fileList: {
      handler(fileList) { // 监听fileList 有可能异步
        const fileNum = fileList.length
        const { limit } = this.config
        this.showUploadButton = fileNum < limit
        this.fileList = fileList
      },
      immediate: true
    }
  },

  data() {
    return {
      imageUrl: '',
      dialogVisible: false,
      showUploadButton: true,
      config: {
        ...defaultOptions,
        ...this.options,
        data: {
          name: ''
        }
      },
      uploadUrl: '',
      oneimageUrl: '' // 单个图片上传
    }
  },

  methods: {
    ...mapMutations(['setProjectID', 'setProjectName']),
    beforeUpload(file) { // 上传前检测
      // const { fileSize, type } = this.config
      // const isImage = type === 'image' ? file.type.indexOf(type) !== -1 : true
      // const isLtLimit = file.size / 1024 / 1024 < fileSize
      // let isRepeat = true
      this.$set(this.config.data, 'name', file.name)
      let name
      const index = this.config.data.name.indexOf('.')
      if (index >= 0) {
        name = this.config.data.name.substring(0, index)
      } else {
        name = this.config.data.name
      }
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          this.uploadUrl = `${this.config.url}/${this.projectID}/${this.fileType}/${name}`
          resolve()
        })
      })
      // this.$set(this.config, 'url', `${this.config.url}/${file.name}`)
      // this.$nextTick(() => {
      //   this.$set(this.config, 'url', `${this.config.url}/${file.name}`)
      // })
      // this.fileList.forEach(element => {
      //   if (file.name === element.name) {
      //     isRepeat = false
      //   }
      // })
      // else if (!isLtLimit) {
      //   this.$message.error(`图片大小不能超过 ${fileSize}MB!`)
      // }
      // if (!isImage) {
      //   this.$message.error('只能上传图片!')
      // } else if (!isRepeat) {
      //   this.$message.error('不能重复上传!')
      // }
      // eslint-disable-next-line no-unreachable
      if (this.config.limit === 1) {
        this.showUploadButton = false
      }
      // return isImage && isLtLimit && isRepeat
    },
    handleSuccess(res, file, fileList) { // 上传成功
      const fileNum = fileList.length
      const { limit } = this.config
      if (fileNum === limit) {
        this.showUploadButton = false
      }
      if (res) {
        file.id = res.id
        file.downloadUrl = res.downloadUrl
        file.viewUrl = res.viewUrl
        this.$emit('on-success', file, fileList)
        this.$emit('update:fileList', fileList)
      }
    },

    handleError(res) { // 上传失败
      const result = JSON.parse(res.message)
      if (result.message === 'File is duplicated!') {
        this.$message({
          message: '文件名重复！',
          type: 'error'
        })
      } else if (result.message === 'File type is not matched!') {
        this.$message({
          message: '文件类型不匹配！',
          type: 'error'
        })
      } else if (result.message === 'Invalid file type!') {
        this.$message({
          message: '文件类型无效！',
          type: 'error'
        })
      } else {
        this.$message({
          message: result.message,
          type: 'error'
        })
      }
      this.$emit('on-error', res)
    },

    handleRemove(file, fileList) {
      const fileNum = fileList.length
      const { limit } = this.config
      if (fileNum < limit) {
        this.showUploadButton = true
      }
      this.$emit('on-success', file, fileList)
      this.$emit('update:fileList', fileList)
    },

    handlePreview(file) {
      this.imageUrl = file.url
      this.dialogVisible = true
    },

    btnClick() {
      this.$emit('btnClick')
    }
  },

  mounted() {
  }
}
</script>
<style type="text/scss" lang="scss">
  .hidden {
    .el-upload {
      display: none;
    }
  }

  .imageDialog {
    .el-dialog__header {
      border-bottom: none;
    }
  }

  .uploader {
    display: flex;

    .el-upload-list--text {
      /*display: flex;*/
      width: 100%;
      flex: 1;

      .el-upload-list__item:first-child {
        margin-top: 5px;
      }
    }

    .el-upload-list.is-disabled + .el-upload--picture-card {
      display: none;
    }
  }

  .preview {
    height: 72vh;
    text-align: center;

    .img {
      height: 72vh;
      max-width: 100%;
    }
  }
</style>
