<template>
  <view class="bg-max bg-gray">
    <van-sticky>
      <view class="justify-center bg-white sh pd-px-20 mg-b-20">
        <van-icon class="top-left" name="arrow-left" @tap="goBack" />
        <view class="top-center">{{ state.title }}</view>
      </view>
    </van-sticky>
    <van-grid :column-num="2" :gutter="5" class="bg-gray pd-b-px-60">
      <van-grid-item v-for="(item, index) in state.list" @tap="onCard(index)">
        <view class="text-center bg-white mg-v-px-10-m">
          <van-image :src="item.path" width="322rpx" height="543rpx"
            loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default.png" icon-size="322rpx" />
          <view>{{ item.name }}</view>
        </view>
        <!-- 这个部分是卡片的实体部分，我置底了 -->
        <view class="card" :id="'card' + index" v-if="item.showed">
          <canvas style="width: 720px;height: 1214px;" :id="'cardbg' + index" :canvas-id="'cardbg' + index" />
          <view class="info flex">
            <view>
              <van-image width="160px" height="160px" :src="state.qrcode"
                loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default.png" icon-size="160px" />
              <view class="tip">扫码获取更多活动信息</view>
            </view>
            <view class="detail">
              <view class="flex" v-for="item in state.infoList">
                <view class="name">{{ item.name }}</view>
                <view class="value">{{ item.value }}</view>
              </view>
            </view>
          </view>
        </view>
      </van-grid-item>
    </van-grid>
    <view class="fixed-bottom text-center bg-white pd-30 br-t" style="z-index: 1">点击查高清图</view>
    <van-image-preview v-model:show="state.preview.show" :start-position="state.preview.index" closeable
      :images="state.list.map((item: any) => item.showPath)" @change="onCardShow" :showIndex="false"/>
    <!-- 因为生成卡片会卡，所以加载完一张之后，再让用户操作 -->
    <van-overlay :show="state.preview.loading" style="z-index: 2003"/>
  </view>
</template>

<script setup lang="ts">
import api from '@/api';
import { onBeforeMount, reactive } from 'vue';
import { PageUtils } from '@/utils/utils';
// @ts-ignore
import QRCode from 'qrcode'
import html2Canvas from "html2canvas"
const state = reactive({
  title: PageUtils.getTitle(),
  data: {} as any,
  list: [] as any,
  infoList: [] as any,
  qrcode: '',
  preview: {
    index: 0,
    show: false,
    loading: false
  }
})

onBeforeMount(() => {
  storeCard()
})
function storeCard() {
  api.storeCard({
    link: uni.getStorageSync('subdomain')
  }).then((data: any) => {
    state.data = data
    state.list = data.cards
    state.infoList = [
      { name: '商城名称：', value: state.data.mallName },
      { name: '商城网址：', value: state.data.mallLink + '.edstao.com' },
      { name: '联系电话：', value: state.data.mallContact },
      { name: '门店地址：', value: state.data.storeAddress },
    ]
  })
}
// 再画卡片
function drawBg(index: number) {
  const item = state.list[index]
  uni.downloadFile({
    url: item.path + '?timestamp=' + new Date().getTime(),
    success: (res) => {
      if (res.statusCode === 200) {
        const ctx = uni.createCanvasContext('cardbg' + index)
        ctx.drawImage(res.tempFilePath, 0, 0, 720, 1214)
        ctx.draw()
        // 等待1s画完卡片
        setTimeout(() => {
          const cardDom = document.getElementById("card" + index)
          if (!cardDom) return
          html2Canvas(cardDom, { useCORS: false }).then(canvas => {
            // 生成实际blob-url
            item.showPath = canvas.toDataURL("image/png")
          })
        }, 500);
      }
    },
    fail: () => {
      item.showed = false
    },
    complete: () => {
      setTimeout(() => {
        state.preview.loading = false
      }, 1000)
    },
  })
}
// 先画二维码
function drawQR(index: number) {
  const item = state.list[index]
  if (item.showed || state.preview.loading) return
  state.preview.loading = true
  item.showed = true
  if (state.qrcode) {
    drawBg(index)
  } else {
      if(window.__wxjs_environment === 'miniprogram'&&state.data.appletCode){
          var appresultText=state.data.appletCode
          convertImgToBase64(appresultText, function(base64Img){
              state.qrcode = base64Img
          });
          drawBg(index)
	}else {
          QRCode.toDataURL('https://'+state.data.mallLink + '.edstao.com', {
              width: 160,
              height: 160,
              margin: 1
          } as QRCode.QRCodeToDataURLOptions).then((url: any) => {
              state.qrcode = url
              drawBg(index)
          }).catch(() => {
              state.preview.loading = false
          })
	}
  }
}
function convertImgToBase64(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img,0,0);
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
        canvas = null;
    };
    img.src = url;
}

function onCard(index: number) {
  state.preview.index = index
  state.preview.show = true
  drawQR(index)
}
function onCardShow(index: number) {
  state.preview.index = index
  drawQR(index)
}
function goBack() {
  PageUtils.goBack()
}
</script>

<style lang="scss" scoped>
.card {
  position: absolute;
  width: 720px;
  height: 1214px;
  bottom: 0;
  right: 0;
  z-index: -1;

  .info {
    position: absolute;
    top: 920px;
    padding: 20px;

    .tip {
      font-size: 16px;
      white-space: nowrap;
      overflow: visible;
    }

    .detail {
      font-size: 24px;
      padding-left: 20px;

      .name {
        width: 140px;
      }

      .value {
        width: 360px;
      }
    }
  }
}
</style>
