<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { usePrecision } from '@vueuse/math'
import type { ReportItem } from '../types'
import { submitScore } from '../api'

defineProps<{ reportList: ReportItem[] }>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const detail = $ref<any>(inject('detail'))
let tableList = $ref<any>([])
watchEffect(() => {
  const checkDetails = detail?.check_details || []
  tableList = checkDetails.map((item: any) => {
    return {
      ...item,
      old_score: parseFloat(item.old_score),
      ratio: parseFloat(item.ratio),
      score: isNaN(parseFloat(item.score)) ? null : parseFloat(item.score)
    }
  })
})

// 最终得分
// 评分 / 分值 * 占比
const score = $computed(() => {
  // 未打分的列表
  const unScoreList = tableList.filter((item: any) => item.score === null || item.score === '')
  if (unScoreList.length) {
    return '--'
  }
  const output = tableList.reduce((result: number, item: any) => {
    return (result += (item.score / item.old_score) * item.ratio || 0)
  }, 0)
  return usePrecision(output, 1).value
})

// 提交
function handleSubmit() {
  const scores = tableList.map((item: any) => {
    return { id: item.id, score: item.score }
  })
  const params = { id: detail.id, scores: JSON.stringify(scores) }
  submitScore(params).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
const qaURL = import.meta.env.VITE_QA_CENTER_URL

// 查看评分规则
const handleScoreRule = function () {
  if (detail?.competition_rubric && detail?.competition_rubric?.url) {
    window.open(detail?.competition_rubric?.url)
  }
}
</script>

<template>
  <el-dialog
    title="评分"
    :close-on-click-modal="false"
    width="700px"
    @update:modelValue="value => $emit('update:modelValue', value)"
  >
    <el-form label-suffix="：" v-if="detail">
      <el-form-item label="赛项名称">{{ detail.competition_id_name }}</el-form-item>
      <el-form-item label="选手姓名">{{ detail.student_name }}</el-form-item>
      <el-form-item label="选手ID">{{ detail.login_id }}</el-form-item>
      <div style="display: flex; justify-content: space-between">
        <el-form-item label="报告">
          <el-dropdown>
            <el-button text>
              查看报告<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu v-if="reportList.length">
                <el-dropdown-item v-for="item in reportList" :key="item.id">
                  <a :href="item.url" target="_blank">{{ item.platform.name }}</a>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
        <el-button type="primary" @click="handleScoreRule">查看评分规则</el-button>
      </div>
    </el-form>
    <el-table :data="tableList" :header-cell-style="{ background: '#ededed' }">
      <el-table-column label="评分规则" prop="name" align="center"></el-table-column>
      <el-table-column label="评分方法" prop="type_name" align="center"></el-table-column>
      <el-table-column label="分值" prop="old_score" align="center"></el-table-column>
      <el-table-column label="占比（%）" prop="ratio" align="center"></el-table-column>
      <el-table-column label="评分" prop="score" align="center">
        <template #default="{ row }">
          <el-input-number
            :controls="false"
            v-model="row.score"
            step-strictly
            :step="0.1"
            :min="0"
            :max="row.old_score"
            style="width: 100%"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button text type="primary" v-if="row.type === '2'">
            <a :href="`${qaURL}/exam/markingPaper?exam_id=${row.exam_id}&id_number=${detail.id_number}`" target="_blank"
              >查看</a
            >
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <p class="result">
      最终得分：<span>{{ score }}</span>
    </p>
    <el-row justify="center">
      <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<style lang="scss" scoped>
.result {
  padding: 40px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  span {
    padding: 0 10px;
    font-size: 40px;
    color: var(--main-color);
  }
}
</style>
