import request from '@/helpers/request';
import { Tab, Tabs, Image } from 'vant';
import { state as baseState } from '@/state';
import {
  Transition,
  computed,
  defineComponent,
  onMounted,
  reactive
} from 'vue';
import styles from './index.module.less';
import { useRoute, useRouter } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import OHeader from '@/components/o-header';
import OSticky from '@/components/o-sticky';
import OEmpty from '@/components/o-empty';
import CourseItem from '../lessonCourseware/component/CourseItem';
import OLoading from '@/components/o-loading';
import { useEventListener } from '@vant/use';
export default defineComponent({
  name: 'courseList',
  setup() {
    // music | video | onlymusic
    const route = useRoute();
    const router = useRouter();

    const pageType = route.query.type as any;
    let topType = 'music';

    if (pageType !== 'onlymusic') {
      topType = pageType;
    }

    const state = reactive({
      topKey: topType || ('music' as 'music' | 'courseware'),
      list: [] as any,
      show: true,
      actionKey: 0,
      loading: true,
      subjectList: [] as any,
      classList: [] as any,
      titleOpacity: 0
    });

    const FetchList = async () => {
      try {
        const res = await request.get(
          baseState.platformApi + '/sysMusicScoreCategories/queryTree'
        );
        // 在管乐迷后台分部配置已经有显示对应教材，所以不用单独过滤了
        state.list = res.data || [];
        state.show = state.list.length > 0 ? true : false;
      } catch (error) {
        //
      }
    };

    // 课件
    const getList = async () => {
      state.loading = true;
      try {
        const res: any = await request.post(
          baseState.platformApi + `/lessonCourseware/queryLessonCourseware`,
          {
            data: {
              subjectId: state.actionKey ? state.actionKey : null,
              page: 1,
              rows: 999
            }
          }
        );
        const _data = res.data.rows.map((n: any) => {
          return {
            ...n,
            coverImg: n.cover,
            name: n.name,
            id: n.id,
            courseNum: n.courseNum
          };
        });
        state.classList = _data;
      } catch (error) {
        //
      }
      state.loading = false;
    };

    const getSubjectList = async () => {
      try {
        const res = await request.get(
          baseState.platformApi +
            '/lessonCourseware/getLessonCoursewareSubjectList'
        );

        state.subjectList = res.data || [];
      } catch {
        //
      }
    };

    const _initClassroom = async () => {
      try {
        await getSubjectList();
        const studentSubjectIds =
          baseState.platformType === 'TEACHER'
            ? baseState.user.data.subjectId
            : baseState.user.data.student.subjectIdList;
        const id = studentSubjectIds ? studentSubjectIds.split(',')[0] : 0;
        state.subjectList.forEach((subject: any) => {
          if (Number(id) === subject.id) {
            state.actionKey = Number(id);
          }
        });

        await getList();
      } catch (e) {
        //
        console.log(e, 'e');
      }
      state.loading = false;

      // 获取默认数据
      postMessage(
        {
          api: 'getCoursewareSelectResult'
        },
        (res: any) => {
          if (res?.content) {
            console.log(res?.content);
            baseState.max = res.content.max;
            baseState.vIds = res.content.coursewareIds || [];
            return;
          }
        }
      );
    };

    const onChangeTopTabs = () => {
      if (state.topKey === 'music') {
        //
        if (state.list.length <= 0) {
          FetchList();
        }
      } else if (state.topKey === 'courseware') {
        if (state.subjectList.length <= 0 || state.classList.length <= 0) {
          _initClassroom();
        }
      }
    };

    useEventListener('scroll', () => {
      const height =
        window.scrollY ||
        window.pageYOffset ||
        document.documentElement.scrollTop;
      state.titleOpacity = height > 100 ? 1 : height / 100;
    });

    onMounted(async () => {
      //
      if (state.topKey === 'music') {
        FetchList();
      } else {
        _initClassroom();
      }
    });

    const actions = computed(() => {
      const _list = state.subjectList.map((item: any) => {
        return {
          id: item.id,
          name: item.name,
          text: item.name,
          value: item.id
        };
      });
      _list.unshift({
        id: '',
        name: '课程类型',
        text: '全部',
        value: 0
      });
      return _list;
    });

    const toDetail = (item: any) => {
      const childLength = item.sysMusicScoreCategoriesList
        ? item.sysMusicScoreCategoriesList.length
        : 0;
      // 如果二级分类只有一个分类，则直接跳转到曲目列表
      sessionStorage.setItem(
        'musicScoreList',
        JSON.stringify(item.sysMusicScoreCategoriesList)
      );
      if (childLength > 1) {
        router.push({
          path: '/classify',
          query: {
            parentId: item.id, // 父级元素编号
            ...route.query
          }
        });
      } else {
        router.push({
          path:
            '/music-list/' +
            (childLength == 1
              ? item.sysMusicScoreCategoriesList[0]?.id
              : item.id),
          query: {
            ...route.query
          }
        });
      }
    };

    const handleClick = (item: any) => {
      router.push({
        path: '/classroom-detail',
        query: {
          id: item.lessonCoursewareId
        }
      });
    };
    return () => (
      <div class={styles.choiseHomework}>
        <OSticky position="top">
          <OHeader
            border={false}
            background="transparent"
            color="#131415"></OHeader>

          {pageType !== 'onlymusic' && (
            <div class={styles.topTabs}>
              <Tabs
                border={false}
                v-model:active={state.topKey}
                onClickTab={(val: any) => {
                  state.topKey = val.name;
                  onChangeTopTabs();
                }}>
                <Tab title="云练习" name="music"></Tab>
                <Tab title="云课堂" name="courseware"></Tab>
              </Tabs>

              {state.topKey === 'courseware' && (
                <Tabs
                  class={styles.classroomTab}
                  v-model:active={state.actionKey}
                  shrink
                  onClickTab={(val: any) => {
                    state.actionKey = val.name;
                    getList();
                  }}>
                  {actions.value.map((item: any) => (
                    <Tab title={item.text} name={item.value}></Tab>
                  ))}
                </Tabs>
              )}
            </div>
          )}
        </OSticky>
        <div
          class={[
            styles.container,
            state.topKey === 'courseware' ? styles.containerClass : '',
            pageType === 'onlymusic' ? styles.containerClassOnly : ''
          ]}>
          {state.topKey === 'music' ? (
            <Transition name="van-fade">
              <div class={styles.items}>
                {state.show ? (
                  state.list.map((item: any) => (
                    <div key={item.id} onClick={() => toDetail(item)}>
                      <div class={styles.inner}>
                        <Image src={item.coverImg} class={styles.img} />
                      </div>
                    </div>
                  ))
                ) : (
                  <OEmpty tips="暂无数据" />
                )}
              </div>
            </Transition>
          ) : (
            <>
              <Transition name="van-fade">
                {!state.loading &&
                  Object.values(state.classList).length > 0 && (
                    <CourseItem
                      // term={key}
                      list={state.classList}
                      onItemClick={row => handleClick(row)}
                    />
                  )}
              </Transition>
              {state.loading && <OLoading />}

              {!state.loading && !Object.values(state.classList).length && (
                <div
                  style={{
                    minHeight: `calc(100vh - var(--header-height))`,
                    display: 'flex',
                    alignItems: 'center'
                  }}>
                  <OEmpty tips="暂无课件" />
                </div>
              )}
            </>
          )}
        </div>
      </div>
    );
  }
});
