<template>
  <div>
    <el-upload
      v-bind="$attrs"
      :action="action"
      :headers="headers"
      accept=".gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG,.pdf,.PDF,.docx,.doc"
      :list-type="listType"
      :before-upload="handleBeforeUpload"
      :auto-upload="autoUpload"
      class="avatar-uploader"
      :class="{disabled: uploadDisabled && !isUploadList}"
      :on-success="success"
      :on-error="error"
      :on-progress="progress"
      :file-list="fileList"
    >
      <i slot="default" class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="file" slot-scope="{file}" class="avatar">
        <!-- 上传时url没有后缀名，使用上传成功后的数据判断展示 -->
        <template v-if="file.response">
          <img
            v-if="
              file.response.value.suffix == 'jpg' ||
                file.response.value.suffix == 'JPG' ||
                file.response.value.suffix == 'jpeg' ||
                file.response.value.suffix == 'JPEG' ||
                file.response.value.suffix == 'png' ||
                file.response.value.suffix == 'PNG' ||
                file.response.value.suffix == 'bmp' ||
                file.response.value.suffix == 'BMP' ||
                file.response.value.suffix == 'gif' ||
                file.response.value.suffix == 'GIF'
            "
            class="el-upload-list__item-thumbnail avatar"
            :src="file.url"
            alt=""
          />
          <img
            v-else-if="
              file.response.value.suffix == 'pdf' ||
                file.response.value.suffix == 'PDF'
            "
            class="el-upload-list__item-thumbnail"
            src="../../assets/img/defaultPdf.jpg"
            alt=""
          />
          <img
            v-else-if="
              file.response.value.suffix == 'docx' ||
                file.response.value.suffix == 'doc'
            "
            class="el-upload-list__item-thumbnail"
            src="../../assets/img/defultWord.jpg"
            alt=""
          />
        </template>
        <!-- 否则就使用后台返回的数据 -->
        <template v-else>
          <img
            v-if="
              getImgUrlType(file.url) == 'jpg' ||
                getImgUrlType(file.url) == 'JPG' ||
                getImgUrlType(file.url) == 'jpeg' ||
                getImgUrlType(file.url) == 'JPEG' ||
                getImgUrlType(file.url) == 'png' ||
                getImgUrlType(file.url) == 'PNG' ||
                getImgUrlType(file.url) == 'bmp' ||
                getImgUrlType(file.url) == 'BMP' ||
                getImgUrlType(file.url) == 'gif' ||
                getImgUrlType(file.url) == 'GIF'
            "
            class="el-upload-list__item-thumbnail avatar"
            :src="file.url"
            alt=""
          />
          <img
            v-else-if="
              getImgUrlType(file.url) == 'pdf' ||
                getImgUrlType(file.url) == 'PDF'
            "
            class="el-upload-list__item-thumbnail"
            src="../../assets/img/defaultPdf.jpg"
            alt=""
          />
          <img
            v-else-if="
              getImgUrlType(file.url) == 'docx' ||
                getImgUrlType(file.url) == 'doc'
            "
            class="el-upload-list__item-thumbnail"
            src="../../assets/img/defultWord.jpg"
            alt=""
          />
          <p v-else>无法显示</p>
        </template>
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="pictureCardPreview(file)"
          >
            <a target="_blank" :href="file.url">预览</a>
            <!-- <i class="el-icon-zoom-in"></i> -->
          </span>
          <span @click="remove(file)">
            <!-- <i class="el-icon-delete"></i> -->
            <span v-if="disabled == true ? false : true">删除</span>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'
