import { computed, defineComponent, reactive, toRef, watch } from 'vue'
import styles from './index.module.less'
import { Icon, Popup } from 'vant'
import ChoosePartName from './choosePartName'
import state, { togglePlay, IPlatform } from "/src/state";
import qs from 'query-string'
import { getInstrumentName, sortMusical } from "/src/constant/instruments";
import { getQuery } from "/src/utils/queryString";
import useDrag from "/src/view/plugins/useDrag/index";
import Dragbom from "/src/view/plugins/useDrag/dragbom";
import { setGuidance } from "/src/page-instrument/custom-plugins/guide-page/api";
import { storeData } from "/src/store";

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)
      // 不需要自定义排序，改为按照xml声轨顺序显示
      // .sort((a: any, b: any) => a.sortId - b.sortId)
      // 支持总谱渲染的时候 加上总谱字段
      state.isScoreRender && arr.unshift({canselect:true, sortId:999, text: "总谱", value: 999})
      return arr
    })

    const trackIdx: any = computed(() => {
      if (partListNames && partListNames.value.length) {
        
        const idx = partListNames.value.find((item: any) => item.value == state.partIndex)?.value || 0
        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',
        },
      })
      // 存储当前 模式
      localStorage.setItem("musicScorePlayType", `${state.playType},${state.playSource}`)
      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
    }

    const parentClassName = "switchBoxClass_drag";
    const userId = storeData.user?.id ? String(storeData.user?.id) : '';
    const positionInfo = state.platform !== IPlatform.PC ? {
      styleDrag: { value: null }
    } : useDrag(
      [
        `${parentClassName} .top_draging`,
        `${parentClassName} .bom_drag`
      ],
      parentClassName,
      toRef(toggleMusicSheet, 'show'),
      userId
    )

    // 完成拖动弹窗引导页
    const handleGuide = async () => {
      state.guideInfo.teacherDrag = true;
			try{
				const res = await setGuidance({guideTag:'guideInfo',guideValue:JSON.stringify(state.guideInfo)})
      }catch(e){
        console.log(e)
      }   
    }

    return () => (
      <Popup v-model:show={toggleMusicSheet.show} class="popup-custom van-scale center-closeBtn switchBoxClass_drag" transition="van-scale" teleport="body" style={positionInfo.styleDrag.value} overlay-style={{background:'rgba(0, 0, 0, 0.3)'}}>
        <ChoosePartName
          partIndex={trackIdx.value || 0}
          partListNames={partListNames.value}
          onClose={(value) => {
            console.log("🚀 ~ value:", value)
            toggleMusicSheet.show = false
            if (value !== undefined) {
              switchMusic(value)
            }
          }}
        />
        { state.platform === IPlatform.PC && <Dragbom showGuide={!state.guideInfo?.teacherDrag} onGuideDone={handleGuide}  /> }
      </Popup>
    )
  },
})
