<script setup lang="ts">
import { wordTestService } from '@/api/service/word-test'
import type { MjGridEventProps, MjGridProps } from '@/components/mj/mj-table'
import { timeDiff } from '@/utils'
import hud from '@/utils/hud'
import report from '../word-test/report/index.vue'
import { all_rating_options, all_time_options } from '../word-test-records'
import { throttle } from 'lodash-es'
import { useStudentManageStore } from '@/page/student-mgr/store'
import dayjs from '@/plugins/dayjs'

defineOptions({ name: 'WordTestClassRecords' })

const { schoolId, classId } = storeToRefs(useStudentManageStore())

// 班级学校
const schoolClass = ref({
  schoolId: toRaw(schoolId.value),
  classId: toRaw(classId.value),
} as any)

// 时间
const standardTime = ref('')

// 评级
const rating = ref('')

// 姓名
const name = ref('')

// 单词书
const wordBookRef = ref()

// 时间范围
const timeRange = ref([])

// 表格
const gridRef = ref()
const grid = {
  columns: [
    {
      title: '姓名',
      fixed: 'left',
      field: 'displayName',
    },
    {
      field: 'startTime',
      title: '时间',
      // formatter: 'date',
    },
    {
      title: '范围',
      field: 'studyRange',
    },
    {
      title: '词汇数',
      formatter(params) {
        return params.row.graspInfo?.totalNum
      },
    },
    {
      field: 'standardTime',
      title: '限时',
      formatter({ cellValue }) {
        return `${cellValue / 60}m`
      },
    },
    {
      field: 'endTime',
      title: '用时',
      formatter(params) {
        let tag = ''
        const reason = Number(params.row.exitReason)
        if (reason === 1) {
          tag = '超时'
        } else if (reason === 2) {
          tag = '中途退出'
        }
        let res = timeDiff(params.row.startTime, params.row.endTime)
        if (tag) {
          res = `${res}(${tag})`
        }
        return res
      },
    },
    {
      field: 'rating',
      title: '评级',
    },
    {
      title: '奖励',
      slots: {
        default: 'reward',
      },
    },
  ],
  cellClassName(params: any) {
    const field = params.column.field
    if (field === 'endTime') {
      return params.row.timeOutExit ? 'timeout' : undefined
    } else if (field === 'rightNum') {
      const num = params.row.rightNum / params.row.totalNum
      if (num === 1) return 'progress-100'
      if (num === 0) return 'progress-0'
      if (num >= 0.8) return 'progress-80'
      if (num >= 0.6) return 'progress-60'
      return 'progress-1'
    }

    return undefined
  },
  beforeLoadData(params) {
    params.classId = schoolClass.value.classId
    if (standardTime.value) {
      params.standardTime = Number(standardTime.value) * 60
    }
    if (rating.value) {
      params.rating = rating.value
    }
    if (name.value) {
      params.name = name.value
    }
    if (wordBookRef.value?.stage) {
      params.stageId = wordBookRef.value?.stage
    }
    if (wordBookRef.value?.book?.bookId) {
      params.textbookId = wordBookRef.value?.book?.bookId
    }
    if (timeRange.value?.length) {
      const fmt = 'YYYY-MM-DD HH:mm:ss'
      params.startTime = dayjs(timeRange.value[0]).format(fmt)
      params.endTime = dayjs(timeRange.value[1]).format(fmt)
    }
    return params
  },
} as MjGridProps
const gridEvents = {
  cellClick: ({ row }: any) => {
    hud.load({
      task: async () => {
        reportData.value = await wordTestService.getRecordDetail(row.sessionId)
        showReport.value = true
      },
      option: '加载',
      hideSuccess: true,
    })
  },
} as MjGridEventProps

// 是否显示答题报告
const showReport = ref(false)
const reportData = ref({} as any)

watch(
  [
    () => schoolClass.value.classId,
    () => standardTime.value,
    () => timeRange.value,
    () => rating.value,
    () => wordBookRef.value?.stage,
    () => wordBookRef.value?.book?.bookId,
  ],
  () => {
    gridRef.value?.reload()
  },
)
watch(
  [() => name.value],
  throttle(() => {
    gridRef.value?.reload()
  }, 1000),
)

// 更多条件
const showMoreCondition = ref(false)
function moreCondition() {
  showMoreCondition.value = true
}
</script>

<template>
  <div class="word-test-class-records">
    <div class="top">
      <div class="left">
        <BackBar />
        <SchoolClassSelect v-model="schoolClass" />
        <Select v-model="standardTime" :select-list="all_time_options" width="200" />
        <Select v-model="rating" :select-list="all_rating_options" width="200" />
        <el-input v-model="name" class="mj-data-item-input name" placeholder="姓名" clearable />
      </div>
      <div class="right">
        <mj-button class="status-button" type="warn" @click="moreCondition">更多条件</mj-button>
      </div>
    </div>
    <mj-table
      ref="gridRef"
      class="test-table"
      :service="wordTestService"
      :grid="grid"
      :grid-events="gridEvents"
      hide-remove
      hide-search
      hide-toolbar
    >
      <template #reward="{ row }">
        <div v-if="Number(row.bonus['currency'])" class="reward">
          <Icon name="coin" width="48" />
          <span class="num">+{{ row.bonus['currency'] }}</span>
        </div>
        <div v-else>无</div>
      </template>
    </mj-table>
  </div>
  <report v-model="showReport" :data="reportData" />
  <mj-dialog v-model="showMoreCondition" :width="1300" title="更多条件" hide-footer>
    <div class="mj-data-rows">
      <div class="mj-data-row">
        <div class="mj-data-item">
          <span class="mj-data-item-title">范围</span>
          <word-book-selector ref="wordBookRef" />
        </div>
      </div>
      <div class="mj-data-row">
        <div class="mj-data-item">
          <span class="mj-data-item-title">时间</span>
          <mj-date-picker v-model="timeRange" clear-icon="none" />
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss">
.word-test-class-records {
  .timeout .vxe-cell--label {
    color: $error-color;
  }
}
</style>

<style lang="scss" scoped>
.word-test-class-records {
  @include main_bg;
  height: 100%;
  padding: $space-4_h $space-6;
  display: flex;
  flex-direction: column;

  .reward {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;

    .num {
      font-family: $font-text;
    }
  }

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      display: flex;
      align-items: center;
      gap: 2vh;

      .name {
        width: 300px;
      }

      .self-flag {
        :deep(.el-checkbox__label) {
          font-size: 3vh;
        }
      }
    }
  }

  .right {
    display: flex;
    column-gap: 2vh;
    .status-button {
      width: 16vh;
      height: 5vh;
    }
  }

  .test-table {
    margin-top: 2vh;
  }
}
</style>
