<template>
  <div class="card-exchange-view">
    <card-view
      ref="CardView"
      class="card-preview"
      :pages="pages"
      :card-config="cardConfig"
    ></card-view>
    <!-- 卡格式 -->
    <div class="card-spin-container card-preview">
      <template v-for="(page, pageNo) in pages">
        <div
          :class="['page-box', `page-box-${cardConfig.pageSize}`]"
          :key="pageNo"
        >
          <div
            v-for="(item, index) in page.spins"
            :key="index"
            class="element-spin"
            :style="item.style"
          ></div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import CardView from "../../card/components/CardView";
import { cardDetail } from "../../src/modules/card/api";

export default {
  name: "card-exchange-view",
  components: { CardView },
  data() {
    return { cardConfig: {}, pages: [] };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      const cardId = this.$route.params.cardId;
      if (!cardId) return;

      const detData = await cardDetail(cardId);
      if (!detData.content) return;

      const { cardConfig, pages } = JSON.parse(detData.content);
      this.cardConfig = cardConfig;
      this.pages = pages.map((page) => {
        page.spins = this.parseSpins(page);
        return page;
      });
    },
    parseSpins(page) {
      const spins = [];

      const getPercentNum = (num) => {
        return num * 100 + "%";
      };

      const transformData = (dataList) => {
        dataList.forEach((item) => {
          spins.push({
            style: {
              left: getPercentNum(item[0]),
              top: getPercentNum(item[1]),
              width: getPercentNum(item[2]),
              height: getPercentNum(item[3]),
            },
          });
        });
      };

      const { locator, barcode, fill_area, answer_area } = page.exchange;

      const locators = [...locator.top, ...locator.bottom];
      transformData(locators);
      transformData(barcode.map((item) => item.area));
      // transformData(info_area);

      fill_area.forEach((farea) => {
        farea.items.forEach((fitem) => {
          transformData(fitem.options);
        });
      });

      transformData(answer_area.map((item) => item.area));

      return spins;
    },
  },
};
</script>

<style lang="scss">
.card-exchange-view {
  .element-spin {
    position: absolute;
    background: rgba(254, 93, 78, 0.5);
    z-index: auto;
  }
  .card-spin-container {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 9;
    padding: 10px 0;
    background: transparent;

    .page-box {
      background: transparent;
      box-shadow: none;
    }
  }
}
</style>
