<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" :teams="teams" @changeTeam="changeTeam" />
    </template>
    <view class="home-section home-section--first">
      <customer-archive :corpId="corpId" :team="team" @update:customers="handleCustomersUpdate" />
    </view>
    <view class="home-section">
      <consult :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 useGuard from "@/hooks/useGuard";
import useAccount from "@/store/account";
import api from "@/utils/api";
import { toast } from "@/utils/widget";

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 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 team = ref(null);
const teams = ref([]);
const loading = ref(true);
const customers = ref([]);

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

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;
    team.value.corpName = corpName;
  } else {
    toast(res?.message || "获取团队信息失败");
  }
}

async function getTeams() {
  loading.value = true;
  const res = await api('getWxappRelateTeams', { openid: account.value.openid });
  teams.value = res && Array.isArray(res.data) ? res.data : [];
  const validTeam =
    teams.value.find(
      (item) => team.value && item.teamId === team.value.teamId
    ) || teams.value[0];
  if (validTeam) {
    changeTeam(validTeam);
    return;
  } else {
    team.value = null;
  }
  loading.value = false;
}

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

useShow(() => {
  getTeams();
});
</script>
<style scoped>
.home-container {
  min-height: 100vh;
}

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

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