import {
  Transition,
  TransitionGroup,
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import icon_back from './images/icon_back.svg';
import icon_separator from './images/icon_separator.svg';
import {
  NBreadcrumb,
  NBreadcrumbItem,
  NButton,
  NEmpty,
  NImage,
  NSpace,
  NSpin
} from 'naive-ui';
import TheSearch from '/src/components/TheSearch';
import { IMusicItem } from './type';
import icon_arrow from './images/icon_arrow.svg';
import icon_play from './images/icon_play.svg';
import icon_pause from './images/icon_pause.svg';
import icon_goXiaoku from './images/icon_goXiaoku.svg';
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 { 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';
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
    });
    const showGuide = ref(false);
    const userStore = useUserStore();
    let musicsrc = ''
    const getSubjects = async () => {
      const res = await api_subjectList();
      if (Array.isArray(res?.data)) {
        data.tags = [{ name: '全部', id: 0 }, ...res.data];
      }
    };
    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();
    };

    onMounted(async () => {
      getSubjects();
      await getList();
      const obv = new IntersectionObserver(entries => {
        if (entries[0].intersectionRatio > 0) {
          handleResh();
        }
      });
      nextTick(() => {
        obv.observe(spinRef.value);
      });
    });
    /** 查看收藏状态 */
    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}
            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}
          style={{ paddingBottom: data.showPlayer ? '108Px' : '' }}>
          <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}>
                <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
                              width={60}
                              height={60}
                              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',
                    bottom: data.showPlayer ? '154Px' : '46Px'
                  }}
                  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}`;
                    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}
      </div>
    );
  }
});
