<script>
import {downFileBase64, getTemplateList} from "@/api/commitment";
import TemplateImg from "@/static/images/commitment/template.png";

export default {
  props:{
    activeTemplateId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      templateList:[]
    };
  },
  async mounted() {
    await this.getTemplateList();
    this.templateList.length && this.$emit('click', this.templateList[0]);
  },
  methods: {
    /* 获取模板列表 */
    async getTemplateList() {
      try {
        const res = await getTemplateList({
          current: 1,
          size: 8,
          departmentId: uni.getStorageSync("userInfo").deptId
        });
        this.templateList = res.data.records || [];
        for (const [index, item] of this.templateList.entries()) {
          await this.handleDownImg(item.iconUrl, index);
        }
      } catch (e) {
        console.log(e);
      }
    },
    /* 点击模板 */
    handleClick(item) {
      this.$emit('click', item);
    },
    async handleDownImg(iconUrl, index) {
      if (!iconUrl) {
        this.templateList[index].imgUrl = TemplateImg;
      } else {
        let res = await downFileBase64({
          uuid: iconUrl
        });
        this.templateList[index].imgUrl = 'data:image/jpeg;base64,' + res.data;
      }
    }
  }
};
</script>

<template>
  <view class="box">
    <view v-for="item in templateList" :key="item.uuid"
          @click="handleClick(item)"
          :class="{active: item.uuid === activeTemplateId}">
      <img :src="item.imgUrl" style="border-radius: 5px" alt="">
      <view class="text-overflow">{{item.name}}</view>
    </view>
  </view>
</template>

<style scoped lang="scss">
// box每行显示4个,超出换行,靠右
.box {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  height: 188px;
  border-radius: 0 0 6px 6px;
  box-sizing: border-box;
  padding: 20px 10px;
  background-image: linear-gradient(180deg, #FFFFFF 87%, #F2F3F5 100%);
  > view {
    margin: 0 2% 0 0;
    width: 23%;
    display: flex;
    flex-direction: column;
    align-items: center;
    > view {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
      text-align: center;
    }
    img {
      width: 42px;
      height: 42px;
    }
  }
}
.active {
  transform: scale(1.1);
}
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  display: block;
  box-sizing: border-box;
}
</style>
