<script lang="ts" setup name="analysis_classDailyReport">
import studentManageApi from '@/api/studentManage'
import type { Class } from '@/api/studentManage'
import {
  englishDailyColumn,
  englishTotalColumn,
  P_GROUP_PERSONAL,
  P_TYPE_TOTAL,
  UNGROUP_NAME,
} from './column.tsx'
import { useStudyData } from './hooks/index.ts'
import { only_last_id_value } from '../index.ts'
import { subject_english } from '@/api/subject/config'
import router from '@/router/index.ts'
import { only_last_id } from '@/api/only-last.ts'

const props = defineProps<{
  cls: Class
}>()

// hooks
const {
  updateTime,
  handleHeaderClick,
  tableRef,
  xbTable,
  date,
  loading,
  groupList,
  activeGroup,
  typeList,
  activeType,
  showUpdateTime,
  autoUpdate,
  changeAuto,
  getSummaries,
} = useStudyData(init)

async function init(showLoad = true) {
  const classId = props.cls.classId
  if (!classId) return
  showLoad && (loading.value = true)
  try {
    let fn = studentManageApi.getClassTodayLearnData
    // []清空操作必须做，不然cloumn的render只会调用一次
    xbTable.table.data = []
    if (activeType.value === P_TYPE_TOTAL) {
      // 总计
      xbTable.table.column = englishTotalColumn({ group: activeGroup.value })
      fn = studentManageApi.getClassTotalLearnData
    } else {
      // 每日
      xbTable.table.column = englishDailyColumn({ group: activeGroup.value })
    }
    const data = (await fn(
      {
        classId,
        date: date.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((d: any) => ({
        ...d,
        id: d.userId,
      }))
      return
    }

    // 小组
    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
        }
        if (!i.stuList) return {}
        i.stuList.reduce((prev: anyObj, next: anyObj) => {
          Object.keys(sum).forEach(key => {
            prev[key] += next[key]
          })
          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))
        }
        let children = i.stuList.map((c: anyObj) => ({
          ...c,
          id: c.userId,
          average,
        }))
        if (isAbnormal.value) {
          children = children.filter(
            (c: anyObj) => c.wordCount < average.wordCount || c.learnTime < average.learnTime,
          )
        }
        return {
          id: i.groupId,
          name: `${i.groupName || UNGROUP_NAME}`,
          ...average,
          children,
        }
      })
      .filter((i: anyObj) => i.children.length > 0)

    if (tableData.length === 1) {
      tableData = tableData[0].children
    }
    xbTable.table.data = tableData
  } finally {
    loading.value = false
  }
}

// const showAbnormal = computed(() => userInfo.value.isTeacher && activeGroup.value === P_GROUP_GROUP)
const showAbnormal = false
const isAbnormal = ref(false)

// 过滤异常数据
function changeAbnormal() {
  isAbnormal.value = !isAbnormal.value
  init()
}

function onRowClick(row: any, column: any, event: Event) {
  router.push({
    path: '/studyAnalysis',
    query: {
      id: row.id,
      subjectId: subject_english.subjectId,
      subjectName: subject_english.name,
    },
  })
}

function toWordTest() {
  // 去单词测评
  router.push('/subject/learnWord/word-test-class-records')
}

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 v-if="showAbnormal" class="update-time-box" @click="changeAbnormal">
          <span class="icon-text"
            ><Icon
              class="select-icon"
              :name="isAbnormal ? 'checkbox_checked' : 'checkbox_unchecked'"
              size="48"
            />
            显示异常</span
          >
        </div>
      </div>
      <div class="right-items">
        <mj-button thin-font class="status-button" type="primary" @click="toWordTest"
          >单词测评</mj-button
        >
        <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"
        :pagination="false"
        :summary-method="getSummaries as any"
        :default-sort="{
          prop: 'wordGraspCount',
          order: 'descending',
        }"
        show-summary
        @header-click="handleHeaderClick"
        @row-click="onRowClick"
      >
      </Table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@use './index.scss' as *;
</style>
