<template>
  <div :class="['file-box', isShowImg || fileObj[imgType] ? 'show-img' : '']">
    <div v-loading="imgLoading" class="img-box" element-loading-background="rgba(0, 0, 0, .7)"
         element-loading-spinner="el-icon-loading">
      <el-image :preview-src-list="srcList" :src="previewUrl + fileObj[imgType]" fit="fill" @error="imgLoad"
                @load="imgLoad">
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline" />
        </div>
      </el-image>
      <div v-if="fileObj[imgType]" class="action-overlay">
        <i class="el-icon-view" title="点击预览" @click="clickView(imgType)"></i>
        <i class="el-icon-delete" title="点击删除" @click="clickRemove(imgType)"></i>
      </div>
    </div>
    <div class="file-upload">
      <el-upload ref="upload" :accept="accept" :action="actionUrl + '/file/v1/fileUpload'" :before-upload="beforeUpload"
                 :data="{ file: JSON.stringify({ storeType: 'minio' }) }"
                 :headers="headers" :limit="1" :on-error="handleError" :on-success="handleSuccess"
                 :show-file-list="false" list-type="picture-card" name="files">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
      </el-upload>
    </div>
    <!-- 图片预览组件 -->
    <el-image-viewer v-if="isViewShow" :on-close="closeView" :url-list="srcList" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import {mapState} from 'vuex'
import {deleteFileById} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueVehicleMgmt'

export default {
  name: 'imgDialog',
  components: {
    ElImageViewer
  },
  props: {
    imgType: {
      type: String,
      default: ''
    },
    imgId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      accept: '.png, .jpg, .jpeg',
      srcList: [],
      fileObj: {
        drivingLicenseF: '',
        drivingLicenseB: '',
        carFrontUrl: '', //车辆正面照片
        carSideUrl: '', //车辆侧面照
        carBehindUrl: '' //车辆后面照
      },
      isViewShow: false,
      imgLoading: false,
      isShowImg: false
    }
  },
  watch: {
    imgId: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          this.imgLoading = true
          this.fileObj[this.imgType] = newVal
        })
      }
    }
  },
  computed: {
    actionUrl: _ => window.context.portal,
    previewUrl: _ => window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
    ...mapState({
      headers: (state) => ({Authorization: `Bearer ${state.login.currentUser.token}`})
    })
  },
  created() {
  },
  methods: {
    beforeUpload(file) {
      const {size} = file
      const maxSize = 5 * 1024 * 1024 // 20MB
      if (size > maxSize) {
        this.$message.warning('附件大小不能超过5MB')
        setTimeout(_ => this.saveLoading = false, 0)
        return false
      } else {
        this.isShowImg = true
        this.imgLoading = true
        // 动态设置 data 参数
        this.$refs.upload.data = {fileUpload: 'minio', otherParam: 'value'}
      }
    },
    handleSuccess(response) {
      const {fileId: id} = response
      this.fileObj[this.imgType] = id
      this.$emit('updateFile', id, this.imgType)
    },
    // 文件上传失败
    handleError() {
      this.isShowImg = false
      this.imgLoading = false
      this.$message.warning('图片上传失败')
    },
    imgLoad() {
      this.imgLoading = false
    },
    //点击预览
    clickView(type) {
      let url = this.previewUrl + this.fileObj[type]
      this.srcList = [url]
      this.isViewShow = true
    },
    closeView() {
      this.srcList = []
      this.isViewShow = false
    },
    // 图片删除
    clickRemove(type) {
      this.$confirm('确定删除后重新上传吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.imgLoading = true
          deleteFileById(this.fileObj[type]).then(res => {
            if (res.state) {
              this.fileObj[type] = ''
              this.srcList = []
              this.$message.success('图片删除成功，请重新上传')
              this.$emit('updateFile', '', type)
              this.isShowImg = false
              this.$refs.upload?.clearFiles()
            } else {
              this.$message.error('删除失败')
            }
            this.imgLoading = false
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

.file-box {
  position: relative;
  width: fit-content;
  border-radius: 5px;

  .file-upload {
    position: absolute;
    left: 0;
    top: 0;
    width: fit-content;
    opacity: 1;
    z-index: 1;
    border-radius: 5px;
    transition: all .3s;

    ::v-deep.el-upload {
      width: 240px;
      height: 150px;
      border-radius: 5px;
      border: 1px dashed #43a1ff !important;

      i {
        font-size: 24px;

        &::before {
          font-size: 20px;
          color: #43a1ff;
        }
      }

      * {
        border-radius: 5px !important;
      }
    }
  }

  .img-box {
    position: relative;
    // left: 0;
    // top: 0;
    width: 240px;
    height: 150px;
    box-sizing: border-box;
    border-radius: 5px;
    opacity: 0;
    z-index: 0;
    transition: all .3s;

    ::v-deep.el-image {
      width: 100%;
      height: 100%;
      border-radius: 5px;

      * {
        background: transparent;
        box-sizing: border-box;
        border-radius: 5px;
      }
    }

    ::v-deep.el-loading-mask {
      border-radius: 5px;
    }

    ::v-deep.image-slot {
      width: 100%;
      height: 100%;
      line-height: 150px;
      text-align: center;
      border: 1px #43a1ff dashed;
      background: transparent;
      box-sizing: border-box;
      border-radius: 5px;

      i {
        font-size: 20px;
        color: #43a1ff;
      }
    }

    .action-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      line-height: 150px;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background: rgba(0, 0, 0, .5);
      transition: opacity .3s;

      &:hover {
        opacity: 1;
        transition: opacity .3s;
      }

      i {
        cursor: pointer;
        width: 30px;
        height: 40px;
        font-size: 20px !important;
        line-height: 40px;

        &:last-child {
          margin-left: 20px;
        }
      }
    }
  }
}

.show-img {
  .file-upload {
    opacity: 0;
    z-index: 0;
    transition: all .3s;
  }

  .img-box {
    opacity: 1;
    z-index: 1;
    transition: all .3s;
  }
}
</style>
