import { computed, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import { browser, vaildMusicScoreUrl } from '@/helpers/utils';
import MSticky from '@/components/m-sticky';
import MHeader from '@/components/m-header';
import { useRouter } from 'vue-router';
import MSearch from '@/components/m-search';
import { Cell, Image, List, Popup } from 'vant';
import iconPlayer from './images/icon-player.png';
import { api_musicSheetCategoriesPage, api_musicSheetPage } from '../co-ai/api';
import { state as baseState } from '@/state';
import { useEventListener, useWindowScroll } from '@vueuse/core';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import { postMessage } from '@/helpers/native-message';

export default defineComponent({
  name: 'hot-music-more',
  setup() {
    const router = useRouter();
    const state = reactive({
      background: 'transparent',
      loading: false,
      finished: false,
      searchPopup: false,
      musics: [] as any,
      types: [] as any,
      subjectList: [] as any,
      sMSCI: '',
      sMII: ''
    });

    const musicForms = reactive({
      page: 1,
      rows: 20,
      status: 1,
      keyword: '', // 关键词
      musicSheetCategoriesId: '',
      musicalInstrumentId: ''
    });

    const getMusicList = async () => {
      state.loading = true;
      try {
        const res = await api_musicSheetPage({
          ...musicForms
        });
        if (res.code === 200 && Array.isArray(res?.data?.rows)) {
          state.musics = [...state.musics, ...res.data.rows];
          state.finished = !res.data.next;
          musicForms.page = res.data.current + 1;
          // state.listState.dataShow = state.list.length > 0;
        } else {
          state.finished = true;
        }
      } catch (error) {
        // console.log('🚀 ~ error:', error);
      }
      state.loading = false;
    };

    const getSubjecList = async () => {
      try {
        let subjectIds = baseState.user.data?.subjectId || '';
        subjectIds = subjectIds.split(',');
        const subjectId = subjectIds[0] || '';
        const res = await request.post('/edu-app/subject/list', {
          enableFlag: true,
          delFlag: 0,
          page: 1,
          subjectId: subjectId || '',
          rows: 999
        });

        if (subjectId) {
          const result = res.data || [];
          let tempSubjects: any = [];
          result.forEach((item: any) => {
            const instruments = item.instruments || [];
            if (Number(subjectId) === item.id && instruments.length > 0) {
              instruments.forEach((child: any, index: number) => {
                tempSubjects.push({
                  text: child.name,
                  value: child.id,
                  className: index === 0 ? 'selected' : ''
                });
              });
            }
          });

          if (tempSubjects.length > 0) {
            state.subjectList = [{ text: '全部', value: '' }, ...tempSubjects];
            // musicForms.musicalInstrumentId = tempSubjects[0].value;
          }
        }
        // console.log(state.subjectList, state.subjectItem);
      } catch {
        //
      }
    };

    /** 获取音乐教材列表 */
    const getMusicSheetCategories = async () => {
      try {
        let subjectIds = baseState.user.data?.subjectId || '';
        subjectIds = subjectIds.split(',');
        const subjectId = subjectIds[0] || '';
        const res = await api_musicSheetCategoriesPage({
          page: 1,
          rows: 999
          // subjectId: subjectId
          // musicTagIds: route.query.musicTagId ? [route.query.musicTagId] : []
        });
        if (res.code === 200 && Array.isArray(res?.data?.rows)) {
          const temp: any = [];
          res.data.rows.forEach((item: any) => {
            temp.push({
              value: item.id,
              text: item.name
            });
          });
          state.types = temp;
        }
      } catch (error) {
        console.log('🚀 ~ error:', error);
      }
    };

    const onDetail = (item: any) => {
      let src = `${vaildMusicScoreUrl()}/instrument/?id=${
        item?.id
      }&showGuide=true`;
      postMessage({
        api: 'openAccompanyWebView',
        content: {
          url: src,
          orientation: 0,
          isHideTitle: true,
          statusBarTextColor: false,
          isOpenLight: true,
          c_orientation: 0 // 0 横屏 1 竖屏
        }
      });
    };

    // 判断是否有数据
    const isSearch = computed(() => {
      return state.subjectList.length > 2 || state.types.length > 0
        ? true
        : false;
    });

    onMounted(async () => {
      // useEventListener(document, 'scroll', () => {
      //   const { y } = useWindowScroll();
      //   if (y.value > 32) {
      //     state.background = '#fff';
      //   } else {
      //     state.background = 'transparent';
      //   }
      // });
      state.loading = true;
      // await getSubjecList();
      await getMusicSheetCategories();
      getMusicList();
    });
    return () => (
      // sortType： 2
      <div
        class={[
          styles.hotMusicMore,
          browser().isTablet ? styles.hotMusicMoreTablet : ''
        ]}>
        <MSticky position="top">
          <MHeader border={false} background={'transparent'}>
            {{
              content: () => (
                <div class={styles.woringHeader}>
                  <i
                    onClick={() => {
                      if (browser().isApp) {
                        postMessage({
                          api: 'goBack'
                        });
                      } else {
                        router.back();
                      }
                    }}
                    class={[
                      'van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow',
                      styles.leftArrow
                    ]}></i>
                  <span class={styles.title}>
                    <i></i>
                  </span>
                </div>
              )
            }}
          </MHeader>

          <MSearch
            // background={state.background}
            background={'transparent'}
            onSearch={(val: any) => {
              musicForms.keyword = val;
              musicForms.page = 1;
              state.musics = [];
              state.finished = false;
              getMusicList();
            }}>
            {{
              left: () =>
                isSearch.value && (
                  <div
                    class={[
                      styles.searchContent,
                      state.searchPopup && styles.active
                    ]}
                    onClick={() => {
                      state.sMSCI = musicForms.musicSheetCategoriesId;
                      state.sMII = musicForms.musicalInstrumentId;
                      state.searchPopup = true;
                    }}>
                    <span>筛选</span>
                    <i></i>
                  </div>
                )
            }}
          </MSearch>
        </MSticky>

        <List
          loading={state.loading}
          finished={state.finished}
          finishedText=" "
          onLoad={getMusicList}
          immediateCheck={false}>
          {state.musics.length > 0 && (
            <div class={styles.musicList}>
              {state.musics.map((item: any) => (
                <Cell
                  class={styles.musicItem}
                  border={false}
                  center
                  onClick={() => onDetail(item)}>
                  {{
                    icon: () => (
                      <Image class={styles.musicImg} src={item.titleImg} />
                    ),
                    title: () => (
                      <div class={styles.musicContnet}>
                        <h2>{item.musicSheetName}</h2>
                        {item.composer && <p>{item.composer}</p>}
                      </div>
                    ),
                    'right-icon': () => (
                      <Image class={styles.musicPlayIcon} src={iconPlayer} />
                    )
                  }}
                </Cell>
              ))}
            </div>
          )}
        </List>

        {!state.loading && state.musics.length === 0 && (
          <div class={styles.emptyGroup}>
            <MEmpty description="暂无曲谱" />
          </div>
        )}

        <Popup position="bottom" round v-model:show={state.searchPopup}>
          <div class={styles.searchContainer}>
            <div class={styles.searchHead}>
              <span
                class={styles.cancel}
                onClick={() => (state.searchPopup = false)}>
                取消
              </span>
              <span>筛选</span>
              <span
                class={styles.confirm}
                onClick={() => {
                  musicForms.musicSheetCategoriesId = state.sMSCI;
                  musicForms.musicalInstrumentId = state.sMII;
                  state.searchPopup = false;
                  musicForms.page = 1;
                  state.musics = [];
                  state.finished = false;
                  getMusicList();
                }}>
                确定
              </span>
            </div>

            <div class={styles.changeSubjectContainer}>
              {/*
                {state.subjectList.length > 2 && (
                <>
                  <div class={styles.title}>乐器</div>
                  <div class={styles.subjectContainer}>
                    {state.subjectList.map((subject: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          subject.value === state.sMII && styles.active
                        ]}
                        onClick={() => {
                          state.sMII = subject.value;
                        }}>
                        {subject.text}
                      </div>
                    ))}
                  </div>
                </>
              )}
              */}

              {state.types.length > 0 && (
                <>
                  <div class={styles.title}>曲谱教材</div>
                  <div
                    class={[
                      styles.subjectContainer,
                      styles.subjectContainerTwo
                    ]}>
                    <div
                      class={[
                        styles.subjectItem,
                        state.sMSCI === '' && styles.active
                      ]}
                      onClick={() => {
                        state.sMSCI = '';
                      }}>
                      全部
                    </div>
                    {state.types.map((item: any) => (
                      <div
                        class={[
                          styles.subjectItem,
                          item.value === state.sMSCI && styles.active
                        ]}
                        onClick={() => {
                          state.sMSCI = item.value;
                        }}>
                        {item.text}
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
