import {
  Transition,
  TransitionGroup,
  computed,
  defineComponent,
  reactive
} 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,
  NImage,
  NSpace
} from 'naive-ui';
import TheSearch from '/src/components/TheSearch';
import listData from './data.json';
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 { useRouter } from 'vue-router';
import PlayItem from './component/play-item';
import PlayLoading from './component/play-loading';

export default defineComponent({
  name: 'XiaokuMusic',
  setup() {
    const router = useRouter();
    const data = reactive({
      tags: [
        { name: '全部', id: 0 },
        { name: '竖笛', id: 1 },
        { name: '排箫', id: 2 },
        { name: '口风琴', id: 3 },
        { name: '陶笛', id: 4 },
        { name: '葫芦丝', id: 5 }
      ],
      tagIndex: 0,
      list: listData.rows as unknown as IMusicItem[],
      listActive: 0,
      playState: 'pause' as 'play' | 'pause',
      showPlayer: false
    });

    /** 改变模仿的曲谱 */
    const handleChange = (item: IMusicItem) => {
      const index = data.list.findIndex(_item => _item.id === item.id);
      if (index > -1) {
        data.listActive = index;
      }
    };
    /** 选中的item */
    const activeItem = computed(() => {
      return data.list[data.listActive] || {};
    });

    /** 收藏 */
    const handleFavitor = () => {
      data.list[data.listActive].delFlag = !data.list[data.listActive].delFlag;
    };

    /** 播放曲目 */
    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') => {
      console.log("🚀 ~ type:", type)
      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>一年级上册人教版（2013版）</NBreadcrumbItem>
          </NBreadcrumb>
        </NSpace>
        <div class={styles.wrap}>
          <div class={styles.content}>
            <div class={styles.tools}>
              <div class={styles.tags}>
                <NSpace size={[24, 12]} wrap={false}>
                  {data.tags.map((item, index) => (
                    <NButton
                      round
                      textColor={data.tagIndex === index ? '#fff' : '#000'}
                      color={data.tagIndex === index ? '#198CFE' : '#fff'}
                      onClick={() => (data.tagIndex = index)}>
                      {item.name}
                    </NButton>
                  ))}
                </NSpace>
              </div>
              <TheSearch round />
            </div>

            <div
              class={styles.contentWrap}
              style={{ paddingBottom: data.showPlayer ? '90px' : '' }}>
              <div class={styles.musicList}>
                <div class={styles.wrapList}>
                  {data.list.map((item: IMusicItem, index) => {
                    return (
                      <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}
                            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}>
                            {item.musicSheetName}
                          </div>
                          <div class={styles.titleDes}>{item.composer}</div>
                        </div>
                        <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>
              </div>

              <div class={styles.musicStaff}>
                <div class={styles.musicName}>
                  {activeItem.value.musicSheetName}
                </div>
                <img class={styles.goBtn} src={icon_goXiaoku} onClick={() => {
                    window.open('https://dev.kt.colexiu.com/instrument/');
                }} />
                <div class={styles.favitor} onClick={() => handleFavitor()}>
                  <Transition name="favitor" mode="out-in">
                    {activeItem.value.delFlag ? (
                      <img src={icon_favitorActive} key="1" />
                    ) : (
                      <img src={icon_favitor} key="2" />
                    )}
                  </Transition>
                </div>
                <div class={styles.staffImgs}>
                  <TransitionGroup name="van-fade">
                    {activeItem.value?.firstTone
                      ?.split(',')
                      .map((item, index) => {
                        return <img src={item} key={item} />;
                      })}
                  </TransitionGroup>
                </div>
              </div>
            </div>
          </div>
        </div>
        <PlayItem
          show={data.showPlayer}
          playState={data.playState}
          item={activeItem.value}
          onChange={value => handleChangeAudio(value)}
        />
      </div>
    );
  }
});
