<template>
  <view class="flex flex-col justify-center items-center h-full" @click="copy()">
    <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";
import { normalizeCorpId, normalizeCorpIdFields } from "@/utils/api-base-config";

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



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

function copy() {
  uni.setClipboardData({
    data: opts.value || '暂无内容'
  })
}

function safeDecode(value) {
  try {
    return decodeURIComponent(value);
  } catch (error) {
    return value;
  }
}

function parseInviteOptions(options = {}) {
  const href =
    typeof options.q === "string" ? safeDecode(options.q) : "";
  const [, url = ""] = href.split("?");
  const data = url.split("&").reduce((acc, cur) => {
    if (!cur) return acc;
    const [key, ...valueParts] = cur.split("=");
    if (!key) return acc;
    acc[key] = safeDecode(valueParts.join("=") || "");
    return acc;
  }, {});
  return {
    ...normalizeCorpIdFields(options),
    ...normalizeCorpIdFields(data),
  };
}

async function syncExternalUserRelation({ corpId, externalUserId, corpUserId }) {
  const normalizedCorpId = normalizeCorpId(corpId);
  const currentAccount = account.value || {};
  if (!(normalizedCorpId && externalUserId && currentAccount.openid)) return;
  try {
    const res = await api('syncWxappExternalUserRelation', {
      corpId: normalizedCorpId,
      externalUserId,
      unionid: currentAccount.unionid || '',
      openid: currentAccount.openid,
      corpUserId: corpUserId || '',
    }, false);
    if (!res || !res.success) {
      console.warn('关联 externalUserId 失败:', res && res.message);
    }
  } catch (error) {
    console.warn('关联 externalUserId 异常:', error && error.message ? error.message : error);
  }
}

async function changeTeam({ teamId, corpId, corpUserId, externalUserId, qrid, referenceCustomerId }) {
  const normalizedCorpId = normalizeCorpId(corpId);
  loading.value = true;
  const res = await api("getTeamData", { teamId, corpId: normalizedCorpId, withCorpName: true });
  loading.value = false;
  if (res && res.data) {
    team.value = normalizeCorpIdFields({
      ...res.data,
      corpId: res.data.corpId || normalizedCorpId,
    });
    team.value.corpName = res.data.corpName;
    set('home-invite-team-info', {
      teamId: team.value.teamId,
      corpId: team.value.corpId,
      corpUserId: corpUserId || '',
      externalUserId: externalUserId || '',
      qrid,
      referenceCustomerId: referenceCustomerId || ''
    });
    await login()
    if (account.value && account.value.mobile) {
      bindTeam({ corpUserId, externalUserId })
    } else {
      set("invite-team-info", {
        corpUserId,
        externalUserId,
        qrid,
        referenceCustomerId,
        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({ corpUserId, externalUserId }) {
  const res = await api('bindWxappWithTeam', { appid, corpId: team.value.corpId, teamId: team.value.teamId, openid: account.value.openid });
  if (!res || !res.success) {
    return toast("关联团队失败");
  }
  await syncExternalUserRelation({
    corpId: team.value.corpId,
    externalUserId,
    corpUserId,
  });
  const res1 = await api('getWxAppCustomerCount', { miniAppId: account.value.openid, corpId: team.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?corpUserId=${corpUserId || ''}&teamId=${team.value.teamId}&corpId=${team.value.corpId}`
    })
  }
}

onLoad((options) => {
  if (options.q) {
    opts.value = JSON.stringify(options)
    changeTeam(parseInviteOptions(options));
  } else if (options.type === 'archive' || (options.teamId && options.corpId)) {
    changeTeam(options);
  }

});
</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>
