import { computed, defineComponent, reactive } from 'vue'
import styles from './index.module.less'
import { Icon, Popup } from 'vant'
import ChoosePartName from './choosePartName'
import state, { togglePlay } from "/src/state";
import qs from 'query-string'
import { getInstrumentName, sortMusical } from "/src/constant/instruments";
import { getQuery } from "/src/utils/queryString";

export const toggleMusicSheet = reactive({
  show: false,
  toggle: (type = true) => {
    toggleMusicSheet.show = type
  },
})

export default defineComponent({
  name: 'ToggleMusicSheet',
  setup() {
    const query = getQuery();

    const partListNames = computed(() => {
      let partList = state.partListNames || []
      partList = partList.filter((item: any) => !item?.toLocaleUpperCase()?.includes('COMMON'))
      const arr =  partList.map((item: any, index: number) => {
        // 该声轨能否被选
        const canselect = state.canSelectTracks.length == 0 || state.canSelectTracks.includes(item) ? true : false
        // console.log(canselect,index)
        const instrumentName = getInstrumentName(item)
        const sortId = sortMusical(instrumentName, index)
        return {
          text: item + (instrumentName ? `(${instrumentName})` : ''),
          value: index,
          sortId,
          canselect
        }
      }).filter((item: any) => item.canselect).sort((a: any, b: any) => a.sortId - b.sortId)
      return arr
    })

    const trackIdx: any = computed(() => {
      if (partListNames && partListNames.value.length) {
        
        const idx = partListNames.value.find((item: any) => item.value == state.partIndex).value
        console.log(3333,idx)
        return idx
      } else {
        return 0
      }
    })

    const switchMusic = (index: number) => {
      if (state.partIndex === index) return
      // 暂停播放
      togglePlay("paused");
      // 销毁播放器
      postMessage({
        api: 'cloudDestroy',
      })
      postMessage({
        api: 'cloudLoading',
        content: {
          show: true,
          type: 'fullscreen',
        },
      })
      const _url =
        location.origin +
        location.pathname +
        '?' +
        qs.stringify({
          ...query,
          behaviorId: sessionStorage.getItem('behaviorId') || '',
          _t: new Date().valueOf(),
          'part-index': index,
        })
      console.log(_url)
      location.href = _url
    }

    return () => (
      <Popup class={styles.popup} v-model:show={toggleMusicSheet.show}>
        <ChoosePartName
          partIndex={trackIdx.value || 0}
          partListNames={partListNames.value}
          onClose={(value) => {
            console.log("🚀 ~ value:", value)
            toggleMusicSheet.show = false
            if (value !== undefined) {
              switchMusic(value)
            }
          }}
        />
      </Popup>
    )
  },
})
