<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

import { taskMgrService } from '#/api/service/question-bank/task-mgr'
import PaperQuestionItem from '#/components/paper-question-item/index.vue'

import ViewStudents from './viewStudents.vue'

const props = defineProps({
  responseStatus: {
    type: Array,
    default: () => [],
  },
  resourceId: {
    type: String,
    default: '',
  },
  classId: {
    type: String,
    default: '',
  },
  paperId: {
    type: String,
    default: '',
  },
})

const ResponseStatusViewType = ref('table')
// 试卷详情
const paperDetail = ref<any>([])

const rows = computed(() => {
  const list = Array.isArray(props.responseStatus) ? props.responseStatus : []
  return list.map((item: any) => {
    const total = Number(item?.totalNum ?? 0)
    const correct = Number(item?.correctNum ?? 0)
    const error = Number(item?.errorNum ?? 0)
    const rate = Number(item?.correctRate ?? 0)
    const unSubmit = Math.max(total - correct - error, 0)
    return {
      sort: item?.sort ?? '',
      titleId: item?.titleId ?? '',
      correctNum: correct,
      errorNum: error,
      correctRateText: `${(rate * 100).toFixed(0)}%`,
      unSubmitNum: unSubmit,
    }
  })
})

const route = useRoute()
const recordId = computed(
  () => props.resourceId || (route.query as any)?.resourceId || '',
)

const studentDialogVisible = ref(false)
const studentList = ref<any[]>([])
const studentTitle = ref('查看')

// 获取题目得分详情
async function getTitleStudentInfo(row: any, markType: number) {
  console.warn(recordId.value, '-', row.titleId, markType)

  const res = await taskMgrService.getListTitleStudentInfo(
    recordId.value,
    row.titleId,
    markType,
  )
  if (markType === 1) {
    studentTitle.value = '满分学生'
  } else if (markType === 2) {
    studentTitle.value = '非满分学生'
  } else {
    studentTitle.value = '未提交学生'
  }
  const list = Array.isArray(res) ? res : (res?.rows ?? res?.data ?? [])
  studentList.value = list as any[]
  studentDialogVisible.value = true
}

function onCellClick(row: any, column: any) {
  const prop = column?.property
  switch (prop) {
    case 'correctNum': {
      getTitleStudentInfo(row, 1)

      break
    }
    case 'correctRateText':
    case 'sort':
    case 'unSubmitNum': {
      gotoDetailAndScroll(row)

      break
    }
    case 'errorNum': {
      getTitleStudentInfo(row, 2)

      break
    }
    // No default
  }
}

async function gotoDetailAndScroll(row: any) {
  ResponseStatusViewType.value = 'detail'
  await getPaperDetail()
  await nextTick()
  const id = `question-${row.titleId}`
  const el = document.querySelector(`#${id}`)
  el?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}

// 获取试卷详情
async function getPaperDetail() {
  const res = await taskMgrService.getPaperDetail(props.paperId)
  paperDetail.value = res?.schoolPaperTitleVoList ?? []
  // 将作答统计匹配到试卷题目，answerStatus为对象
  paperDetail.value.forEach((item: any) => {
    const titleKey =
      item?.xkwTitle?.titleId ?? item?.titleId ?? item?.xkwTitle?.id ?? item?.id
    const matched = rows.value.find(
      (stat: any) => String(stat.titleId) === String(titleKey),
    )
    item.answerStatus = matched || {}
  })
}

// 监听切换视图类型
watch(
  () => ResponseStatusViewType.value,
  (newVal, oldVal) => {
    if (newVal !== oldVal && newVal === 'detail') {
      getPaperDetail()
    }
  },
)
function getTitleKey(item: any) {
  return item.xkwTitle?.titleId ?? item.titleId ?? item.xkwTitle?.id ?? item.id
}
</script>

