<template>
  <page-loading v-if="loading" />
  <full-page v-else-if="teams.length && team">
    <template #header>
      <team-head :team="team" :teams="teams" @changeTeam="changeTeam" />
      <view class="pb-10"></view>
    </template>
    <customer-archive :corpId="corpId" :team="team" @update:customers="handleCustomersUpdate" />
    <consult :corpId="corpId" :teamId="team.teamId" :customers="customers" />
    <team-mate :team="team" />
    <article-list :team="team" />
  </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);

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('queryWxJoinedTeams', { 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>
