<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: [],
      current: 1,
      size: 16
    };
  },
  async mounted() {
    await this.getTemplateList();
    this.templateList.length && this.$emit('click', this.templateList[0][0]);
  },
  methods: {
    /* 获取模板列表 */
    async getTemplateList() {
      try {
        const res = await getTemplateList({
          current: this.current,
          size: this.size,
          departmentId: uni.getStorageSync("userInfo").deptId
        });
        if(res.data && res.data.records.length > 0) {
          //每8个一组作为一个数组,push到templateList中
          for (let i = 0; i < res.data.records.length; i += 8) {
            this.templateList.push(res.data.records.slice(i, i + 8));
//            //依次下载每个模板的图片
            for (const item of this.templateList[this.templateList.length - 1]) {
              await this.handleDownImg(item);
            }
          }
        }
      } catch (e) {
        console.log(e);
      }
    },
    /* 点击模板 */
    handleClick(item) {
      this.$emit('click', item);
    },
    async handleDownImg(item) {
      if (!item.iconUrl) {
        item.imgUrl = TemplateImg;
      } else if(!item.imgUrl) {
        let res = await downFileBase64({
          uuid: item.iconUrl
        });
        item.imgUrl = 'data:image/jpeg;base64,' + res.data;
      }
    }
  }
};
</script>

<template>
  <van-swipe class="my-swipe" @change="onChange"  indicator-color="white" :loop="false">
    <van-swipe-item  v-for="(groupItem,index) in templateList" :key="index">
      <view class="box">
        <view v-for="item in groupItem" :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>
    </van-swipe-item>
  </van-swipe>
</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>
