<template>
  <view class="flex flex-col justify-center items-center h-full">
    <image class="flash-logo" src="/static/logo-plain.png" />
  </view>
</template>
<script setup>
import { ref } from "vue";
import { storeToRefs } from "pinia";
import { onLoad } from "@dcloudio/uni-app";
import api from "@/utils/api";
import { set } from "@/utils/cache";
import { toast } from "@/utils/widget";
import useAccountStore from "@/store/account";

const env = __VITE_ENV__;
const appid = env.MP_WX_APP_ID;
const { account } = storeToRefs(useAccountStore());


const loading = ref(false);
const team = ref(null);

async function changeTeam({ teamId, corpId }) {
  loading.value = true;
  const res = await api("getTeamData", { teamId, corpId, withCorpName: true });
  loading.value = false;
  if (res && res.data) {
    team.value = res.data;
    team.value.corpName = res.data.corpName;
    if (account.value) {
      bindTeam()
    } else {
      set("invite-team-info", {
        corpId: team.value.corpId,
        teamId: team.value.teamId,
        corpName: team.value.corpName,
        teamName: team.value.name,
        avatars:
          team.value && Array.isArray(team.value.memberList)
            ? team.value.memberList.map((item) => item.avatar || "")
            : [],
      });
      uni.redirectTo({
        url: "/pages/login/login?source=teamInvite",
      });
    }
  } else {
    toast(res?.message || "获取团队信息失败");
  }
}

async function bindTeam() {
  const res = await api('bindWxappWithTeam', { appid, corpId: team.value.corpId, teamId: team.value.teamId, openid: account.value.openid });
  if (!res || !res.success) {
    return toast("关联团队失败");
  }
  const res1 = await api('getWxAppCustomerCount', { miniAppId: account.value.openid, corpId: account.value.corpId, teamId: team.value.teamId });
  if (res1 && res1.data > 0) {
    uni.switchTab({
      url: "/pages/home/home",
    });
  } else {
    uni.redirectTo({
      url: `/pages/archive/edit-archive?teamId=${team.value.teamId}&corpId=${team.value.corpId}`
    })
  }
}

onLoad((options) => {
  const href =
    typeof options.q === "string" ? decodeURIComponent(options.q) : "";
  const [, url = ""] = href.split("?");
  const data = url.split("&").reduce((acc, cur) => {
    const [key, value] = cur.split("=");
    acc[key] = value;
    return acc;
  }, {});
  changeTeam(data);
});
</script>
<style>
.flash-logo {
  width: 200rpx;
  height: 200rpx;
  animation: flash 2.5s infinite;
}

@keyframes flash {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</style>