import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  computed,
  watch
} from 'vue';
import { useRoute } from 'vue-router';
import request from '@/helpers/request';
import MEmpty from '@/components/m-empty';
import styles from './index.module.less';
import musicBg from '../../image/music_bg.png';
import pBg from '../../image/plh.png';
import titleIcon1 from '../../image/title_icon1.png';
import titleIcon2 from '../../image/title_icon2.png';
import playIcon from '../../image/music_play_icon.png';
import pauseIcon from '../../image/music_pause_icon.png';
import emptyIcon from '../../image/ins-empty-icon.png';
import songIcon from '../../image/song_icon.png';
import { NoticeBar } from 'vant';
import PlayItem from '../play-item';
import PlayLoading from '../play-loading';

export default defineComponent({
  name: 'InstrumentInfo',
  props: {
    id: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'select'],
  setup(props, { emit }) {
    const route = useRoute();
    const initDone = ref(false);
    const forms = reactive({
      detailId: route.query.detailId,
      loading: false,
      dataInfo: {} as any,
      musicList: [] as any,
      title: ' ',
      playState: 'pause' as 'play' | 'pause',
      showPlayer: false,
      listActive: 0,
    });
    /** 选中的item */
    const activeItem = computed(() => {
      return forms.musicList[forms.listActive] || {};
    });

    const getDetail = async () => {
      forms.loading = true;
      try {
        const { data } = await request.get(
          '/edu-app/knowledgeWiki/detail/' + props.id
        );
        data.intros = data.intros.replace(
          /<video/gi,
          '<video class="video-music" style="width: 100% !important;" controlslist="nodownload" poster="https://oss.dayaedu.com/ktqy/1701759849244.png"'
        );
        forms.dataInfo = data || {};
        forms.musicList = data.knowledgeWikiResources.map((item: any) => {
          return {
            id: item.id,
            name: item.name,
            url: item.url
          };
        });
      } catch {}
      forms.loading = false;
    };

    /** 播放曲目 */
    const handlePlay = (item: any) => {
      if (!initDone.value) initDone.value = true
      const index = forms.musicList.findIndex(
        (_item: any) => _item.id === item.id
      );
      if (index > -1) {
        if (forms.listActive === index) {
          forms.playState = forms.playState === 'play' ? 'pause' : 'play';
        } else {
          forms.playState = 'play';
        }
        forms.showPlayer = true;
        forms.listActive = index;
      }
    };
    /** 音频控制 */
    const handleChangeAudio = (
      type: 'play' | 'pause' | 'pre' | 'next' | 'favitor'
    ) => {
      if (type === 'play') {
        forms.playState = 'play';
      } else if (type === 'pause') {
        forms.playState = 'pause';
      } else if (type === 'pre') {
        if (forms.musicList[forms.listActive - 1]) {
          handlePlay(forms.musicList[forms.listActive - 1]);
        }
      } else if (type === 'next') {
        if (forms.musicList[forms.listActive + 1]) {
          handlePlay(forms.musicList[forms.listActive + 1]);
        }
      }
    };

    watch(
      () => props.show,
      val => {
        if (val) {
          // onToggleAudio();
        } else {
          //  audioRef.value.pause();
          //  data.playState = 'pause';
          handleChangeAudio('pause');
          try {
            // 暂停视频
            const doms = document.querySelectorAll('.video-music');
            if (doms && doms.length > 0) {
              doms.forEach((dom: any) => {
                dom.pause();
              });
            }
          } catch {
            //
          }
        }
      }
    );

    onMounted(async () => {
      await getDetail();
    });
    return () => (
      <div
        class={[styles.knowledgeBg, forms.showPlayer ? styles.wrapBottom : '']}>
        <div class={styles.left}>
          {props.type === 'wiki' && (
            <div class={styles.insTop}>
              <div class={styles.imgSection}>
                <img
                  class={styles.img}
                  src={forms.dataInfo.avatar || musicBg}
                />
                <div class={styles.pan}>
                  <img src={forms.dataInfo.avatar || musicBg} />
                </div>
              </div>
              {/* <div class={styles.songName}>{forms.dataInfo.name || '--'}</div>    */}
              <NoticeBar
                text={forms.dataInfo.name}
                color="#000"
                class={styles.songName}
                delay={1.5}
                background="none"
              />
              <div class={styles.songWords}>
                {forms.dataInfo.lyricists && (
                  <span>作词：{forms.dataInfo.lyricists}</span>
                )}
                {forms.dataInfo.composers && (
                  <span>作曲：{forms.dataInfo.composers}</span>
                )}
              </div>
            </div>
          )}
          {props.type === 'instrument' && (
            <div class={styles.insTop}>
              <img src={forms.dataInfo.avatar || pBg} />
              <div class={styles.insName}>{forms.dataInfo.name || ''}</div>
              <div class={styles.insTro}>
                {forms.dataInfo.knowledgeWikiCategories?.[0]?.knowledgeWikiCategoryTypeName || ''}
              </div>
            </div>
          )}
          {props.type === 'musician' && (
            <div class={styles.insTop}>
              <img class={styles.musician} src={forms.dataInfo.avatar || pBg} />
              <div class={styles.insName}>{forms.dataInfo.name || ''}</div>
              <div class={styles.insTro}>
                {forms.dataInfo.knowledgeWikiCategories?.[0]?.knowledgeWikiCategoryTypeName || ''}
              </div>
            </div>
          )}
          <div class={styles.songColumn}>
            <img src={songIcon} />
            <span>{props.type === 'wiki' ? '名曲鉴赏' : '代表作'}</span>
          </div>
          <div class={styles.insList}>
            {forms.musicList.length > 0 && (
              <>
                {forms.musicList.map((item: any, index: number) => {
                  return (
                    <div
                      class={[styles.li, initDone.value && forms.listActive === index ? styles.liActive : '']}
                      onClick={(e: Event) => {
                        e.stopPropagation();
                        handlePlay(item);
                      }}>
                      <div class={styles.liBg}>
                        <img src={musicBg} />
                        <div class={[forms.listActive === index && forms.playState === 'play' ? styles.playingIcon : styles.hidePlayLoading]}>
                          <PlayLoading /> 
                        </div>
                      </div>
                      {/* <div class={styles.liName}>{item.name || '--'}</div> */}
                      <NoticeBar
                        text={item.name}
                        color="#131415"
                        class={styles.liName}
                        delay={1.5}
                        background="none"
                      />
                      {/* <img
                        class={styles.liPlay}
                        src={
                          forms.listActive === index &&
                          forms.playState === 'play'
                            ? pauseIcon
                            : playIcon
                        }
                      /> */}
                    </div>
                  );
                })}
              </>
            )}

            {forms.musicList.length <= 0 && forms.loading && (
              <div class={styles.emptyBox}>
                <img src={emptyIcon} />
                <span>暂无曲目～</span>
              </div>
            )}
          </div>
        </div>
        <div class={styles.right}>
          <div class={styles.title}>
            <img
              class={styles.liBg}
              src={props.type === 'musician' ? titleIcon2 : titleIcon1}
            />
            {props.type === 'wiki'
              ? '名曲故事'
              : props.type === 'instrument'
              ? '乐器简介'
              : props.type === 'musician'
              ? '个人简介'
              : ''}
          </div>
          <div class={styles.desc} v-html={forms.dataInfo.intros}></div>
          {!forms.loading && !forms.dataInfo.intros && (
            <MEmpty description="暂无内容" />
          )}
        </div>

        {forms.musicList.length !== 0 && (
          <PlayItem
            show={forms.showPlayer}
            playState={forms.playState}
            item={activeItem.value}
            onChange={value => handleChangeAudio(value)}
          />
        )}
      </div>
    );
  }
});
