import { defineComponent, onMounted, reactive, ref } from 'vue'
import '../../vue-tsx-shim.d'
import '../../app.d'
import { useRoute } from 'vue-router'
import { useClientType, useOriginSearch } from './uses'
import request from '/src/helpers/request'
import { browser, getPlatform, getRequestHostname } from '/src/helpers/utils'
import HomeIndex from './index'
import Empty from '/src/components/empty'
import styles from './index.module.less'
import { postMessage, promisefiyPostMessage } from '/src/helpers/native-message'
import { storeData } from './state'

let startTime = Date.now()
let timer = null as any
const initBehaviorId = '' + Date.now()
/** 学生端记录在云教练里面的时长 */
const recordTotalTime = () => {
  const client = useClientType()
  if (client == 'web') return
  const search = useOriginSearch()
  const prefix = getRequestHostname()
  const totalTime = (Date.now() - startTime) / 1000
  startTime = Date.now()
  // 如果累计时间是负数,就不记录
  if (totalTime < 0){
    return
  }

  //课后训练
  if (search.lessonTrainingId) {
    const browserInfo = browser()
    request.post('/studentLessonTraining/lessonTrainingRecord', {
      prefix: prefix,
      requestType: 'json',
      data: {
        materialType: 'SONG',
        record: {
          clientType: (client as string)?.toLocaleUpperCase(),
          practiceSource: 'LESSON_TRAINING',
          feature: 'PRACTICE',
          deviceType: browserInfo.android ? 'ANDROID' : browserInfo.isApp ? 'IOS' : 'WEB',
          behaviorId: initBehaviorId,
          playTime: totalTime,
          musicSheetId: search.id,
        },
        courseScheduleId: search.courseScheduleId,
        lessonTrainingId: search.lessonTrainingId,
        materialId: search.materialId,
      },
    })
  } else {
    request.post('/musicPracticeRecord/save', {
      prefix: prefix,
      requestType: 'json',
      data: {
        musicSheetId: search.id,
        sysMusicScoreId: search.id,
        feature: 'PRACTICE',
        practiceSource: 'PRACTICE',
        playTime: totalTime,
        deviceType: getPlatform(),
        behaviorId: initBehaviorId,
      },
    })
  }
}

/**退出时,记录时长 */
export const sendBackRecordTotalTime = () => {
  clearInterval(timer)
  recordTotalTime()
}
/**用户信息 */
export const userInfo = reactive({
  id: '',
  /**会员天数 */
  membershipDays: 0,
  /**是否有订单记录 */
  purchaseMemberRecord: false,
  /**是否会员 */
  vipMember: false,
  phone: null,
})
export const renderError = ref(false)
export default defineComponent({
  setup() {
    const getUserInfo = async () => {
      // 验证token
      const token = sessionStorage.getItem('Authorization')!
      if (!token) {
        const res = await promisefiyPostMessage({ api: 'getToken' })
        if (res?.content?.accessToken) {
          sessionStorage.setItem('Authorization', res.content.tokenType + ' ' + res.content.accessToken)
        }
      }

      try {
        const res: any = await request.get(`/user/getUserInfo`)
        Object.assign(userInfo, res?.data || {})
        if(res.data?.clientType){
          storeData.platformType = res.data.clientType
        }
      } catch (error) {
        console.log(error)
        renderError.value = true
        // @ts-ignore
        window.isLoading = false
        postMessage({
          api: 'cloudLoading',
          content: {
            show: false,
            type: 'fullscreen',
          },
        })
      }
    }

    onMounted(() => {
      // 进入页面设置常量
      postMessage({
        api: 'keepScreenLongLight',
        content: {
          isOpenLight: true,
        },
      })      
      getUserInfo()
      clearInterval(timer)
      timer = setInterval(() => {
        recordTotalTime()
      }, 60 * 1000)
    })

    return () => (
      <>
        {!!userInfo.id && (
          <>
            <HomeIndex />
          </>
        )}
        {/* 加载错误 */}
        {renderError.value && (
          <div class={styles.errorWrap}>
            <Empty />
          </div>
        )}
      </>
    )
  },
})
