<template>
  <page-loading v-if="loading && teams.length === 0" />
  <full-page v-else-if="teams.length && team" class="home-container" :pageStyle="pageStyle">
    <!-- <template #header> -->
    <team-head :team="team" :customers="customers" :teams="teams" @changeTeam="changeTeam" />
    <!-- </template> -->
    <view class="home-section home-section--first">
      <customer-archive ref="archiveRef" :corpId="corpId" :corpUserIds="corpUserIds"
        :referenceCustomerIds="referenceCustomerIds" :team="team" @update:customers="handleCustomersUpdate" />
    </view>
    <view class="home-section">
      <team-guide :team="team" />
    </view>
    <view class="home-section">
      <consult ref="consultRef" :corpId="corpId" :teamId="team.teamId" :team="team" :customers="customers" />
    </view>
    <!-- <view class="home-section">
      <team-mate :team="team" />
    </view> -->
    <view class="home-section">
      <article-list :team="team" />
    </view>
  </full-page>
  <yc-home v-else />
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { onLoad, onShow, onShareAppMessage } from "@dcloudio/uni-app";
// import useGuard from "@/hooks/useGuard";
import useAccount from "@/store/account";
import api from "@/utils/api";
import { toast } from "@/utils/widget";
import { get, remove, set } from "@/utils/cache";
import { normalizeCorpId } from "@/utils/api-base-config";

import FullPage from "@/components/full-page.vue";
import articleList from "./article-list.vue";
import consult from "./consult.vue";
import customerArchive from "./customer-archive.vue";
import teamHead from "./team-head.vue";
import teamGuide from "./team-guide.vue";
// import teamMate from "./team-mate.vue";
import ycHome from "./yc-home.vue";
import pageLoading from "./loading.vue";

// const { useLoad, useShow } = useGuard();
const { account } = storeToRefs(useAccount());
const { login, getTeams } = useAccount();
const env = __VITE_ENV__;
const shareAppVersion = env.MP_SHARE_WX_APP_VERSION;

const team = ref(null);
const teams = ref([]);
const loading = ref(false);
const customers = ref([]);
const consultRef = ref(null);
const archiveRef = ref(null);
const corpUserIds = ref({});
const referenceCustomerIds = ref({});
const HOME_CURRENT_TEAM_CACHE_KEY = "home-current-team-info";

const corpId = computed(() => team.value?.corpId);

// UI 两段式背景：顶部 281px 渐变 + 下方纯色（按 375 设计稿，281px ≈ 562rpx）
const pageStyle =
  "background: linear-gradient(180deg, #065BD6 15.05%, #F6FAFA 95.37%) 0 0/100% 562rpx no-repeat, #F6FAFA;";

function handleCustomersUpdate(newCustomers) {
  customers.value = newCustomers;
}

function getTeamIdentity(source = {}) {
  return {
    teamId: source.teamId || "",
    corpId: normalizeCorpId(source.corpId || ""),
  };
}

function cacheCurrentTeam(currentTeam) {
  if (!currentTeam || !currentTeam.teamId) return;
  set(HOME_CURRENT_TEAM_CACHE_KEY, getTeamIdentity(currentTeam));
}

function isSameTeam(candidate, target = {}) {
  const targetTeamId = target.teamId || "";
  if (!candidate || !candidate.teamId || candidate.teamId !== targetTeamId) return false;

  const targetCorpId = normalizeCorpId(target.corpId || "");
  if (!targetCorpId) return true;

  const teamCorpId = normalizeCorpId(candidate.corpId || "");
  return targetCorpId === teamCorpId;
}

async function changeTeam({ teamId, corpId, corpName }) {
  loading.value = true;
  const res = await api("getTeamData", { teamId, corpId });
  loading.value = false;
  if (res && res.data) {
    team.value = {
      ...res.data,
      corpId: normalizeCorpId(res.data.corpId || corpId),
    };
    team.value.corpName = corpName;
    cacheCurrentTeam(team.value);
  } else {
    toast(res?.message || "获取团队信息失败");
  }
}

async function getMatchTeams(inviteTeam = null) {
  loading.value = true;
  teams.value = await getTeams();
  const inviteIdentity = typeof inviteTeam === "string" ? { teamId: inviteTeam } : (inviteTeam || {});
  const cachedIdentity = get(HOME_CURRENT_TEAM_CACHE_KEY) || {};
  const targetIdentity = getTeamIdentity({
    teamId: inviteIdentity.teamId || team.value?.teamId || cachedIdentity.teamId,
    corpId: inviteIdentity.corpId || team.value?.corpId || cachedIdentity.corpId,
  });
  const validTeam = teams.value.find(i => isSameTeam(i, targetIdentity));
  const firstTeam = teams.value[0]
  if (validTeam || firstTeam) {
    changeTeam(validTeam || firstTeam);
  } else {
    team.value = null;
  }
  loading.value = false;
}

// useLoad((opts) => {
//   if (opts.teamId) {
//     team.value = { teamId: opts.teamId, corpId: opts.corpId };
//   }
// });

onLoad(() => {
  if (!account.value) login();
})

onShow(async () => {
  if (!account.value) await login();
  const inviteTeam = get('home-invite-team-info');
  remove('home-invite-team-info');
  if (inviteTeam && inviteTeam.teamId && inviteTeam.corpUserId) {
    corpUserIds.value[inviteTeam.teamId] = inviteTeam.corpUserId;
  }
  if (inviteTeam && inviteTeam.teamId && inviteTeam.referenceCustomerId) {
    referenceCustomerIds.value[inviteTeam.teamId] = inviteTeam.referenceCustomerId;
  }
  if (account.value && account.value.openid) {
    getMatchTeams(inviteTeam && inviteTeam.teamId ? inviteTeam : null);
  } else {
    teams.value = [];
  }
  if (consultRef.value && typeof consultRef.value.getBadgeCount === 'function') {
    consultRef.value.getBadgeCount()
  }
  if (archiveRef.value && typeof archiveRef.value.getCustomers === 'function') {
    archiveRef.value.getCustomers()
  }
});

onShareAppMessage((res) => {
  if (team.value && team.value.supportPatientForward === 'YES') {
    const customer = customers.value[0];
    const referenceCustomerId = customer ? customer._id : '';
    return {
      title: `【${team.value.name}】这个团队不错，推荐给你！`,
      type: shareAppVersion || 0, // 0 正式版本 | 1 开发版本 | 2 体验版本
      path: `/pages/login/redirect-page?teamId=${team.value.teamId}&corpId=${team.value.corpId}&type=archive&referenceCustomerId=${referenceCustomerId}`
    }
  }
})

watch(account, (n, o) => {
  if (n && !o) {
    getMatchTeams();
  } else if (!n && o) {
    teams.value = [];
  }
})


</script>
<style scoped>
.home-container {
  min-height: 100vh;
}

.home-section {
  margin-top: 24rpx;
}

.home-section--first {
  margin-top: 0;
}
</style>
