<script setup>
import liff from "@line/liff";

import { showToast, showSuccessToast } from 'vant';

import { onMounted, ref, computed, watch } from 'vue'

import { getCard, getCusCard, getVipCard, updateSendCount, getFlexcard } from '@/api'

import { cardFactory } from '@/utils/card'

import { genCard1 } from '@/utils/card2'
import { genVipCard } from '@/utils/vipcard'
import { genAdCard } from '@/utils/adcard'

import { useUserStore } from '@/store/user';
import { useCardStore } from '@/store/card';

const userStore = useUserStore();
const cardStore = useCardStore();

const imageUrl = ref(import.meta.env.VITE_APP_BASE_URL)

const state = ref({
  // active: 0,
  showCusCard: false,
  card_title: computed(() => cusCardInfo.value.card_title),
  vip_card: [],
  flexContent: {},
})

const activeName = ref('0');

let flexRef = ref(null)

const userInfo = computed(() => {
  return userStore.userData;
});

const cusCardInfo = computed(() => {
  return cardStore.cusCard;
});

// const vipCardInfo = computed(() => {
//   return cardStore.vipCard;
// });

onMounted(async () => {
  await liff.init({ liffId: import.meta.env.VITE_APP_LINE_LIFF_ID });

  await userStore.getUserData();
  await cardStore.getCardData();

  if (userInfo.value.level > 2) {
    let vipCardRes = await getVipCard({ userid: sessionStorage.getItem('uid') })
    state.value.vip_card = vipCardRes.data
  } else {
    state.value.vip_card = []
  }
})

//切換tab
watch(() => activeName.value, function (newVal, oldVal) {
  if (newVal !== oldVal) {
    showFlex(newVal)
  }
}, { immediate: true })

//確認是否顯示附加卡片
watch(() => userInfo.value.cus_card, function (newVal, oldVal) {
  // if (userInfo.value.level > 1 && newVal > 0) {
  if (userInfo.value.level > 1) {
    state.value.showCusCard = true
  }
}, { immediate: true })

//切換NFC版型
watch(() => userInfo.value.nc_template, function (newVal, oldVal) {
  showFlex('0')
})

async function showFlex(id) {
  switch (id) {
    case '0':
      let { data: res } = await getCard({ userid: sessionStorage.getItem('uid') })
      let { card } = cardFactory({ tid: userInfo.value.nc_template, vcard: res })
      if (userInfo.value.status !== 0 && !userInfo.value.is_send_ad) { //正常 & 願意帶廣告  
        state.value.flexContent = JSON.parse(card)
      } else {
        let res2 = await getFlexcard();
        if (res2.code === 200) {
          if (res2.data.length !== 0) {
            let data = res2.data;
            data.ad_image = imageUrl.value + data.ad_image;
            state.value.flexContent = genAdCard(JSON.parse(card), data);
          }else{
            state.value.flexContent = JSON.parse(card)
          }
        }
      }

      console.log('card', JSON.stringify(state.value.flexContent) )

      flexRef.value.innerHTML = ''

      flex2html("flex", state.value.flexContent)

      break
    case '1':
      if (userInfo.value.level > 1) {
        let card2Res = await getCusCard({ userid: sessionStorage.getItem('uid') })
        if (card2Res.code === 200) {
          if (card2Res.data.cus_card) {
            state.value.flexContent = genCard1(JSON.parse(card2Res.data.cus_card))
            flexRef.value.innerHTML = ''
            flex2html("flex", state.value.flexContent)
          }
        }
      } else {
        flexRef.value.innerHtml = ''
      }
      break
    default:
      if (userInfo.value.level > 2) {
        // let vipCardRes = await getCusCard({userid: sessionStorage.getItem('uid')})
        let res = state.value.vip_card.find(item => { return item.id == id })
        if (res.type === 0) {
          state.value.flexContent = genCard1(JSON.parse(res.content))
          flexRef.value.innerHTML = ''
          flex2html("flex", state.value.flexContent)
        } else {
          state.value.flexContent = genVipCard(JSON.parse(res.content))
          flexRef.value.innerHTML = ''
          flex2html("flex", state.value.flexContent)
        }
        // if( card2Res.code === 200){
        //   if(card2Res.data.cus_card){
        //     state.flexContent = genCard1(JSON.parse(card2Res.data.cus_card))
        //     flexRef.value.innerHTML = ''
        //     flex2html("flex", state.flexContent)
        //   }
        // }
      } else {
        flexRef.value.innerHtml = ''
      }
      break
  }
}