<template>
  <div class="title">
    <p style="display: flex; flex: 1; justify-content: center">作答情况</p>

    <el-radio-group
      v-model="ResponseStatusViewType"
      size="large"
      fill="#409eff"
    >
      <el-radio-button label="表格" value="table" />
      <el-radio-button label="试卷详情" value="detail" />
    </el-radio-group>
  </div>
  <div
    style="width: 100vw; margin-top: 16px"
    v-if="ResponseStatusViewType === 'table'"
  >
    <el-table :data="rows" border @cell-click="onCellClick">
      <el-table-column
        prop="sort"
        label="题目序号"
        class-name="pointer-cell"
        sortable
        header-align="center"
        align="center"
      />
      <el-table-column
        prop="correctNum"
        label="满分人数"
        class-name="pointer-cell"
        header-align="center"
        align="center"
      >
        <template #default="{ row }">
          <span class="cell-link" style="color: #67c23a">{{
            row.correctNum
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="errorNum"
        label="非满分人数"
        class-name="pointer-cell"
        header-align="center"
        align="center"
      >
        <template #default="{ row }">
          <span class="cell-link" style="color: #f56c6c">{{
            row.errorNum
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="correctRateText"
        label="得分率"
        class-name="pointer-cell"
        sortable
        header-align="center"
        align="center"
      >
        <template #default="{ row }">
          <span class="cell-link" style="color: #67c23a">{{
            row.correctRateText
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="unSubmitNum"
        label="未提交人数"
        class-name="pointer-cell"
        header-align="center"
        align="center"
      />
    </el-table>
  </div>
  <!-- 试卷详情 -->
  <div v-if="ResponseStatusViewType === 'detail'">
    <div
      v-for="(item, idx) in paperDetail"
      :key="item.titleId"
      class="question-block"
      :id="`question-${getTitleKey(item)}`"
    >
      <div class="question-stats">
        <span class="stats-item">题号：{{ item.sort ?? idx + 1 }}</span>
        <span
          class="stats-item"
          style="cursor: pointer"
          @click="getTitleStudentInfo({ titleId: getTitleKey(item) }, 1)"
        >
          满分人数：
          <span class="cell-link" style="color: #67c23a">
            {{ item.answerStatus?.correctNum ?? 0 }}
          </span>
        </span>
        <span
          class="stats-item"
          style="cursor: pointer"
          @click="getTitleStudentInfo({ titleId: getTitleKey(item) }, 2)"
        >
          非满分人数：
          <span class="cell-link" style="color: #f56c6c">
            {{ item.answerStatus?.errorNum ?? 0 }}
          </span>
        </span>
        <span class="stats-item">
          得分率：{{ item.answerStatus?.correctRateText ?? '0%' }}
        </span>
        <span
          class="stats-item"
          style="cursor: pointer"
          @click="getTitleStudentInfo({ titleId: getTitleKey(item) }, 3)"
        >
          未作答人数:
          <span class="cell-link" style="color: #909399">
            {{ item.answerStatus?.unansweredNum ?? 0 }}
          </span>
        </span>
      </div>
      <template
        v-if="
          Array.isArray(item.xkwTitle?.questionList) &&
          item.xkwTitle.questionList.length
        "
      >
        <PaperQuestionItem
          v-for="question in item.xkwTitle.questionList"
          :key="question.id"
          :index="item.sort ?? idx + 1"
          :question="{ ...question, score: item.score }"
          :preview="true"
        />
      </template>
      <template v-else>
        <PaperQuestionItem
          :index="item.sort ?? idx + 1"
          :question="{ ...item.xkwTitle, score: item.score }"
          :preview="true"
        />
      </template>
    </div>
  </div>

  <ViewStudents
    v-model="studentDialogVisible"
    :title="studentTitle"
    :students="studentList"
  />
</template>

<style scoped>
.title {
  display: flex;
  width: 100%;
  margin-top: 24px;
  margin-bottom: 16px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

:deep(.paper-question-item .preview-toolbar) {
  display: none !important;
}

.question-block {
  position: relative;
  padding: 16px 20px;
  margin: 20px 0 28px;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #e6e8eb;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgb(31 35 40 / 6%);
}

.question-block::before {
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  content: '';
  background: #246cff;
}

.question-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  align-items: center;
  padding: 12px 14px;
  margin: 4px 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2328;
  background-color: #f4f9ff;
  border: 1px solid #dbe8ff;
  border-radius: 8px;
}

.stats-item {
  line-height: 1.6;
}

:deep(.paper-question-item) {
  padding: 6px 8px;
  margin-top: 10px;
  border: 1px dashed #e6e8eb;
  border-radius: 6px;
}

.cell-link {
  cursor: pointer;
}

:deep(.pointer-cell) {
  cursor: pointer;
}
</style>
