<template>
  <div class="image-chooser" v-loading="loading">
    <div v-for="(item, i) in list" :key="item.id" class="image-item">
      <img :src="imageUrl(item)" />
      <i v-if="!readonly" class="el-icon-circle-close" @click.stop="removeImage(item, i)"></i>
    </div>
    <div class="image-item" v-loading="uploading" v-if="!readonly">
      <el-popover
        v-model="bubVisible"
        placement="top"
        trigger="click">
        <el-button type="primary" size="small" @click="goChooseImage" plain>选择系统图库</el-button>
        <el-upload
          ref="upload"
          class="image-uploader"
          :action="uploadFileUrl"
          :show-file-list="false"
          :on-change="handleFileChange"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :before-upload="beforeFileUpload"
          :auto-upload="true"
          :headers="headers"
          :data="uploadData"
          :limit="1" accept=".png,.jpg,.jpeg,.gif">
          <el-button type="success" size="small" style="margin-top: 10px;width: 104px;" plain>上传图片</el-button>
        </el-upload>
        <div class="image-choose" slot="reference">
          <i class="el-icon-plus"></i>
        </div>
      </el-popover>
    </div>
    <ImageChooseDialog ref="imageChooseDialog" @confirm="addImages"></ImageChooseDialog>
  </div>
</template>

<script>
import { delImages, listImages } from "@/api/gallery/images";
import { getToken } from "@/utils/auth";
import { formatDateStr } from "@/utils";
import ImageChooseDialog from "./ImageChooseDialog";

export default {
  name: 'ImageChooser',
  components: {
    ImageChooseDialog,
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    queryId: {
      type: [String, Number],
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    },
    tag: {
      type: Object,
      default: () => ({})
    },
    taskName: {
      type: String,
      default: ''
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  created() {
    if (this.queryId) {
      this.loading = true;
      listImages({
        feedbackId: this.queryId,
      }).then(res => {
        this.list = res.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      })
    }
  },
  data () {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/gallery/images/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      list: [],
      uploadData: {
        imageTitle: this.taskName + '任务-' + this.tag.tagName + '图片',
        photoTime: formatDateStr(),// 图片拍摄时间,
        uploadTime: formatDateStr(),
        isOpen: 1,
        keyWords: '任务',
        cataId: this.tag.saveDir,
      },
      uploading: false,
      loading: false,
      bubVisible: false
    }
  },
  methods: {
    imageUrl(item) {
      let url = item.imagePath;
      if (item.file?.length > 0) {
        url = item.file[0].attachFileUrl || item.imagePath;
      }
      if (url.indexOf("http") === 0 || url.indexOf("blob:") === 0) {
          return url;
      }
      return process.env.VUE_APP_BASE_API + url;
    },
    handleFileChange(file) {

    },
    beforeFileUpload() {
      this.uploading = true;
    },
    handleFileSuccess(res, file) {
      this.uploading = false;
      if (res.code === 200) {
        this.$message.success('上传成功');
        console.log('上传成功；', res);
        
        this.list.push({
          imagePath: URL.createObjectURL(file.raw),
          id: res.imageId,
          _new: true,
        });
        this.$emit('change', this.list.map(item => item.id));
        this.bubVisible = false;
      } else {
        this.$message.error('上传失败');
        
      }
      this.$refs.upload.clearFiles();
    },
    handleFileError() {
      this.$message.error('上传失败');
      this.uploading = false;
      this.$refs.upload.clearFiles();
    },
    removeImage(item, i) {
      if (item._new) {
        this.loading = true;
        delImages(item.id).then(() => {
          this.$message.success('删除成功');
          this.list.splice(i, 1);
          this.$emit('change', this.list.map(item => item.id));
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        })
      } else {
        this.list.splice(i, 1);
        this.$emit('change', this.list.map(item => item.id));
      }
    },
    goChooseImage() {
      this.bubVisible = false;
      this.$refs.imageChooseDialog.open();
    },
    addImages(list) {
      this.list = this.list.concat(list);
      this.$emit('change', this.list.map(item => item.id));

    }
  }
}
</script>

<style scoped lang="scss">
.image-chooser {
  display: flex;
  flex-wrap: wrap;
}
.image-item {
  background: #f3f3f3;
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
  border-radius: 8px;
  position: relative;

  img {
    width: 100%;
    height: 100%;

  }

  .el-icon-circle-close {
    position: absolute;
    top: 0;
    right: 0;
    display: none;
    font-size: 22px;
    color: #f56c6c;
    cursor: pointer;
  }

  .image-choose {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    color: #ccc
  }

}
.image-item:hover {
  .el-icon-circle-close {
    display: block;
  }
}
.image-item + .image-item {
  margin-left: 10px;
}
</style>