<script setup>
import moment from "moment";
import QrcodeVue from "qrcode.vue";
import { toClipboard } from "@soerenmartius/vue3-clipboard";

import { ref, computed, onBeforeMount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from '@/store/user';
import { useCardStore } from '@/store/card';

import { showToast, showSuccessToast, showConfirmDialog } from "vant";
import 'vant/es/toast/style';

import { Dialog } from "vant";

import { login, bindCard, getMovie, getMarquee } from "@/api";

import noUserImg from '@/assets/images/upload.jpg'

const router = useRouter();
const route = useRoute();

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

const showShare = ref(false);
const showNfcQrcode = ref(false);
const showQrcode = ref(false);

const checked = ref(true);
const imageUrl = ref(import.meta.env.VITE_APP_BASE_URL);

const is_due = ref(false);

onBeforeMount(async () => {
  const liff = window.liff;
  try {
    if (!liff.isLoggedIn()) liff.login({ redirectUri: window.location.href });
  } catch (err) {
    console.log(`liff.state init error ${err}`);
    showToast("登入失敗。請聯絡管理員");
    router.push("/login");
  }

  if (!sessionStorage.getItem("token")) {
    const profile = await liff.getProfile();

    const id_token = liff.getIDToken();

    let loginRes = await login({ line_id: profile.userId, token: id_token });

    if (loginRes.code === 200) {
      if (route.query.act === "openright") {
        showToast("您已經是本站會員");
      }
      sessionStorage.setItem("token", loginRes.data.token);
      sessionStorage.setItem("uid", loginRes.data.uid);
    } else if (loginRes.code === 202) {
      if (route.query.act === "openright") {
        if (route.query.verify) {
          //詢問是否綁定
          Dialog.confirm({
            title: "卡片綁定",
            message: "確認是否綁定這張卡片",
          })
            .then(async () => {
              //確認綁定
              let bindRes = await bindCard({
                uid: loginRes.data.uid,
                verify: route.query.verify,
              });
              if (bindRes.code === 200) {
                showSuccessToast("綁定成功");
              } else {
                showToast.fail("綁定失敗");
              }
            })
            .catch(() => { });
        }
      }

      sessionStorage.setItem("token", loginRes.data.token);
      sessionStorage.setItem("uid", loginRes.data.uid);
    } else if (loginRes.code === 201) {
      if (route.query.act === "openright") {
        if (route.query.verify) {
          router.push({
            path: "/register",
            query: {
              verify: route.query.verify,
            },
          });

          return;
        }
      } else if (route.query.aid) {
        router.push({
          path: "/register",
          query: {
            aid: route.query.aid,
          },
        });
        return;
      } else {
        showToast("請先註冊成為本站會員");
        return router.push({
          path: "/register",
          query: { refer: route.query.refer },
        });
      }
    } else {
      showToast("登入失敗。請聯絡管理員");
      router.push("/login");
    }
  }
  
  await userStore.getUserData();
  await cardStore.getCardData();

  handleAD();

});

/**
 * title : 首頁廣告
 * fixed : wayne
 * date : 2023/10/26
 */

const noticeData = ref([]);
const adData = ref({});

const noticeClick = (num) => {
  let url = noticeData.value[num].ad_link;
  window.open(url, "_blank");
};

const handleAD = async () => {  
  console.log(userInfo.value);
  if(userInfo.value.status !== 1){
    let res;
    res = await getMarquee();
    if (res.code === 200) {
      noticeData.value = res.data;
    }

    res = await getMovie();
    if (res.code === 200) {
      adData.value = res.data;
      popShow.value = true;
    }
  }  
};

const popShow = ref(false);
const modalClose = ref(false);

const closeShow = () => {
  modalClose.value = true;
};

// 使用computed, 因為不能確認userInfo.value.is_send_ad是否有得到
// const adSwitchStatus = ref(Boolean(userInfo.value.is_send_ad));
const adSwitchStatus = computed(() => {
  return Boolean(userInfo.value.is_send_ad);
});

const onUpdateValue = (newValue) => {
  showConfirmDialog({
    title: "提醒確認",
    message: "是否切換開關？",
    confirmButtonText: "確認",
    cancelButtonText: "取消",
  }).then(() => {
    let res = userStore.setSendWithAd(newValue)
  }).catch(() => {

    // on cancel
  });

};


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

const nfcurl = computed(() => {
  return encodeURI(userStore.userData.ufcurl);
});

const overdue = computed(() => {
  if (userStore.userData.overdue_time > 0) {
    return moment
      .unix(userStore.userData.overdue_time)
      .format("YYYY-MM-DD");
  } else {
    return "無期限";
  }
});

const goCardEdit = () => {
  // if (userInfo.value.nc_type < 2) {
  if (userInfo.value.level < 2) {
    router.push("/card/notice");
  } else {
    router.push("/card");
  }
};

const onSelect = (option) => {
  showToast(option.name);
  showShare.value = false;
};

const handleShow = () => {
  showQrcode.value = true;
};

const handleShowNfc = () => {
  showNfcQrcode.value = true;
};

const doCopy = () => {
  toClipboard(userInfo.value.nfcurl);
  showToast("已放入剪貼簿");
};

const doCopyUid = () => {
  toClipboard(userInfo.value.user_id);
  showToast("已放入剪貼簿");
};

const doShare = () => {
  toClipboard(`https://liff.line.me/${import.meta.env.VITE_APP_LINE_LIFF_ID}/?aid=${userInfo.value.user_id}`)
  showToast("已放入剪貼簿");
};

const bindTggo = () => {
  if (userInfo.value.uniqid) {
    let url = `https://www.tggo.com.tw/u.cgi?&mnm=mybinding&ncode=${userInfo.value.uniqid}&name=${userInfo.value.real_name}&openExternalBrowser=1`;
    window.open(url, "_blank");
    return;
  }
  showToast('您的帳號尚未綁定感應卡');
};

const handleLogout = () => {
  if (liff.isLoggedIn()) {
    liff.logout();
  }
  sessionStorage.removeItem("token");
  sessionStorage.removeItem("uid");
  router.push("/login");
};

</script>

<template>
  <div class="home page" v-cloak>
    <van-nav-bar class="bg-darkBlue py-3">
      <template #title>
        <h4 class="text-white mb-1"><strong>UTEL電子名片系統</strong></h4>
        <a href="javascript:;">
          <h5 class="text-gray">歡迎來到會員中心</h5>
        </a>
      </template>
      <template #left>
        <div class="btn btn-sm text-skyBlue" @click="handleLogout">
          <h4><i class="fa-solid fa-arrow-right-to-bracket"></i></h4>
        </div>
      </template>
      <template #right>
        <div class="btn btn-sm text-skyBlue" @click="router.push('/member')">
          <h4><i class="fa-solid fa-gear"></i></h4>
        </div>
      </template>
    </van-nav-bar>

    <!-- START: 跑馬燈 -->
    <template v-if="userInfo.status !== 1">
      <van-notice-bar color="#ffffff" background="#e05338" left-icon="volume" mode="link" :scrollable="true">
        <van-swipe class="notice-swipe" :touchable="false" :show-indicators="false">
          <van-swipe-item v-for="(item, key, index) in noticeData" :key="index" @click="noticeClick(key)">
            {{ item.ad_title }}
          </van-swipe-item>
        </van-swipe>
      </van-notice-bar>
    </template>
    <!-- END: 跑馬燈 -->

    <div class="my-account">
      <div class="avatar">
        <div class="left">
          <div class="imgCnt shadow-sm">
            <img :src="userInfo.avatar || noUserImg" />
          </div>
          <div class="info">
            <h3 class="name">{{ userInfo.real_name }}</h3>
            <h5 class="conpany">{{ userInfo.company }}</h5>
          </div>
        </div>
        <!-- <div class="right">
          <div class="btn btn-sm text-darkBlue" @click="doShare">
            <h4><i class="fa-solid fa-clone"></i></h4>
          </div>
        </div> -->
      </div>

      <div class="recommend">
        <div class="btn btn-outline-lightBlue shadow-sm" @click="router.push('/shop')">
          <div class="img"><i class="fa-solid fa-cart-arrow-down"></i></div>
          <div class="text">立即開通</div>
        </div>
        <div class="btn btn-outline-lightBlue shadow-sm" @click="goCardEdit">
          <div class="img"><i class="fa-solid fa-id-card"></i></div>
          <div class="text">商務卡片</div>
        </div>
        <div class="btn btn-outline-lightBlue shadow-sm" @click="router.push('/address')">
          <div class="img"><i class="fa-solid fa-address-book"></i></div>
          <div class="text">通訊錄</div>
        </div>
      </div>
    </div>

    <!-- <div class="bwtFlex px-3 mb-2">
      <h5 class="font-weight-bold text-darkBlue">會員資料</h5>
      <a href="javascript:;" @click="router.push('/member')">
        <h5><i class="fa-solid fa-sliders text-darkBlue"></i></h5>
      </a>
    </div> -->  

    <div class="content" v-if="userInfo">
      <van-cell-group inset>
        <van-field :model-value="userInfo.create_time" input-align="right" readonly>
          <template #label><i class="fa-regular fa-fw fa-calendar-days"></i> 建立日期</template>
        </van-field>
        <van-field :model-value="userInfo.user_id" input-align="right" readonly>
          <template #label><i class="fa-solid fa-fw fa-fingerprint"></i> 會員編號</template>
          <template #button>
            <van-button size="small" @click="doCopyUid">
              <i class="fa-regular fa-copy"></i>
            </van-button>
          </template>
        </van-field>
        <van-field :model-value="userInfo.level_name" input-align="right" readonly>
          <template #label><i class="fa-solid fa-fw fa-layer-group"></i> 會員等級</template>
        </van-field>
        <van-field :model-value="overdue" input-align="right" readonly>
          <template #label><i class="fa-regular fa-fw fa-calendar-check"></i> 使用期限</template>
        </van-field>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-solid fa-fw fa-handshake-angle"></i> 分享加入</template>
          <template #button>
            <van-button size="small" class="btn-outline-skyBlue mr-1"
              @click="handleShow"><i class="fa-solid fa-qrcode"></i> QRcode
            </van-button>
            <van-button size="small" class="btn-outline-skyBlue"
              @click="doShare"><i class="fa-regular fa-copy"></i> 複製連結
            </van-button>
          </template>
        </van-field>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-solid fa-fw fa-chess-board"></i> NFC名片</template>
          <template #button>
            <van-button size="small" class="btn-outline-skyBlue mr-1"
              @click="handleShowNfc"><i class="fa-solid fa-qrcode"></i> QRcode
            </van-button>
            <van-button size="small" class="btn-outline-skyBlue"
              @click="doCopy"><i class="fa-regular fa-copy"></i> 複製連結
            </van-button>
          </template>
        </van-field>
      </van-cell-group>

      <van-cell-group inset>
        <van-field :model-value="userInfo.title" input-align="right" readonly>
          <template #label><i class="fa-regular fa-fw fa-building"></i> 職稱</template>
        </van-field>
        <van-field :model-value="userInfo.phone" input-align="right" readonly>
          <template #label><i class="fa-solid fa-fw fa-mobile-retro"></i> 手機</template>
        </van-field>
        <van-field :model-value="userInfo.tel" input-align="right" readonly>
          <template #label><i class="fa-solid fa-fw fa-phone"></i> 市話</template>
        </van-field>
        <van-field :model-value="userInfo.email" input-align="right" readonly>
          <template #label><i class="fa-regular fa-fw fa-envelope"></i> Email</template>
        </van-field>
        <van-field :model-value="userInfo.address" input-align="right" readonly>
          <template #label><i class="fa-solid fa-fw fa-location-dot"></i> 住址</template>
        </van-field>
      </van-cell-group>

      <van-cell-group inset>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-solid fa-fw fa-user-tie"></i> 授權商務卡片編輯</template>
          <template #button>
            <van-button size="small" @click="$router.push('/auth/auth')">
              授權
            </van-button>
          </template>
        </van-field>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-regular fa-fw fa-handshake"></i> 代客編輯商務卡片</template>
          <template #button>
            <van-button size="small" @click="$router.push('/auth/getauth')">
              編輯
            </van-button>
          </template>
        </van-field>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-solid fa-fw fa-award"></i> 綁定UTel淘金購會員</template>
          <template #button>
            <van-button size="small" @click="bindTggo">
              點擊後前往綁定
            </van-button>
          </template>
        </van-field>
        <van-field input-align="right" class="longText" readonly>
          <template #label><i class="fa-regular fa-fw fa-paper-plane"></i> 發送名片帶廣告</template>
          <template #input>
            <van-switch v-model="adSwitchStatus" @update:model-value="onUpdateValue" size="18px" active-color="#345068"
              inactive-color="#888888" />
          </template>
        </van-field>
      </van-cell-group>

      <div class="px-3">
        <van-button size="normal" block class="bg-darkBlue text-white border-0" @click="router.push('/send')">
          <h5><i class="fa-regular fa-fw fa-paper-plane"></i> 發送名片</h5>
        </van-button>

      </div>
    </div>


    <van-dialog v-model:show="showQrcode" title="會員加入分享" :show-cancel-button="true" cancel-button-text="關閉"
      :show-confirm-button="false">
      <div class="qrcode text-center pt-3">
        <qrcode-vue :value="userInfo.referurl" :size="200" level="M" />
      </div>
    </van-dialog>
    
    <van-dialog v-model:show="showNfcQrcode" title="NFC名片分享" :show-cancel-button="true" cancel-button-text="關閉"
      :show-confirm-button="false">
      <div class="qrcode text-center pt-3">
        <qrcode-vue :value="userInfo.nfcurl" :size="200" level="M" />
      </div>
    </van-dialog>

    <van-overlay :show="popShow" z-index="1000" :style="{ background: 'rgba(0, 0, 0, .85)' }">
      <div class="wrapper" @click.stop>
        <div class="clip">
          <van-icon :style="{ display: 'none', marginRight: '5px' }" @click="popShow = false"
            :class="{ 'd-block': modalClose }" name="cross" size="15" />
          <van-count-down :style="{ color: '#fff' }" @finish="closeShow" :auto-start="true" :time="adData.play_sec * 1000"
            format="ss 秒" />
        </div>
        <div class="top">
          <iframe width="100%" height="100%" :src="imageUrl + adData.ad_movie" title="YouTube video player"
            autoplay="true" frameborder="0" controls="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowfullscreen></iframe>
        </div>
        <div class="bottom">
          <h5 class="title">{{ adData.ad_title }}</h5>
          <h6 class="desc ellipsis e3">{{ adData.ad_desc }}</h6>
          <van-button type="light" :url="adData.ad_link" block v-if="adData.ad_link">
            <i class="fa-solid fa-fw fa-link"></i> 前往連結
          </van-button>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<style src="@/assets/css/main.css"></style>

<style lang="less" scoped>
.home {
  .wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 100%;

    .clip {
      position: absolute;
      display: flex;
      align-items: center;
      color: #ffffff;
      background-color: rgba(#000000, 0.8);
      top: 5px;
      right: 5px;
      margin-left: auto;
      padding: 10px;
      cursor: pointer;
      z-index: 1005;
    }

    .top {
      position: relative;
      display: flex;
      align-items: center;
      width: 100%;
      flex: 1 0 0;
    }

    .bottom {
      position: relative;
      width: 100%;
      flex: 0 0 auto;
      padding: 15px;

      .title {
        color: #ffffff;
        font-weight: bold;
        margin-bottom: 15px;
      }

      .desc {
        color: #ffffff;
        margin-bottom: 30px;
      }
    }
  }

  .my-account {
    position: relative;
    width: 100%;
    padding: 20px 25px;

    .avatar {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        align-items: center;
        flex: 1 0 0;

        .imgCnt {
          width: 80px;
          height: 80px;
          min-width: 80px;
          border-radius: 50%;
          border: 2px #fff solid;
          overflow: hidden;
          margin-right: 15px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .info {
          .name {
            font-weight: bold;
            color: #303a47;
          }

          .conpany {
            margin-top: 5px;
          }
        }
      }

      .right {
        flex: 0 0 auto;
      }
    }

    .recommend {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 0 10px;

      .btn {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        width: 30%;
        height: 100px;
        background-color: #fff;
        border-radius: 0;

        .img {
          font-size: 35px;
          line-height: 45px;
          color: #345068;
        }

        .text {
          font-size: 16px;
          font-weight: bold;
          color: #345068;
        }
      }
    }
  }
}
</style>
