<template>
  <el-dialog
    title="图库"
    width="80%"
    :visible.sync="imgVisible"
    class="imglist-dialog"
  >
    <div class="btns">
      <el-upload
        class="upload-demo"
        :on-success="onSuccess"
        :show-file-list="false"
        action="/api/file/uploadFile"
        :headers="{ 'Blade-Auth': Authorization }"
        multiple
        list-type="picture"
      >
        <el-button size="small" icon="el-icon-upload" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button
        size="small"
        type="danger"
        plain
        icon="el-icon-delete"
        @click="handleSetimg('')"
      >
        清空
      </el-button>
    </div>
    <el-scrollbar class="imgList">
      <img
        :src="item.value"
        :style="styleName"
        @click="handleSetimg(item.value)"
        v-for="(item, index) in imgOption[imgActive]"
        :key="index"
      />
    </el-scrollbar>
  </el-dialog>
</template>

<script>
import { getToken } from "../../../util/auth";
import { imgOption } from "../config";
import website from "../../../config/website";

export default {
  data() {
    return {
      imgVisible: false,
      imgObj: "",
      type: "",
      imgActive: 0,
      imgOption: imgOption,
      imgTabs: [],
      Authorization: "bearer " + getToken(),
    };
  },
  computed: {
    styleName() {
      if (this.type === "background") {
        return {
          width: "200px",
        };
      }
      return {};
    },
  },
  watch: {
    type: {
      handler() {
        if (this.type === "background") {
          this.imgActive = 0;
        } else if (this.type == "border") {
          this.imgActive = 1;
        } else {
          this.imgActive = 2;
        }
      },
      immediate: true,
    },
  },
  methods: {
    onSuccess(res) {
      const url = website.url.replace("/dev", "") + "/" + res.msg;
      this.imgOption[this.imgActive].unshift({
        label: url,
        value: url,
      });
    },
    openImg(item, type) {
      this.type = type;
      this.imgObj = item;
      this.imgVisible = true;
    },
    handleSetimg(item) {
      this.imgVisible = false;
      this.$emit("change", item, this.imgObj);
    },
  },
};
</script>

<style lang="scss">
.imglist-dialog {
  .btns {
    display: flex;
    .el-button {
      margin-left: 20px;
    }
  }
  .el-scrollbar__view img {
    width: 200px;
    height: 100px;
    margin: 20px 10px;
  }
}
</style>
