import {
  Transition,
  TransitionGroup,
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import icon_back from './images/icon_back.png';
import icon_separator from './images/icon_separator.png';
import {
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NEmpty,
  NImage,
  NModal,
  NSpace,
  NSpin
} from 'naive-ui';
import TheSearch from '/src/components/TheSearch';
import { IMusicItem } from './type';
import icon_arrow from './images/icon_arrow.png';
import icon_play from './images/icon_play.png';
import icon_pause from './images/icon_pause.png';
import icon_goXiaoku from './images/icon_goXiaoku.png';
import icon_favitor from '/src/common/images/icon-collect-default.png';
import icon_favitorActive from '/src/common/images/icon-collect-active.png';
import icon_default from './images/icon_default.png';
import icon_close from './images/icon-close.png';
import { useRoute, useRouter } from 'vue-router';
import PlayItem from './component/play-item';
import PlayLoading from './component/play-loading';
import TheNoticeBar from '/src/components/TheNoticeBar';
import {
  api_materialFavorite,
  api_materialFavoriteStatus,
  api_musicSheetPage,
  api_subjectList
} from '../xiaoku-ai/api';
import { useUserStore } from '/src/store/modules/users';
import Musicguide from '@/custom-plugins/guide-page/music-guide';
import TheEmpty from '/src/components/TheEmpty';
import { state } from '/src/state';
import { useResizeObserver } from '@vueuse/core';
export default defineComponent({
  name: 'XiaokuMusic',
  setup() {
    const user = useUserStore();
    const route = useRoute();
    const router = useRouter();
    const forms = reactive({
      page: 1,
      rows: 20,
      status: true,
      name: '', // 关键词
      musicSheetCategoriesId: route.query.id || ''
    });
    const data = reactive({
      loading: false,
      finshed: false,
      reshing: false,
      tags: [] as any[],
      tagIndex: 0,
      list: [] as unknown as IMusicItem[],
      listActive: 0,
      playState: 'pause' as 'play' | 'pause',
      showPlayer: false,
      previewModal: false,
      showPreivew: false,
      previewUrl: '',
      showCloseBtn: true
    });
    const showGuide = ref(false);
    const userStore = useUserStore();
    let musicsrc = '';
    const getSubjects = async () => {
      // const res = await api_subjectList();
      // if (Array.isArray(res?.data)) {
      const subjectList = sessionStorage.getItem('musicSubjectList')
        ? JSON.parse(sessionStorage.getItem('musicSubjectList') as any)
        : [];
      data.tags = [{ name: '全部', id: 0 }, ...subjectList];
      // }
    };
    const getList = async () => {
      data.loading = true;
      let res = {} as any;
      try {
        res = await api_musicSheetPage({
          ...forms,
          musicSubject: data.tagIndex ? data.tagIndex : ''
        });
      } catch (error) {
        console.log(error);
      }
      if (data.reshing) {
        data.list = [];
        data.reshing = false;
      }
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        data.list = [...data.list, ...res.data.rows];
        data.finshed = res.data.rows.length < forms.rows;
        console.log('🚀 ~ data.finshed:', data.finshed);
      }
      if (data.list[data.listActive]) {
        getFavitor(data.list[data.listActive]);
      }
      data.loading = false;
      setTimeout(() => {
        showGuide.value = true;
      }, 500);
    };

    const handleGetList = () => {
      data.listActive = 0;
      data.showPlayer = false;
      data.playState = 'pause';
      forms.page = 1;
      data.finshed = false;
      getList();
    };
    const spinRef = ref();
    const handleResh = () => {
      console.log(data.finshed);
      if (data.loading || data.finshed) return;
      forms.page = forms.page + 1;
      getList();
    };

    // ifram事件处理
    const iframeHandle = (ev: MessageEvent) => {
      if (ev.data?.api === 'api_fingerPreView') {
        data.showCloseBtn = !ev.data.state;
      }
    };

    onMounted(async () => {
      // musicList-container
      useResizeObserver(
        document.querySelector('.musicList-container') as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          console.log(height, 'height - 11');
          document.documentElement.style.setProperty(
            '--xiaoku-music-height',
            height + 'px'
          );
        }
      );

      getSubjects();
      await getList();
      const obv = new IntersectionObserver(entries => {
        if (entries[0].intersectionRatio > 0) {
          handleResh();
        }
      });
      nextTick(() => {
        obv.observe(spinRef.value);
      });
      window.addEventListener('message', iframeHandle);
    });
    onUnmounted(() => {
      window.removeEventListener('message', iframeHandle);
    });
    /** 查看收藏状态 */
    const getFavitor = async (item: any) => {
      const res = await api_materialFavoriteStatus({
        type: 'MUSIC',
        materialId: item.id
      });
      if (res?.code === 200) {
        item.favitor = res.data;
      }
    };

    /** 改变模仿的曲谱 */
    const handleChange = (item: IMusicItem) => {
      const index = data.list.findIndex(_item => _item.id === item.id);
      if (index > -1) {
        data.listActive = index;
      }
      getFavitor(item);
    };
    /** 选中的item */
    const activeItem = computed(() => {
      if (data.list[data.listActive]) {
        const origin = /(localhost|192)/.test(location.host)
          ? 'https://dev.kt.colexiu.com'
          : location.origin;
        console.log(
          data.list[data.listActive].xmlFileUrl,
          'data.list[data.listActive]'
        );
        musicsrc = `${origin}/instrument?modelType=practise&id=${
          data.list[data.listActive].xmlFileUrl
        }&Authorization=${userStore.getToken}/#/preview`;
      } else {
        musicsrc = '';
      }

      return data.list[data.listActive] || {};
    });

    /** 收藏曲谱 */
    const handleFavitor = () => {
      data.list[data.listActive].favitor = !data.list[data.listActive].favitor;
      api_materialFavorite({
        favoriteFlag: data.list[data.listActive].favitor,
        type: 'MUSIC',
        materialId: data.list[data.listActive].id
      });
    };

    /** 播放曲目 */
    const handlePlay = (item: IMusicItem) => {
      const index = data.list.findIndex(_item => _item.id === item.id);
      if (index > -1) {
        if (data.listActive === index) {
          data.playState = data.playState === 'play' ? 'pause' : 'play';
        } else {
          data.playState = 'play';
        }
        data.showPlayer = true;
        data.listActive = index;
      }
    };

    /** 音频控制 */
    const handleChangeAudio = (
      type: 'play' | 'pause' | 'pre' | 'next' | 'favitor'
    ) => {
      if (type === 'play') {
        data.playState = 'play';
      } else if (type === 'pause') {
        data.playState = 'pause';
      } else if (type === 'pre') {
        if (data.list[data.listActive - 1]) {
          handlePlay(data.list[data.listActive - 1]);
        }
      } else if (type === 'next') {
        if (data.list[data.listActive + 1]) {
          handlePlay(data.list[data.listActive + 1]);
        }
      } else if (type === 'favitor') {
        handleFavitor();
      }
    };
    return () => (
      <div class={styles.container}>
        <NSpace align="center" wrapItem={false} size={16}>
          <img
            style={{ cursor: 'pointer' }}
            src={icon_back}
            class={styles.iconBack}
            onClick={() => router.push({ path: '/xiaoku-ai' })}
          />
          <NBreadcrumb separator="">
            <NBreadcrumbItem
              onClick={() => router.push({ path: '/xiaoku-ai' })}>
              全部列表
            </NBreadcrumbItem>
            <img class={styles.separator} src={icon_separator} />
            <NBreadcrumbItem>{route.query.name}</NBreadcrumbItem>
          </NBreadcrumb>
        </NSpace>
        <div class={[styles.wrap, data.showPlayer ? styles.wrapBottom : '']}>
          <div class={styles.content}>
            <div class={styles.tools}>
              <NSpace
                style={{ width: '100%' }}
                size={[24, 12]}
                wrapItem={false}>
                <div
                  {...{
                    id: 'music-0'
                  }}>
                  <NSpace
                    style={{ width: '100%' }}
                    size={[24, 12]}
                    wrapItem={false}>
                    {data.tags.map(item => (
                      <NButton
                        round
                        textColor={data.tagIndex === item.id ? '#fff' : '#000'}
                        color={data.tagIndex === item.id ? '#198CFE' : '#fff'}
                        onClick={() => {
                          data.tagIndex = item.id;
                          data.reshing = true;
                          handleGetList();
                        }}>
                        {item.name}
                      </NButton>
                    ))}
                  </NSpace>
                </div>
              </NSpace>
              <TheSearch
                style={{ marginLeft: 'auto' }}
                round
                border={false}
                onSearch={val => {
                  forms.name = val;
                  data.reshing = true;
                  handleGetList();
                }}
              />
            </div>

            <div class={styles.contentWrap}>
              <div class={[styles.musicList, 'musicList-container']}>
                <div class={styles.wrapList}>
                  {data.list.map((item: IMusicItem, index) => {
                    return (
                      <div class={styles.itemContainer}>
                        <div
                          class={[
                            styles.item,
                            data.listActive === index && styles.active
                          ]}
                          onClick={() => handleChange(item)}>
                          <div class={styles.img}>
                            <NImage
                              lazy
                              objectFit="cover"
                              previewDisabled={true}
                              src={item.titleImg || icon_default}
                              onLoad={e => {
                                (e.target as any).dataset.loaded = 'true';
                              }}
                            />
                            <PlayLoading
                              class={[
                                data.listActive === index &&
                                data.playState === 'play'
                                  ? ''
                                  : styles.showPlayLoading
                              ]}
                            />
                          </div>
                          <div class={styles.title}>
                            <div class={styles.titleName}>
                              <TheNoticeBar text={item.musicSheetName} />
                            </div>
                            <div class={styles.titleDes}>{item.composer}</div>
                          </div>
                          {index == 0 ? (
                            <NButton
                              color="#259CFE"
                              textColor="#fff"
                              {...{ id: 'music-1' }}
                              round
                              class={styles.btn}
                              type="primary"
                              onClick={(e: Event) => {
                                e.stopPropagation();
                                handlePlay(item);
                              }}>
                              试听
                              <img
                                src={
                                  data.listActive === index &&
                                  data.playState === 'play'
                                    ? icon_pause
                                    : icon_play
                                }
                              />
                            </NButton>
                          ) : (
                            <NButton
                              color="#259CFE"
                              textColor="#fff"
                              round
                              class={styles.btn}
                              type="primary"
                              onClick={(e: Event) => {
                                e.stopPropagation();
                                handlePlay(item);
                              }}>
                              试听
                              <img
                                src={
                                  data.listActive === index &&
                                  data.playState === 'play'
                                    ? icon_pause
                                    : icon_play
                                }
                              />
                            </NButton>
                          )}

                          <img class={styles.arrow} src={icon_arrow} />
                        </div>
                      </div>
                    );
                  })}
                  {!data.finshed && (
                    <div ref={spinRef} class={styles.loadingWrap}>
                      <NSpin show={true}></NSpin>
                    </div>
                  )}
                  {!data.loading && data.list.length === 0 && (
                    <div class={styles.empty}>
                      <TheEmpty></TheEmpty>
                    </div>
                  )}
                </div>
              </div>

              <div class={styles.musicStaff}>
                <div class={styles.musicName}>
                  {activeItem.value.musicSheetName}
                </div>
                <img
                  id="music-2"
                  style={{
                    display: activeItem.value.id ? '' : 'none'
                  }}
                  class={[styles.goBtn]}
                  src={icon_goXiaoku}
                  onClick={() => {
                    handleChangeAudio('pause');
                    const origin = /(localhost|192)/.test(location.host)
                      ? 'https://test.lexiaoya.cn'
                      : location.origin;
                    const src = `${origin}/instrument?platform=pc&showGuide=true&id=${activeItem.value.id}&Authorization=${user.getToken}`;
                    if (
                      window.matchMedia('(display-mode: standalone)').matches
                    ) {
                      state.application = window.matchMedia(
                        '(display-mode: standalone)'
                      ).matches;
                      data.previewModal = true;
                      data.previewUrl = src;
                      data.showPreivew = false;
                    } else {
                      window.open(src);
                    }
                  }}
                />
                <div
                  style={{ display: activeItem.value.id ? '' : 'none' }}
                  class={styles.favitor}
                  onClick={() => handleFavitor()}>
                  <Transition name="favitor" mode="out-in">
                    {activeItem.value.favitor ? (
                      <img src={icon_favitorActive} key="1" />
                    ) : (
                      <img src={icon_favitor} key="2" />
                    )}
                  </Transition>
                </div>
                <div class={styles.staffImgs}>
                  <TransitionGroup name="van-fade">
                    {activeItem.value?.musicSvg ||
                    activeItem.value?.musicImg ? (
                      (activeItem.value?.musicSvg || activeItem.value?.musicImg)
                        ?.split(',')
                        .map((item, index) => {
                          return <img src={item} key={item} />;
                        })
                    ) : (
                      <TheEmpty></TheEmpty>
                    )}
                  </TransitionGroup>
                </div>
              </div>
            </div>
          </div>
        </div>
        {data.list.length !== 0 && (
          <PlayItem
            show={data.showPlayer}
            playState={data.playState}
            item={activeItem.value}
            onChange={value => handleChangeAudio(value)}
          />
        )}
        {showGuide.value ? <Musicguide></Musicguide> : null}

        <NModal
          v-model:show={data.previewModal}
          onUpdate:show={(val: any) => {
            if (!val) {
              data.previewUrl = '';
            }
          }}
          class={styles.previewWindow}
          showIcon={false}
          displayDirective="show">
          <NSpin show={data.showPreivew} style="--n-opacity-spinning: 1;">
            <img
              style={{ display: data.showCloseBtn ? '' : 'none' }}
              src={icon_close}
              class={styles.previewClose}
              onClick={() => {
                data.previewModal = false;
                data.previewUrl = '';
              }}
            />

            <iframe
              class={styles.previewIframe}
              onLoad={() => {
                data.showPreivew = false;
              }}
              frameborder="0"
              src={data.previewUrl}></iframe>
          </NSpin>
        </NModal>
      </div>
    );
  }
});
