<script lang="ts" setup name="analysis_classDailyReport">
import studentManageApi from '@/api/studentManage'
import subjectApi from '@/api/subject/subject'
import type { Class } from '@/api/studentManage'
import { subjectColumn, P_TYPE_DAILY, P_GROUP_PERSONAL, UNGROUP_NAME } from './column.tsx'
import { useStudyData } from './hooks/index.ts'
import { only_last_id_value } from '../index.ts'
import router from '@/router/index.ts'
import type { SubjectItem } from '@/api/subject/config'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores/user.ts'
import { only_last_id } from '@/api/only-last.ts'

const props = defineProps<{
  cls: Class
  subject: SubjectItem
}>()
// hooks
const {
  updateTime,
  tableRef,
  xbTable,
  date,
  loading,
  groupList,
  activeGroup,
  typeList,
  activeType,
  showUpdateTime,
  autoUpdate,
  handleHeaderClick,
  changeAuto,
  getSummaries,
} = useStudyData(init)
const { userInfo } = storeToRefs(userStore())

async function init(showLoad = true) {
  const classId = props.cls.classId
  if (!classId) return
  showLoad && (loading.value = true)
  try {
    xbTable.table.column = subjectColumn({ group: activeGroup.value })
    // xbTable.table.data = [];
    // 远程获取排名数据
    let data = (await studentManageApi.getSubjectStudyData(
      {
        subjectId: props.subject.subjectId,
        classId,
        date: activeType.value === P_TYPE_DAILY ? date.value : undefined,
        // 每日-总计
        queryDateType: activeType.value,
        // 个人-小组
        queryType: activeGroup.value,
      },
      {
        [only_last_id]: only_last_id_value,
      },
    )) as any
    await nextTick()
    if (activeGroup.value === P_GROUP_PERSONAL) {
      // 个人
      xbTable.table.data = data.map((i: anyObj) => ({
        ...i,
        id: i.userId,
      }))
    } else {
      // 小组
      let tableData = data.map((i: anyObj) => {
        // 统计平均
        const sum = {} as any
        for (const col of xbTable.table.column) {
          if (col.noAverage) continue
          sum[col.prop] = 0
        }
        i.stuList.reduce((prev: anyObj, next: anyObj) => {
          Object.keys(sum).forEach(key => {
            prev[key] += Number(next[key] || 0)
          })
          return prev
        }, sum)
        const len = i.stuList.length
        const average = {} as any
        for (const col of xbTable.table.column) {
          if (col.noAverage) continue
          average[col.prop] = Number((sum[col.prop] / len).toFixed(2))
        }
        return {
          id: i.groupId,
          name: `${i.groupName || UNGROUP_NAME}`,
          ...average,
          children: i.stuList.map((c: anyObj) => ({
            ...c,
            id: c.userId,
            average,
          })),
        }
      })
      if (tableData.length === 1) {
        tableData = tableData[0].children
      }
      xbTable.table.data = tableData
    }
  } finally {
    loading.value = false
  }
}

function onRowClick(row: any, column: any, event: Event) {
  if (userInfo.value.isTaskStudent) return
  router.push({
    path: '/studyAnalysis',
    query: {
      id: row.id,
      subjectId: props.subject.subjectId,
      subjectName: props.subject.name,
    },
  })
}

watch(
  () => props.cls,
  async () => await init(),
)
</script>

<template>
  <div v-loading="loading" class="stu-mgr-content">
    <div class="student-toolbar">
      <div class="left-items">
        <el-date-picker
          v-if="activeType === 2"
          v-model="date"
          popper-class="filter-date"
          type="date"
          value-format="YYYY-MM-DD"
          :clearable="false"
        />
        <div v-if="showUpdateTime" class="update-time-box" @click="changeAuto">
          <span class="update-time">更新时间：{{ updateTime }}</span>
          <span class="icon-text"
            ><Icon
              class="select-icon"
              :name="autoUpdate ? 'checkbox_checked' : 'checkbox_unchecked'"
              size="48"
            />
            自动更新</span
          >
        </div>
      </div>
      <div class="right-items">
        <SelectTab
          v-model="activeGroup"
          class="filter-tab-item"
          :dataList="groupList"
          round
          type="small"
        ></SelectTab>
        <SelectTab v-model="activeType" :dataList="typeList" round type="small"></SelectTab>
      </div>
    </div>

    <div class="table-box">
      <Table
        ref="tableRef"
        class="page-table"
        height="76.67vh"
        :default-sort="{
          prop: 'learnTime',
          order: 'descending',
        }"
        :pagination="false"
        :summary-method="getSummaries as any"
        show-summary
        @header-click="handleHeaderClick"
        @row-click="onRowClick"
      >
      </Table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@use './index.scss' as *;
</style>
