<script setup lang="ts">
import { userStore, globalStore, taskStore, subjectStore } from '@/stores'
import { storeToRefs } from 'pinia'
import globalApi from '@/api/global'
import { useRouter } from 'vue-router'
import { useAudio } from '@/hooks'
import {
  getLevelProgress,
  $XXL,
  getVersion,
  newPage,
  isStudyMachine,
  isWebEvn,
  isNotStudyMachine,
} from '@/utils'
import { debounce } from 'lodash-es'
import { isShufaAccount, SHUFA_PATH } from '@/page/app/app.ts'
import { useHomeRedPointStore } from '@/stores/home-red-point'
import hud from '@/utils/hud'
import { compareVersions } from 'compare-versions'

defineOptions({
  name: 'Home',
})

const OSS_URL = import.meta.env.VITE_OSS_URL
const coinBg = `url(${OSS_URL}/urm/border_coin.svg) 100%/contain no-repeat`
const diamondBg = `url(${OSS_URL}/urm/border_diamond.svg) 100%/contain no-repeat`
const ipBoy = `${OSS_URL}/urm/ip_boy.png`
const ipGirl = `${OSS_URL}/urm/ip_girl.png`
const homeTask = `${OSS_URL}/urm/home_task.png`
const homeSubject = `${OSS_URL}/urm/home_subject.png`
// const homeUrge = `${OSS_URL}/urm/home_urge.png`
const homeApp = `${OSS_URL}/urm/home_app.png`
const homeEnglish = `${OSS_URL}/urm/home_english.png`
const receiveReward = `${OSS_URL}/sound/receive_reward.mp3`

const router = useRouter()
const homeRedPointStore = useHomeRedPointStore()
const { setRedPointStatus } = homeRedPointStore
const { redPointStatus } = storeToRefs(homeRedPointStore)
const taskData = taskStore()
const { userInfo, workToken } = storeToRefs(userStore())
const { getUserInfo, isFirstBind } = userStore()
const { system, checkUpdate } = globalStore()

const navMain = computed(() => {
  // const { purchasedInspector, nextInspectorCourseDate, conductInspectorPlanId } =
  //     inspectorInfo.value ?? {}
  return [
    {
      id: '2',
      url: homeSubject,
      key: 'subject',
      path: '/subject',
    },
    // {
    //     id: '3',
    //     url: homeUrge,
    //     key: 'urge',
    //     path: '',
    //     show: !isHide.value,
    //     // id: '3',
    //     // url: homeUrge,
    //     // key: 'urge',
    //     // path: conductInspectorPlanId
    //     //     ? '/urge/learning'
    //     //     : purchasedInspector
    //     //       ? '/urge/timetable'
    //     //       : '/urge/service',
    //     // desc: nextInspectorCourseDate && dayjs(nextInspectorCourseDate).format('MM-DD HH:mm'),
    //     // showTip: true,
    // },
    {
      id: '5',
      url: homeTask,
      key: 'task',
      path: '/task',
      showTip: taskData.hasRedPoint,
    },
    {
      id: '6',
      url: homeApp,
      key: 'app',
      path: '/app',
      show: isStudyMachine && !hideApp.value,
    },
    {
      id: '7',
      url: homeEnglish,
      key: 'english',
      path: '/subject/learningArtifact',
    },
  ]
})

const navLeft = computed(() => {
  const hideAppSchools = ['勤智', '德艺', '领航', '黄古']
  // 如果是特定学校的
  const school = userInfo.value.schoolName
  let special = false
  for (const s of hideAppSchools) {
    if (school?.includes(s)) {
      special = true
      break
    }
  }

  const list = [
    {
      id: '1',
      icon: 'nav_mailbox',
      key: 'messageBox',
      showTip: false,
      path: '/system/mailbox',
    },
    {
      id: '2',
      icon: 'nav_activity',
      key: 'activity',
      showTip: false,
      path: '/system/activity',
    },
    // {
    //     id: '3',
    //     icon: 'nav_notice',
    //     key: 'announcement',
    //     showTip: false,
    //     path: '/system/announcement',
    // },
  ]

  if (userInfo.value.isTaskStudent && special) {
    list.push({
      id: '4',
      icon: 'nav_homeWork',
      key: 'homeWork',
      showTip: redPointStatus.value.homeWork,
      path: '/system/homeWork',
    })
  }

  // 配置
  list.push({
    id: '5',
    icon: 'nav_setting',
    key: 'config',
    showTip: false,
    path: '/system/setting',
  })
  return list
})

