import { computed, defineComponent, reactive } from 'vue'
import styles from './index.module.less'
import { Icon, Popup } from 'vant'
import ChoosePartName from './choosePartName'
import state from '/src/pages/detail/state'
import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
import qs from 'query-string'
import { useOriginSearch } from '../../uses'
import { getInstrumentName } from '../../helpers/instruments'

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

export default defineComponent({
  name: 'ToggleMusicSheet',
  setup() {
    const search = useOriginSearch()

    const partListNames = computed(() => {
      let partList = state.activeDetail?.background || []
      partList = partList.filter((item: any) => !item.track?.toLocaleUpperCase()?.includes('COMMON'))
      return partList.map((item: any, index: number) => {
        const instrumentName = getInstrumentName(item.track)
        return {
          text: item.track + (instrumentName ? `(${instrumentName})` : ''),
          value: index,
        }
      }).filter(Boolean)
    })

    const switchMusic = (index: number) => {
      // 暂停播放
      RuntimeUtils.pause()
      // 销毁播放器
      postMessage({
        api: 'cloudDestroy',
      })
      postMessage({
        api: 'cloudLoading',
        content: {
          show: true,
          type: 'fullscreen',
        },
      })
      const _url =
        location.origin +
        location.pathname +
        '?' +
        qs.stringify({
          ...search,
          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={state.partIndex}
          partListNames={partListNames.value}
          onClose={(value) => {
            console.log("🚀 ~ value:", value)
            toggleMusicSheet.show = false
            if (value !== undefined) {
              switchMusic(value)
            }
          }}
        />
      </Popup>
    )
  },
})
