<template>
  <div class="banner-image" :style="{width: width}">
    <el-carousel v-loading="loading" ref="carousel" :height="height" arrow="never" class="banner-carousel" indicator-position="none"
      @change="carouselChange">
      <el-carousel-item v-for="item in imageDatas" :key="item.attachId">
        <div class="banner-carousel-item">
          <el-image style="width:100%;height:100%" :src="getFullImageUrl(item)" fit="fill"
            @click="handlePreview(item)"></el-image>
          <el-button class="banner-delete" type="danger" size="mini" icon="el-icon-delete" circle v-if="!readonly"
            @click.stop="handleRemove(item)"></el-button>
        </div>
      </el-carousel-item>
    </el-carousel>
    <el-pagination layout="prev, pager, next" hide-on-single-page small :current-page="currentPage" :page-size="1"
      :total="imageDatas.length" @current-change="currentPageChange">
    </el-pagination>
    <el-upload style="margin-top: 10px;" v-if="imageDatas.length < maxLength && !readonly" :action="action"  :headers="headers" name="file" accept="image"
      :data="{ fileId: bannerId, businessUnits: businessUnits }" :disabled="!bannerId" :before-upload="beforeUpload" multiple :limit="limit"
      :show-file-list="false" :file-list="fileList" :on-success="uploadSucess">
      <el-button size="small" type="primary">添加照片</el-button>
    </el-upload>
    <my-image-viewer ref="previewImage" v-model="imageDatas" :options="{
      edit: !readonly,
      check: !readonly,
      delete: !readonly,
    }"></my-image-viewer>
  </div>
</template>

<script>
import {getAttachList,deleteFile as deleteAttach} from "@/api/common/file";
// import { getAttachs, deleteFile as deleteAttach } from '@/api/system/file.js';
import { getToken } from '@/utils/auth'

export default {
  name: 'BannerUpload',
  props: {
    bannerId: null,
    readonly: {
      type: Boolean,
      default: false
    },
    // 业务单元，用于同个业务下不同单元
    businessUnits: {
      type: String,
      default: '',
    },
    // 限制9张图
    maxLength: {
      type: Number,
      default: 9,
    },
    height: {
      type: String,
      default: '210px',
    },
    width: {
      type: String,
      default: '200px',
    }
  },
  computed: {
    limit() {
      if (this.imageDatas) {
        return Math.max(0, this.maxLength - this.imageDatas.length);
      }
      return this.maxLength;
    }
  },
  watch: {
    bannerId: {
      handler(val) {
        this.imageDatas = [];
        if (val) {
          this.getImages();
        }
      },
      immediate: true,
    }
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + getToken(),
      },
      imageDatas: [],
      currentPage: 1,
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      loading: false,
    }
  },
  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('只能上传图片');
      }
      this.loading = true;
      return isImg;
    },
    getImages() {
      if (!this.bannerId) {
        return;
      }
      this.loading = true;
      getAttachList(this.bannerId).then((res) => {
        this.loading = false;
        this.imageDatas = res.data || [];
      }).catch(e => {
        this.loading = false;
      });
    },
    uploadSucess(response, file, fileList) {
      this.fileList = [];
      this.loading = false;
      this.getImages();
    },
    handleRemove(item) {
      this.$confirm('是否确认删除当前照片', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.loading = true;
        deleteAttach(item.id).then((res) => {
          this.loading = false;
          this.getImages();
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    handlePreview(item) {
      // this.dialogImageUrl = this.getFullImageUrl(item);
      // this.dialogVisible = true;
      const index = this.imageDatas.findIndex(val => val.attachId === item.attachId);
      this.$refs.previewImage.open(index);
    },
    carouselChange(page) {
      this.currentPage = page + 1;
    },
    currentPageChange(page) {
      if (this.$refs.carousel) {
        this.$refs.carousel.setActiveItem(page - 1);
      }
    }
  }
}
</script>

<style scoped>
.banner-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0px 0px 20px 20px;
}

.banner-carousel {
  background-color: #f3f3f3;
  border-color: gray;
  border-radius: 4px;
  border-width: 2px;
  width: 100%;
}

.banner-delete {
  position: absolute;
  top: 2px;
  right: 2px;
  /* font-size: 20px; */
  display: none;
  /* background-color: #f3f3f3; */
}


.banner-carousel-item {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f3f3f3;
  border-color: gray;
  border-radius: 4px;
  border-width: 2px;
}

.banner-carousel-item:hover .banner-delete {
  display: block;
}
</style>