const sendEcard = async () => {
  if (!liff.isLoggedIn()) {
    liff.login({ redirectUri: window.location.href })
  }

  let content = JSON.parse(JSON.stringify(state.value.flexContent))

  // console.log('content', JSON.stringify(state.value.flexContent))
  let res

  if (activeName.value === '0') {
    res = await liff.shareTargetPicker([content,
      {
        'type': 'text',
        'text': '名片的連結都可以點擊!'
      }])
  } else {
    res = await liff.shareTargetPicker([content])
  }

  if (res.status === 'success') {
    let result = await updateSendCount(userInfo.value.user_id)
    showSuccessToast('傳送成功')
    // .then(() => {
    //   // on confirm
    // })
    // .catch(() => {
    //   // on cancel
    // })
  } else {
    showToast.fail('傳送失敗')
  }
}

const sendMsg = async () => {
  if (!liff.isLoggedIn()) {
    liff.login({ redirectUri: window.location.href })
  }
  // console.log(state.value.flexContent)
  // if(state.active===0){
  let res0 = await liff.sendMessages([JSON.parse(JSON.stringify(state.value.flexContent))])
  // }else{
  //   let res1 = await liff.sendMessages([JSON.parse(JSON.stringify(state.flexContent))])
  // }

}

const showDraw = ref(false)

function showChangeTpl() {
  showDraw.value = true
}

const changeTpl = async (val) => {
  userStore.setUserTpl(val)
  showDraw.value = false
}


</script>

<template>
  <div class="member page bg-lightBlue">
    <van-nav-bar class="bg-skyBlue py-1" left-arrow @click-left="$router.push('/')">
      <template #title>
        <h5 class="text-white mb-1"><strong>名片分享</strong></h5>
      </template>
      <template #left>
        <h4><i class="fa-solid fa-angle-left text-white" :style="{ opacity: 0.5 }"></i></h4>
      </template>
    </van-nav-bar>


    <div class="tab-section bg-lightPink" v-cloak>
      <van-tabs :lazy-render="true" v-model:active="activeName" v-show="userInfo.level > 1">
        <van-tab name="0">
          <template #title>
            <div class="tab_item">
              <i class="fa-regular fa-id-card fa-2x mb-1"></i>
              <p class="mb-3">我的名片</p>
            </div>
          </template>
        </van-tab>

        <van-tab name="1" v-if="state.showCusCard">
          <template #title>
            <div class="tab_item">
              <i class="fa-solid fa-clipboard fa-2x mb-1"></i>
              <p class="mb-3">{{ state.card_title }}</p>
            </div>
          </template>
        </van-tab>

        <van-tab :name="card.id.toString()" v-for="card of state.vip_card" :key="card.id">
          <template #title>
            <div class="tab_item">
              <i class="fa-regular fa-file-lines fa-2x mb-1"></i>
              <p class="mb-3">{{ card.title }}</p>
            </div>
          </template>
        </van-tab>

        <!-- <van-tab :title="state.card_title" name="1" v-if="state.showCusCard"/>
        <van-tab :title="card.title" :name="card.id.toString()" v-for="card of state.vip_card" :key="card.id"/> -->
      </van-tabs>


      <div class="flex-section">
        <div class="table-responsive">
          <div class="chatbox">
            <!-- <div id="flex" ref="flexRef"></div> -->
            <div id="flex" ref="flexRef"></div>
          </div>
        </div>
      </div>
      <h6 class="text-center text-white bg-darkBlue py-2">上面圖內「分享」無效，請點下列「分享」</h6>
    </div>

    <van-sticky position="bottom">
      <div class="bottomBtnCnt d-flex">
        <van-button block class="btn-skyBlue m-2" @click="sendEcard">
          <h6><i class="fa-solid fa-share-from-square"></i> 分享好友</h6>
        </van-button>
        <van-button block class="btn-tomatoRed m-2" @click="showChangeTpl" v-show="activeName == '0'">
          <h6><i class="fa-solid fa-right-left"></i> 切換樣版</h6>
        </van-button>
      </div>
    </van-sticky>

    <van-popup v-model:show="showDraw" round position="bottom">
      <div>
        <ul class="tpl-list d-flex flex-wrap">
          <li class="tpl-item" @click="changeTpl(0)">
            <img src="@/assets/images/tpl/tpl0.png">
          </li>
          <li class="tpl-item" @click="changeTpl(1)">
            <img src="@/assets/images/tpl/tpl1.png">
          </li>
          <li class="tpl-item" @click="changeTpl(2)">
            <img src="@/assets/images/tpl/tpl2.png">
          </li>
          <li class="tpl-item" @click="changeTpl(3)">
            <img src="@/assets/images/tpl/tpl3.png">
          </li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<style lang="less" scoped>
.btn-area {
  padding: 5px 15px
}

.flex-section {
  // color: white;
  // z-index: 99999;
  background-color: #333;
}


.chatbox {
  background-color: #333;
  margin-top: 10px;
  padding-top: 10px;
}


.table-responsive {
  width: 100%;
  overflow-x: auto;
}


.tpl-list {
  .tpl-item {
    width: 150px;
    padding: 10px;

    img {
      width: 100%;
    }
  }
}
</style>
