<template>
  <mj-page class="page">
    <ChildrenBox
      :list="childrenList"
      :showItem="showChildrenInfo"
      @updateShowItem="handleUpdateShowChild"
    />
    <Empty v-if="empty" content="暂无学情报告数据哦~" />
  </mj-page>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import Empty from '@/components/Empty/index.vue'
import ChildrenBox from './components/childrenBox.vue'

import type { ChildrenType } from '@/pages/mine/interface'
import type { SubjectType } from './interface'
import './index.scss'
import { getParentBindChildApi, subjectApi } from '@/api'
import { userStore, bindApplyStore } from '@/store'
import { storeToRefs } from 'pinia'
import db from '@/utils/db'
import hud from '@/utils/hud'

const { userInfo } = storeToRefs(userStore())
const { getApplyBindInfoList } = bindApplyStore()

const childrenList = ref<ChildrenType[]>() // 所有孩子
const empty = ref(false)
const showChildrenInfo = ref<ChildrenType>() // 展示的孩子
const subjectList = ref<SubjectType[]>() // 学科

const chooseSubject = ref<SubjectType>() // 选中学科

async function handleUpdateShowChild(val: ChildrenType) {
  showChildrenInfo.value = val
  chooseSubject.value = {
    name: '',
    pictureUrl: '',
    subject: '',
    subjectId: undefined,
  }
  try {
    hud.loading()
    await getSubject()
  } finally {
    hud.hide()
  }
}
// 学科选择
function tapFilterSubject(i: SubjectType) {
  chooseSubject.value = i
}

// 孩子列表
async function getParentBindChild() {
  const data = await getParentBindChildApi({ parentId: userInfo.value.id, size: -1 })
  empty.value = data.rows?.length ? true : false
  childrenList.value = data.rows
  showChildrenInfo.value = data.rows?.[0]
}
// 学科列表
async function getSubject() {
  if (!showChildrenInfo.value?.gradeId) {
    // hud.error('当前学生无年级,无法查看学情报告')
    subjectList.value = []
    return
  }
  const data = await subjectApi(showChildrenInfo.value.gradeId)
  subjectList.value = data
  chooseSubject.value = data[0]
}
// 处理红点逻辑
async function handleTabBarBadge() {
  await getApplyBindInfoList()
  const hasApplyMsg = db.get('applyBindMsg')

  if (hasApplyMsg) {
    uni.setTabBarBadge({
      index: 3, // "我的"页面在tabBar中的索引
      text: '●',
    })
  } else {
    uni.removeTabBarBadge({
      index: 3,
    })
  }
}

onShow(() => {
  handleTabBarBadge()
})

onMounted(async () => {
  try {
    hud.loading()
    await getParentBindChild()
    await getSubject()
    handleTabBarBadge()
  } finally {
    hud.hide()
  }
})
</script>
