import { Tab, Tabs } from 'vant';
import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';

import { api_musicGroupFindByCooperationId } from './api';
import ContentItem from './contentItem';
import { IMusicGroup } from './type';
import { listenerMessage } from '@/helpers/native-message';

export default defineComponent({
  name: 'home-page',
  setup() {
    const homeData = reactive({
      /** 乐团列表 */
      musicGroups: [] as IMusicGroup[],
      tab: 'home',
      reloadTotal: 0,
      /** 是否吸顶 */
      isStricky: false
    });
    /** 获取学校乐团列表 */
    const getMusicGroup = async () => {
      const res = await api_musicGroupFindByCooperationId();
      if (Array.isArray(res.data)) {
        homeData.musicGroups = res.data;
      }
    };

    /** 重新加载数据 */
    const reloadData = async () => {
      await getMusicGroup();
      homeData.reloadTotal += 1;
    };

    onMounted(() => {
      getMusicGroup();
      listenerMessage('webViewOnResume', reloadData);
      listenerMessage('stickyTop', (res) => {
        homeData.isStricky = res?.content?.status == 0 ? false : true;
      });
    });
    return () => (
      <div class={styles.home}>
        <Tabs
          v-model:active={homeData.tab}
          class={[styles.homeTab, homeData.isStricky && styles.strickyTop]}
          swipeThreshold={3}
          animated
          swipeable>
          <Tab title="数据汇总" name="home">
            <ContentItem reloadTotal={homeData.reloadTotal} />
          </Tab>
          {homeData.musicGroups.map(group => (
            <Tab title={group.name} name={group.id}>
              <ContentItem
                reloadTotal={homeData.reloadTotal}
                musicGroupId={group.id}
              />
            </Tab>
          ))}
        </Tabs>
      </div>
    );
  }
});
