<template>
  <div>
    <div v-if="readonly" v-loading="loading" class="image-list" :style="readListStyle">
      <el-empty v-if="fileList.length === 0 && !hideEmpty" description="未上传照片" :image-size="80"
        style="padding: 5px;width: 100%;"></el-empty>
      <img v-for="(item, index) in fileList" :key="index" class="image-item" :style="readItemStyle" :src="item.url"
        @click="handlePreview(item)" />
    </div>
    <el-upload v-else v-loading="loading" :action="action" :headers="headers" name="file" accept="image" :limit="0"
      :data="{ fileId: bizId, businessUnits: businessUnits }" :disabled="!bizId" :before-upload="beforeUpload" multiple
      :file-list="fileList" :on-success="uploadSucess" list-type="picture-card" :on-preview="handlePreview"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <my-image-viewer ref="previewImage" v-model="fileList" :options="{
      edit: !readonly,
      check: !readonly,
      delete: !readonly,
    }"></my-image-viewer>
  </div>
</template>
<script>
// import { getAttachs, deleteFile as deleteAttach } from '@/api/system/file.js';
import {getAttachList,deleteFile as deleteAttach} from "@/api/common/file";

import { getToken } from '@/utils/auth'

export default {
  name: 'PictureUpload',
  props: {
    bizId: null,
    readonly: false,
    hideEmpty: false,
    readItemStyle: null,
    readListStyle: null,
    // 业务单元，用于同个业务下不同单元
    businessUnits: {
      type: String,
      default: '',
    },
  },
  watch: {
    bizId: {
      handler(val) {
        this.fileList = [];
        if (val) {
          this.getImages();
        }
      },
      immediate: true,
    }
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      previewUrl: null,
      fileList: [],
      loading: false,
    }
  },
  computed: {
    previewSrcList() {
      return this.fileList.map(v => v.url);
    }
  },
  methods: {
    getFullImageUrl(item) {
      return process.env.VUE_APP_BASE_API + item.attachFileUrl;
    },
    beforeUpload(file) {
      const isImg = file.type.indexOf('image/') !== -1;
      if (!isImg) {
        this.$message.warning('只能上传图片');
      }
      return isImg;
    },
    getImages() {
      if (!this.bizId) {
        return;
      }
      this.loading = true;
      getAttachList(this.bizId, { businessUnits: this.businessUnits }).then((res) => {
        this.loading = false;
        if (res.code !== 200) return;
        this.fileList = res.data.map(v => {
          return {
            ...v,
            url: this.getFullImageUrl(v),
            name: v.oldName,
          };
        });
        this.$emit('fetched', this.fileList);
      }).catch(e => {
        this.loading = false;
      });
    },
    uploadSucess(response, file, fileList) {
      if (response.success && response.data[0]) {
        this.fileList = fileList.map(v => {
          if (v.uid === file.uid) {
            return {
              ...v,
              ...response.data[0],
              url: this.getFullImageUrl(response.data[0]),
            };
          }
          return v;
        });
        this.$emit('fetched', this.fileList);
      } else {
        // this.msgError(response.msg);
      }
    },
    handleRemove(item) {
      this.fileList = this.fileList.filter(v => v.id !== item.id);
      this.$emit('fetched', this.fileList);
      if (!item.id) {
        return;
      }
      deleteAttach(item.id).then((res) => {

      }).catch(e => {
      });
    },
    handlePreview(item,) {
      const index = this.fileList.findIndex(val => val.id === item.id);
      this.$refs.previewImage.open(index);
      // this.previewUrl = item.url;
      // this.$nextTick(() => {
      //   this.$refs.previewImage.clickHandler();
      // })
    },
  }
}
</script>
<style lang="scss" scoped>
.image-list {
  display: flex;

  .image-item {
    width: 148px;
    height: 148px;
    border: 1px solid #C0CCDA;
    border-radius: 6px;
    margin-right: 8px;
    margin-bottom: 8px;
    overflow: hidden;
  }
}</style>
