import { usePageVisibility } from '@vant/use'
import { watch } from 'vue'
import AppState from '/src/state'
import detailState from '/src/pages/detail/state'
import request from '/src/helpers/request'
import { useOriginSearch } from '.'
import { permissionPopup } from '../popups/permission/permission'
import { browser, getRequestHostname } from '/src/helpers/utils'
const search = useOriginSearch()

const browserInfo = browser()

export type ClientType = 'student' | 'teacher' | 'web'

export const useClientType = (): ClientType => {
  const search = useOriginSearch()
  // console.log("🚀 ~ search", search)
  if (search.client) return (search.client as ClientType)
  /**
   * pathname 不可能是student ｜ teacher
   */
  let pathnameStudent = location.pathname.indexOf('/orchestra-student/') === 0 || browserInfo.isStudent
  let pathnameTeacher = location.pathname.indexOf('/orchestra-teacher/') === 0 || browserInfo.isTeacher
  if (pathnameStudent) {
    return 'student'
  }
  if (pathnameTeacher) {
    return 'teacher'
  }
  return 'web'
}

// 除学生短外，其他平台无视会员权限信息
const MemberDefaultData = {
  membershipDays: 1,
}

export const useUpdateMember = () => {
  const prefix = getRequestHostname()
  request
    .get(`/musicSheet/detail/${search.id}`, {
      prefix: prefix,
    })
    .then((res) => {
      if (detailState.activeDetail) {
        detailState.activeDetail.orderStatus = res.data.orderStatus
        detailState.activeDetail.play = res.data.play
      }
    })
}

export const useUser = () => {
  const status = usePageVisibility()

  const getUser = async () => {
    try {
      const client = useClientType()
      if (client === 'student') {
        const { data } = await request.get('/appLoginUser/getUserInfo')
        AppState.user = data
      }
      if (client === 'teacher') {
        const { data } = await request.get('/appLoginUser/getUserInfo', {
          prefix: '/api-teacher',
        })
        AppState.user = {
          ...MemberDefaultData,
          ...data,
        }
      }
      if (client === 'web') {
        AppState.user = {
          ...MemberDefaultData,
        }
      }
    } catch (error) {}
  }

  getUser()

  watch(status, async (value) => {
    permissionPopup.show = false
    if (value === 'visible' && AppState.user?.membershipDays === 0) {
      getUser()
    }
    if (value === 'visible' && detailState.activeDetail?.orderStatus !== 'PAID') {
      useUpdateMember()
    }
  })
}
