import { Popup } from 'vant'
import { defineComponent, reactive, watch } from 'vue'
import styles from './index.module.less'
import Member from './member'
import Demand from './demand'
import MemberAndDemand from './memberAndDemand'
import { usePageVisibility } from "@vant/use"
import { studentQueryUserInfo } from "/src/page-instrument/api";
import { getMusicSheetDetail } from "/src/utils/baseApi"
import state from "/src/state";

export type IActive = 'member' | 'demand' | 'memberAndDemand'
export const permissionPopup = reactive({
  active: '' as IActive,
  show: false,
  musicId: '' as string | number,
  musicPrice: 0
})

const pageVisibility = usePageVisibility()
watch(pageVisibility, async (value) => {
  if (value === "visible" && permissionPopup.show) {
    permissionPopup.show = false
    const res = await studentQueryUserInfo()
    state.vipType = res.data.vipType
    if (permissionPopup.active === 'member' && (state.vipType === 'VIP' || state.vipType.includes('SVIP'))) {
      permissionPopup.show = false
    }
    if (permissionPopup.show && (permissionPopup.active === 'demand' || permissionPopup.active === 'memberAndDemand')) {
      getMusicSheetDetail(state.examSongId).then(res => {
        if (res?.code === 200) {
          state.musicBuyInfo.buyed = res?.data?.buyed
           // 已经购买
           if(state.musicBuyInfo.buyed){
            permissionPopup.show = false
           }
        }
     })
    }
  }
})

export default defineComponent({
  name: 'ColexiuPermission',
  setup(props, { expose }) {
    const toggle = () => {
      permissionPopup.show = !permissionPopup.show
    }
    expose({
      toggle,
    })
    return () => (
      <Popup
        class={styles.popup}
        v-model:show={permissionPopup.show}
        teleport="body"
        onClosed={() => {
          // 重置 目前 VIP使用的参数
          permissionPopup.musicId = ''
          permissionPopup.musicPrice = 0
        }}
      >
        {permissionPopup.active === 'member' ? (
          <Member />
        ) : permissionPopup.active === 'demand' ? (
          <Demand />
        ) : permissionPopup.active === 'memberAndDemand' ? (
          <MemberAndDemand />
        ) : null}
      </Popup>
    )
  },
})