// 隐藏app

const hideApp = computed(() => {
  // 如果是老师
  if (userInfo.value.isTeacher) {
    return false
  }
  // 如果是学校的学员
  return userInfo.value.isTaskStudent
})

const navBottom = computed(() => {
  const nav = []
  if (userInfo.value.isTeacher) {
    nav.push({
      id: '1',
      icon: 'nav_student',
      name: '学员管理',
      key: '1',
      showTip: false,
      path: '/student-mgr',
    })
  } else if (userInfo.value.isTaskStudent) {
    // 如果有班级id
    nav.push({
      id: '4',
      icon: 'nav_pk.png',
      name: 'PK赛',
      key: '1',
      showTip: false,
      path: '/student-mgr',
    })
  }
  // if (isStudent.value) {
  //     nav.push({
  //         id: '1',
  //         icon: 'nav_interaction',
  //         name: '课堂互动',
  //         key: '1',
  //         showTip: false,
  //         path: '/classroomInteraction'
  //     })
  // }
  nav.push(
    {
      id: '2',
      icon: 'nav_ranking',
      name: '排行榜',
      key: '1',
      showTip: false,
      path: '/ranking',
    },
    {
      id: '3',
      icon: 'nav_analysis',
      name: '学情分析',
      key: '1',
      showTip: false,
      path: '/studyAnalysis',
    },
  )
  return nav
})

const currentLevelProgress = computed(() =>
  getLevelProgress(userInfo.value?.englishSubjectExpLevelVo),
)

async function getPoint() {
  await setRedPointStatus()
  const redPoint = redPointStatus.value as any
  navLeft.value.forEach(i => {
    i.showTip = redPoint[i.key] || false
  })
  navBottom.value.forEach(i => {
    i.showTip = redPoint[i.key] || false
  })
}

// 获取任务图标红点
function getTaskRedPoint() {
  taskData.setStatus()
}

