import { Tab, Tabs } from 'vant';
import { defineComponent, nextTick, 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={1}
          animated
          swipeable
          onChange={() => {
            nextTick(() => {
              const tabRef : HTMLElement = document.querySelector(`.${styles.homeTab} > .van-tabs__wrap .van-tab--active .van-tab__text`)!
              const lineRef : HTMLElement = document.querySelector(`.${styles.homeTab} > .van-tabs__wrap`)!
              if (tabRef && lineRef){
                lineRef.style.setProperty('--line-width', `${tabRef.offsetWidth}px`)
              }
            })
          }}>
          <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>
    );
  }
});
