<!-- 上传图片 -->
<template>
  <div>
    <!-- 单选图片 -->
    <div v-if="!multiple">
      <el-upload
        :style="{width : width,height : height}"
        class="upload-img"
        :action="'/api/DbFile/{0}'.format(this.tenantId)"
        accept="image/jpg, image/jpeg, image/png, image/gif"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :before-upload="beforeUpload"
      >
        <img :src="imageUrl" v-if="imageUrl" />
        <i :style="{lineHeight : height}" class="el-icon-plus" v-else></i>
      </el-upload>
    </div>

    <!-- 多选图片 -->
    <div v-if="multiple">
      <div
        v-for="(url,index) in imageUrls"
        :key="index"
        :style="{width : width,height : height}"
        class="upload-show-multiple"
      >
        <img :src="url" />
        <div class="pic-delete" v-if="url" @click="deleteImg(index)">
          <i :style="{lineHeight : height}" class="el-icon-delete"></i>
        </div>
      </div>
      <el-upload
        :style="{width : width,height : height}"
        class="upload-img"
        :action="'/api/DbFile/{0}'.format(this.tenantId)"
        accept="image/jpg, image/jpeg, image/png, image/gif"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :before-upload="beforeUpload"
        v-if="imageUrls.length < max"
      >
        <i :style="{lineHeight : height}" style="float:left;" class="el-icon-plus"></i>
      </el-upload>
    </div>
  </div>
</template>
<script>
export default {
  name: "CsFieldUploadImage",
  props: {
    value: {
      default: null,
    },
    tenantId: {
      default: null,
    },
    width: {
      type: String,
      default: "200px",
    },
    height: {
      type: String,
      default: "200px",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    max: {
      type: Number,
      default: 9,
    },
  },
  components: {},
  data() {
    return {
      fileId: 0,
      imageUrl: "",

      fileIds: [],
      imageUrls: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    value: {
      handler(val) {
        this.setData();
      },
      immediate: false, // 首次绑定是否执行
      deep: true, // 对象内部的属性监听，也叫深度监听
    },
    fileId(val) {
      this.$emit("input", val);
    },
    fileIds: {
      handler(val) {
        this.$emit("input", val.join(","));
      },
      immediate: false, // 首次绑定是否执行
      deep: true, // 对象内部的属性监听，也叫深度监听
    },
  },
  //方法集合
  methods: {
    /* 上传文件之前检查 */
    beforeUpload(file) {
      switch (file.type) {
        case "image/png":
        case "image/jpg":
        case "image/jpeg":
        case "image/gif":
          break;
        default:
          this.$util.warning(this.$t("common.uploadImageErrorTips"));
          return false;
          break;
      }

      if (this.imageUrls.length >= this.max) {
        this.$util.warning(
          this.$t("common.uploadImageMaxTips".format(this.max))
        );
        return false;
      }

      return true;
    },

    /* 上传图片成功 */
    uploadSuccess(fileId) {
      if (!this.multiple) {
        this.fileId = fileId;
        this.imageUrl = this.$util.getFileUrl(this.tenantId, fileId);
      } else {
        this.fileIds.push(fileId);
        this.imageUrls.push(
          this.$util.getFileUrl(this.tenantId, Number(fileId))
        );
      }
    },

    /* 上传图片失败 */
    uploadError(res) {
      this.$emit("on-error", res);
    },

    /* 删除图片 */
    deleteImg(index) {
      this.$confirm(this.$t("common.deleteImg"), this.$t("common.tips"), {
        confirmButtonText: this.$t("common.ok"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          this.fileIds.splice(index, 1);
          this.imageUrls.splice(index, 1);
          this.$util.info(this.$t("common.deleteSuccess"));
        })
        .catch(() => {});
    },

    setData() {
      if (!this.multiple) {
        this.fileId = this.value;
        this.imageUrl = this.$util.getFileUrl(this.tenantId, this.fileId);
      } else {
        this.fileIds.splice(0, this.fileIds.length);
        this.imageUrls.splice(0, this.imageUrls.length);
        if (this.value) {
          this.fileIds = this.value.split(",");
          this.fileIds.forEach((fileId) => {
            this.imageUrls.push(
              this.$util.getFileUrl(this.tenantId, Number(fileId))
            );
          });
        }
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (!this.tenantId) {
      this.$util.warning("请传入租户编号");
      return;
    }

    this.setData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
/* 选择图片样式 */
.upload-img {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  i {
    width: 100%;
    color: #8c939d;
    font-size: 28px;
    text-align: center;
  }
  img {
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    object-fit: cover;
  }
}
.upload-img:hover {
  border-color: #409eff;
}

/* 查看多张图片样式 */
.upload-show-multiple {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;
  float: left;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  /* 删除标签 */
  .pic-delete {
    width: 100%;
    height: 100%;
    text-align: center;
    display: none;
    position: absolute;
    top: 0;
    left: 0;

    i {
      color: white;
      font-size: 22px;
    }
  }
}
.upload-show-multiple:hover {
  border-color: #409eff;

  .pic-delete {
    display: block;
    background-color: rgba(0, 0, 0, 0.4);
  }
}
</style>