const { selectSubject } = subjectStore()
const handleNav = debounce(
  (data: anyObj) => {
    if (data.key === 'homeWork' && userInfo.value.isTeacher) {
      const path = `${import.meta.env.VITE_TEACHER_ADMIN_URL}?token=${workToken.value.replace('Bearer ', '')}`
      if (isWebEvn) {
        newPage(path)
        // router.push(`/app/link?p=${path}`);
      } else {
        $XXL.openExternalURL(path)
      }
      return
    } else if (data.key === 'english') {
      selectSubject({ id: 4, name: '英语', subject: '英语' })
    }
    router.push(data.path)
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 提升动画
const showAe = ref(false)
const showName = ref('level_up')
const showData = ref({})
const typeToName: anyObj = {
  1: 'medal_baicirumen',
  2: 'medal_qiancidaren',
  3: 'medal_pinxienengshou',
  4: 'medal_pinxiezhixing',
  5: 'medal_baijurumen',
  6: 'medal_qianjurumen',
  7: 'medal_yuedunengshou',
  8: 'medal_yueduzhixing',
}

function handleKnown(data: anyObj) {
  if (showName.value === 'level_up') {
    globalApi.closePopWin(data.id)
    return
  }
  globalApi.updateMedal({
    ids: data.id,
    checkFlag: 1,
  })
}

// 个人中心
function handleToUserPage() {
  router.push({ path: '/system/user' })
}

// 点击个人形象
function clickPhoto() {
  if (isShufaAccount(userInfo.value.account)) {
    // 书法小状元的账号
    router.replace(SHUFA_PATH)
  }
}

let timer: any
onMounted(async () => {
  // 是否首绑
  const isBind = await isFirstBind()
  if (!isBind) {
    router.push('/init')
    return
  }
  timer = setInterval(() => getPoint(), 1000 * 30)
})
onActivated(async () => {
  checkUpdate()
  // if (!gradeData.value.length) initGrade();
  $XXL.setScreenOn(0)
  // 先获取用户信息，再获取红点
  getPoint()
  getTaskRedPoint()

  await getUserInfo()

  // 获取徽章
  await nextTick()
  // 设置任务状态
  // taskData.setStatusData(userInfo.value.taskRewardStatus)
  const medal = userInfo.value.unCheckMedal?.[0]

  if (medal) {
    showName.value = typeToName[medal.medalId]
    showData.value = medal
    showAe.value = true
    useAudio({
      url: receiveReward,
      autoplay: true,
      volume: system.volume.effectsVolume / 100,
    })
    return
  }

  const popNotice = userInfo.value.popNotices?.[0]
  // 暂时忽略多等级提升
  if (popNotice && popNotice.popType === 1) {
    showName.value = 'level_up'
    showData.value = popNotice
    showAe.value = true
    useAudio({
      url: receiveReward,
      autoplay: true,
      volume: system.volume.effectsVolume / 100,
    })
  }
})

onDeactivated(() => {
  clearInterval(timer)
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>
<template>
  <div class="page">
    <div class="main">
      <div class="user-info" @click="handleToUserPage">
        <UserHead size="90" />
        <div class="user-details">
          <div class="user-details-name">{{ userInfo.nickName }}</div>
          <div class="user-details-level">
            <div class="user-details-level-num">
              {{ userInfo?.englishSubjectExpLevelVo?.currentLevelNum }}
            </div>
            <el-progress
              class="user-details-level-progress"
              :percentage="currentLevelProgress"
              color="#4CEA91"
              :show-text="false"
            />
          </div>
        </div>
        <Icon
          class="user-level"
          :name="`vip_level_${userInfo.vipUserInfo?.currentLevelIntVal}`"
          size="100"
        />
        <!-- <Select
            v-model="grade"
            :selectList="gradeData"
            @selectChange="selectChange"
            @click.stop
        ></Select> -->
      </div>
      <div class="nav-left">
        <div v-for="item in navLeft" :key="item.id" class="nav-left-item" @click="handleNav(item)">
          <Icon :name="item.icon" size="120" />
          <Icon v-if="item.showTip" class="warning" name="warning" size="32" />
        </div>
      </div>
      <!-- <div class="user-assets">
        <user-asset-item
          icon="coin"
          :amount="userInfo.currency"
          :bg="coinBg"
          icon-size="80"
          :popover="{
            title: '乐贝',
            icon: 'reward_coin',
          }"
        />
        <user-asset-item
          icon="diamond"
          :amount="userInfo.diamond"
          :bg="diamondBg"
          icon-size="76"
          :popover="{
            title: '钻石',
            icon: 'reward_diamond',
          }"
        />
      </div> -->
      <div class="user-more">
        <div
          v-for="item in navBottom"
          :key="item.id"
          class="user-more-item"
          @click="handleNav(item)"
        >
          <div class="user-more-item-inner">
            <div class="group">
              <Icon class="logo" :name="item.icon" size="120" />
              <div class="text">
                <LineFont :text="item.name" size="40"></LineFont>
              </div>
              <Icon v-if="item.showTip" class="warning" name="warning" size="32" />
            </div>
          </div>
        </div>
      </div>

      <div class="content">
        <!-- <div class="left">
          <div
            class="img"
            :style="{ backgroundImage: `url(${userInfo.sex === 1 ? ipBoy : ipGirl})` }"
            @click="clickPhoto"
          ></div>
        </div> -->
        <div class="right">
          <template v-for="item in navMain" :key="item.id">
            <div v-if="!(item.show === false)" @click="handleNav(item)">
              <img v-if="item" :src="item.url" />
              <Icon v-if="item.showTip" class="warning" name="warning" size="32" />
              <!-- <div v-if="item.desc" class="desc">{{ item.desc }}</div> -->
            </div>
          </template>
        </div>
      </div>
    </div>
    <XStatusDia v-model="showAe" :name="showName" :data="showData" @ok="handleKnown" />
  </div>
</template>
<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  padding: $space-4_h $space-8 $space-6;
  background: $theme-color-bg;

  .main {
    position: relative;
    height: 100%;

    .user-info {
      min-width: 37.83vh;
      height: 10vh;
      border-radius: 6.42vh;
      background: rgba(0, 0, 0, 0.3);
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      padding: 0.67vh;
      color: #fff;
      cursor: pointer;

      .x-user-head {
        margin-left: $space-1;
      }

      .user-details {
        flex: 1;
        margin-left: $space-3;

        &-name {
          font-size: $font-size-7;
          font-family: $font-special;
        }

        &-level {
          display: flex;
          margin-top: $space-1_h;

          &-num {
            font-size: $font-size-1;
            width: auto;
            height: 2.5vh;
            line-height: 2.5vh;
            padding: 0 8px;
            border-radius: 2.5vh;
            background: #a8b8ea;
            text-align: center;
            box-sizing: content-box;
            margin-right: $space-1;
          }

          &-progress {
            flex: 1;

            :deep(.el-progress-bar__outer) {
              height: 1.17vh !important;
              background: rgba(240, 255, 247, 0.85);
            }
          }
        }
      }

      .user-level {
        margin: 0 $space-2;
      }

      // .select-box {
      //     position: absolute;
      //     right: calc((254px + $space-6) * -1);
      // }
    }

    .nav-left {
      width: auto;
      height: auto;
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      align-items: center;
      gap: 4vh;

      &-item {
        position: relative;
        cursor: pointer;

        .warning {
          position: absolute;
          top: 0;
          right: 0;
        }
      }
    }

    .user-assets {
      position: absolute;
      top: $space-2;
      right: 0;
      display: flex;
    }

    .user-more {
      width: auto;
      height: auto;
      right: 0;
      bottom: 0;
      position: absolute;
      display: flex;

      &-item {
        margin-left: $space-3 + 40px;
        background: rgba(0, 0, 0, 0.25);
        border: 0.17vh solid rgba(0, 0, 0, 0.45);
        border-radius: $radius-5;
        cursor: pointer;

        &-inner {
          min-width: 220px;
          width: auto;
          height: 8.33vh;
          position: relative;
          line-height: 8.33vh;
          padding-left: 10vh;
          border: 0.17vh solid rgba(255, 255, 255, 0.65);
          border-radius: $radius-5;

          .group {
            margin: 0 20px;

            .logo {
              position: absolute;
              left: 10px;
              top: -2.5vh;
            }

            .warning {
              position: absolute;
              top: -0.83vh;
              right: -30px;
            }

            .text {
              padding: 0 $space-1;
              height: 8.33vh;
              opacity: 0.85;
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
      }
    }

    .content {
      width: 100%;
      height: 100%;
      padding: 10vh 0 11.67vh 120px;
      display: flex;

      .left {
        width: 600px;
        height: 100%;
        text-align: center;
        position: relative;
        flex-shrink: 0;

        .img {
          width: 800px;
          height: 82vh;
          position: absolute;
          top: -1.67vh;
          right: -120px;
          transform: scale(0.9);
          //pointer-events: none;
          background-size: contain;
          background-position: center;
          background-repeat: no-repeat;
        }
      }

      .right {
        top: 22vh;
        left: 50%;
        width: auto;
        position: absolute;
        display: flex;
        gap: 6vh;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: center;
        transform: translateX(-50%);

        div {
          width: 40vh;
          height: 40vh;
          cursor: pointer;
          position: relative;

          img {
            width: 40vh;
            height: 40vh;
            object-fit: contain;
          }

          .warning {
            position: absolute;
            top: 0;
            right: 0;
          }

          .desc {
            position: absolute;
            bottom: 6vh;
            left: 8px;
            width: 284px;
            height: 4.33vh;
            background: rgba(0, 0, 0, 0.65);
            font-size: $font-size-3;
            line-height: 1.5em;
            color: #4de798;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: $font-cn;
          }
        }
      }
    }
  }
}
</style>
