<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 NewTestDialog from './new-test-dialog/index.vue'

defineOptions({ name: 'WordTestRecords' })

// 是否显示答题报告
const showReport = ref(false)
const reportData = ref({} as any)
// 是否显示开始测试弹框
const showTest = ref(false)

const carouselKey = ref(0)

const gridRef = ref()
const grid = {
  columns: [
    {
      title: '姓名',
      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) {
        if (params.row.timeOutExit) {
          return '超时'
        }
        return timeDiff(params.row.startTime, params.row.endTime)
      },
    },
    {
      field: 'rating',
      title: '评级',
    },
    {
      title: '奖励',
      slots: {
        default: 'reward',
      },
    },
    {
      title: '提升指南',
      fixed: 'right',
      slots: {
        default: 'improve',
      },
    },
  ],
  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
  },
} 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 backTitle = computed(() => (wordBookRef.value?.nav === nav_stage ? '单词测评' : ''))
const backTitle = computed(() => '单词测评')

// 新的测试
function newTest() {
  showTest.value = true
}

// 定时获取最新的记录
let latestTimer = null as any
// 数据
const latestRecords = ref([] as any[])
async function getLatestRecords() {
  const newData = await wordTestService.getLatestRecords()
  if (!newData?.length) return
  if (latestRecords.value.length) {
    if (newData[0].sessionId === latestRecords.value[0].sessionId) return
  }
  latestRecords.value = newData
  carouselKey.value++
}

// 获取激励的文字
function getLatestEncourage(record: any) {
  if (record.rating === 'SSSSS') {
    return '秀翻全场！'
  }
  if (record.rating.includes('S')) {
    return '真是太秀了！'
  }
  if (record.rating === 'A') {
    return '好样的！'
  }
  if (record.rating === 'D') {
    return '加把劲哦！'
  }
  return '继续加油！'
}

onMounted(() => {
  getLatestRecords()
  latestTimer = setInterval(
    () => {
      getLatestRecords()
    },
    1000 * 5 * 10,
  )
})

onUnmounted(() => {
  clearInterval(latestTimer)
})
</script>

<template>
  <div class="word-test-records">
    <div class="top">
      <div class="left">
        <BackBar :leftText="backTitle" />
      </div>
      <div class="right">
        <el-carousel
          v-if="latestRecords?.length"
          :key="carouselKey"
          ref="carouselRef"
          class="latest-record"
          direction="vertical"
          :interval="4000"
          :autoplay="true"
        >
          <el-carousel-item v-for="item in latestRecords" :key="item">
            <div class="latest-record-item">
              <span>【</span>
              <span class="time">{{ item.startTime }}</span>
              <span>】</span>
              <span class="name">{{ item.redactionDisplayName }}</span>
              <span>挑战《</span>
              <span class="stage">{{ item.studyRange }}</span>
              <span>》测试，获得</span>
              <span class="rating">{{ item.rating }}</span>
              <span>评级！</span>
              <span>{{ getLatestEncourage(item) }}</span>
            </div>
          </el-carousel-item>
        </el-carousel>
        <mj-button class="status-button" type="warn" @click="newTest">新的测试</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>
      </template>
    </mj-table>

    <new-test-dialog v-model="showTest" />
  </div>
  <report v-model="showReport" :data="reportData" />
</template>

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

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

  .mj-data-item {
    .nickname {
      flex: 1;
    }
  }

  .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;

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

  .right {
    display: flex;
    flex: 1;
    column-gap: 4vh;
    padding-left: 4vh;
    justify-content: flex-end;
    .status-button {
      width: 16vh;
      height: 5vh;
    }

    .latest-record {
      flex: 1;
      height: 5vh;
      background-color: #fff;
      border-radius: 2vh;

      :deep(.el-carousel__item) {
        .latest-record-item {
          height: 5vh;
          display: flex;
          align-items: center;
          justify-content: center;

          .name {
            color: $success-color;
          }

          .time {
            color: $success-color;
          }

          .stage {
            color: $success-color;
          }

          .rating {
            color: $success-color;
          }
        }
      }
    }
  }

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