// import pdf from 'vue-pdf'
import ret from 'bluebird/js/release/util'
export default {
  name: 'upload',
  // components: {pdf},
  props: {
    listType: {
      type: String,
      default: 'picture-card'
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    isUploadList: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    /* 回传后的数据 */
    imgUrl: {
      type: [Array, String],
      default: () => [] || ''
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      // fileList: [], //  文件上传列表
      imgUrl_: this.imgUrl,
      upLoadImgUrl: '',
      form: {
        position: ''
      },
      fileArr: [],
      pdfUrl: '',
      wordUrl: ''
    }
  },
  created() {},
  watch: {
    /*
     *这里使用watch监听imgUrl出现bug，第一种情况首次加载监听不到值，第二种是监听到的值是默认值
     *之后采用计算属性来计算改值变化
     */
    // imgUrl: {
    //   handler(newVal) {
    //     console.log(newVal, '新的值')
    //     if (newVal && typeof newVal == 'string') {
    //       this.fileList = [{url: newVal}]
    //     } else {
    //       this.fileList = newVal || []
    //     }
    //   },
    //   deep: true
    //   // immediate: true
    // }
    /*
     *这里监听传递值imgurl，以解决附件缓存问题
     */
    // imgUrl(newVal) {
    //   if (newVal && typeof newVal == 'string') {
    //     this.fileList = []
    //   } else {
    //     this.fileList = []
    //   }
    // }
  },
  computed: {
    ...mapState({
      headers: state => {
        return {Authorization: `Bearer ${state.login.currentUser.token}`}
      },
      action: function() {
        return window.context.portal + '/biz/universal/v1/minioUpload'
      },
      uploadDisabled: function() {
        return this.fileList && this.fileList.length > 0
      }
      /*
       *这样使用会出现无法写入值
       */
      // fileList: function() {
      //   let list = []
      //   if (this.imgUrl && typeof this.imgUrl == 'string') {
      //     list = [{url: this.imgUrl}]
      //   } else {
      //     list = this.imgUrl || []
      //   }
      //   return list
      // }
    }),
    fileList: {
      get() {
        let list = []
        if (this.imgUrl_ && typeof this.imgUrl_ == 'string') {
          list = [{url: this.imgUrl_}]
        } else {
          list = this.imgUrl_ || []
        }
        return list
      },
      set(list) {
        this.imgUrl_ = list
      }
    }
  },
  mounted() {
    // this.fileList = []
    /* 
      *这是使用的是页面加载完成后获取imgUrl的值变化，但是会触发重排和回流，可能导致页面会出现闪一下，
      影响用户使用，这里就不在使用
     */
    // if (this.imgUrl && typeof this.imgUrl == 'string') {
    //   this.fileList = [{url: this.imgUrl}]
    // } else {
    //   this.fileList = this.imgUrl || []
    // }
  },
  methods: {
    getImgUrlType(url) {
      if (typeof url === 'undefined') return
      let file = url.split('/')
      let fileName = file[file.length - 1]
      let type = fileName.split('.')[1]
      return type
    },
    handleBeforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = [
        'pdf',
        'jpg',
        'jpeg',
        'png',
        'JPG',
        'PNG',
        'JPEG',
        'PDF',
        'docx',
        'doc'
      ]
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message.warning(
          '上传文件只能是 pdf、jpg、jpeg、png,docx,doc等格式'
        )
        return false
      }
    },
    remove(file) {
      let INdex = this.fileList.findIndex(item => {
        if (item.id) {
          return item.id == file.id
        } else {
          return item.uid == file.uid
        }
      })
      if (this.isUploadList) {
        this.fileList.splice(INdex, 1)
        this.$emit('upload', this.fileList)
      } else {
        this.fileList = []
        this.$emit('upload', undefined)
      }
    },
    pictureCardPreview(file) {
      console.log(file, 'jjjjjjjjjjjjjj')
      if (file.response.value.suffix == 'pdf' || file.response.value.suffix == 'PDF') {
        this.pdfUrl = this.getPdfUrl(file)
        this.dialogImageUrl = require('../../assets/img/defaultPdf.jpg')
      } else if (file.response.value.suffix == 'docx' || file.response.value.suffix == 'doc') {
        this.wordUrl = this.getWordUrl(file)
        this.dialogImageUrl = require('../../assets/img/defultWord.jpg')
      } else {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    },
    success(response, file, fileList) {
      this.fileList = fileList
      if (this.isUploadList) {
        this.$emit('upload', this.fileList)
      } else {
        this.$emit('upload', response)
      }
    },
    error(err, file, fileList) {
      console.log(err, file, fileList, '上传失败')
    },
    progress(event, file, fileList) {
      console.log(event, file, fileList, '正在上传')
    },
    //处理pdf
    getPdfUrl(file) {
      // let url = window.URL.createObjectURL(file.raw) //将文件转化成url
      //加载pdf
      window.open(file.url, '_blank')
    },
    getWordUrl(file) {
      // window.open(file.url, '_blank')
    }
  },
  beforeDestroy() {
    console.log('附件销毁')
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon,
/deep/ .el-upload--picture-card {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar,
/deep/ .el-upload-list__item {
  width: 128px;
  height: 128px;
}
.avatar {
  display: flex;
  justify-content: center;
  align-items: center;
}

.disabled /deep/ .el-upload--picture-card {
  display: none;
}
// 去除upload自带组件过度效果
/deep/ .el-upload-list__item {
  transition: none !important;
}
a {
  color: #eeeeee;
}
</style>
