import { computed, defineComponent, reactive, toRef, watch, ref } from 'vue'
import styles from './index.module.less'
import { Icon, Popup } from 'vant'
import ChoosePartName from './choosePartName'
import state, { togglePlay, IPlatform, handleGuide } 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";
import { xmlDocRef, downloadXmlStr } from "/src/view/music-score"
import IndexedDBService from "/src/utils/indexedDB";

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)
      return arr
    })

    const partIndexs: any = computed(() => {
      if(state.combinePartIndexs.length > 1){
        return state.combinePartIndexs
      }else{
        return [state.partIndex]
      }
    })

    // 切换的时候存储处理过后的xml
    const storeXmlData = async () => {
      const dbService = new IndexedDBService("MyDatabase", "MyStore");
      await dbService.save({ id: state.examSongId, xmlString: downloadXmlStr.value })
        .then(() => dbService.get(state.examSongId))
        .then((data) => console.log("数据：", data));
    }

    const switchMusic = async (partIndexs: number[]) => {
      const index = partIndexs.join(",") as any
      // 暂停播放
      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,
          'part-name': ''
        })
      // const blob2 = new Blob([downloadXmlStr.value], { type: "text/html" });
      // console.log(_url,xmlDocRef.value,downloadXmlStr.value)
      state.evaluatAudioInitDone = false
      await storeXmlData()
      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
    )


    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.7)'}}>
        <ChoosePartName
          partIndexs={partIndexs.value}
          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>
    )
  },
})
