<script setup>
import { ElMessage } from 'element-plus'
import { getExperimentScore, getExperimentReport, updateExperimentReport, getExperimentScoreTemplate } from '../api'
import { reportScoreRule } from '@/utils/dictionary'

const route = useRoute()

let experiment = $ref()
let report = $ref()

const formRef = $ref()
const form = reactive({
  experiment_id: route.query.experiment_id,
  student_id: route.query.student_id,
  score_detail: [],
  comment: ''
})
const rules = reactive({
  comment: [{ required: true, message: '请输入评语', trigger: 'blur' }]
})
const teacherText = $computed(() => {
  if (!experiment) return ''
  return experiment.teachers.map(item => item.name).join('、')
})
const classText = $computed(() => {
  if (!experiment) return ''
  return experiment.student.classes?.map(item => item.name).join('、')
})
function fetchInfo() {
  getExperimentScore({ experiment_id: route.query.experiment_id, student_id: route.query.student_id }).then(res => {
    experiment = res.data.experiment
  })
}

function fetchReport() {
  getExperimentReport({ experiment_id: route.query.experiment_id, student_id: route.query.student_id }).then(
    async res => {
      report = res.data.detail
      form.comment = report.comment || ''
      if (report.score_detail || report.detail) {
        try {
          form.score_detail = genScoreList(JSON.parse(report.score_detail || report.detail))
        } catch (error) {
          console.log(error)
          await fetchTemplate()
        }
      } else {
        await fetchTemplate()
      }
    }
  )
}

async function fetchTemplate() {
  await getExperimentScoreTemplate({ experiment_id: route.query.experiment_id }).then(res => {
    form.score_detail = genScoreList(res.data.detail.rule_list)
  })
}

function genScoreList(list) {
  return list.map(item => {
    let commitScore = item.commit_score ? parseFloat(item.commit_score) : undefined
    // 附件自动评分
    if (item.rule_mode === 2 && !commitScore) {
      const hasScore = parseFloat(item.has_score)
      const noScore = parseFloat(item.no_score)
      commitScore = item.files?.length ? hasScore : noScore
    }
    return {
      ...item,
      min_score: parseFloat(item.min_score),
      commit_score: commitScore,
      commit: item.commit || ''
    }
  })
}

onMounted(() => {
  fetchInfo()
  fetchReport()
})

const score = $computed(() => {
  const result = form.score_detail.reduce((result, item) => {
    return result + (item.commit_score || 0)
  }, 0)
  return parseFloat(result.toFixed(2))
})

function handleSubmit() {
  formRef?.validate().then(() => {
    const params = { ...form, score_detail: JSON.stringify(form.score_detail) }
    updateExperimentReport(params).then(res => {
      console.log(res)
      ElMessage.success('批改成功')
    })
  })
}
// 关闭
function handleClose() {
  window.close()
}

function scoreValue(value) {
  if (typeof value !== 'number' && !value) {
    return '--'
  } else {
    return value
  }
}
</script>

<template>
  <AppCard title="批改实验报告">
    <h1 class="report-title">实验报告</h1>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-suffix="："
      hide-required-asterisk
      scroll-to-error
      v-if="experiment && report">
      <el-row>
        <el-col :span="12">
          <el-form-item label="课程名称">{{ experiment.course.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验名称">{{ experiment.name }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实验地点">{{ report.experiment_address }} </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验日期"> {{ report.experiment_date }} </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="实验类型">{{ experiment.type_level }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="指导教师">{{ teacherText }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="专业">{{ experiment.student.specialty.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班级">{{ classText }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名">{{ experiment.student.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号">{{ experiment.student.sno_number }}</el-form-item>
        </el-col>
      </el-row>
      <el-divider />
      <p class="report-score">总分：{{ scoreValue(score) }}</p>
      <el-form-item
        v-for="(item, index) in form.score_detail"
        :key="item.id"
        :prop="'score_detail.' + index + '.commit_score'"
        :rules="{ required: true, message: '请输入该项得分', trigger: 'blur' }"
        class="report-form-item">
        <div class="form-hd">
          <h3>{{ index + 1 }}、{{ item.name }}</h3>
          <div>
            <span>{{ item.score }}分</span>
            <span>{{ reportScoreRule[item.rule_mode] }}</span>
          </div>
          <div>
            <span>得分：{{ scoreValue(item.commit_score) }}分</span>
            <el-input-number
              v-model="item.commit_score"
              :min="item.min_score"
              :max="item.score"
              :controls="false"
              :step="0.01"
              step-strictly
              placeholder="更新得分"
              style="width: 100px"></el-input-number>
          </div>
        </div>
        <!-- 内容 -->
        <template v-if="item.type === 1">
          {{ item.notice_message }}
          <div class="report-form-item__content" v-html="item.content"></div>
        </template>
        <!-- 附件 -->
        <template v-if="item.type === 2">
          <el-table :data="item.files" stripe :header-cell-style="{ background: '#ededed' }" style="margin-top: 20px">
            <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
            <el-table-column label="附件类型" prop="type" align="center">
              <template #default="{ row }">
                {{ row.type === '1' ? '本地上传' : '实验截图' }}
              </template>
            </el-table-column>
            <el-table-column label="附件名称" prop="name" align="center"></el-table-column>
            <el-table-column label="更新时间" prop="updated_time" align="center"></el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button text type="primary"><a :href="row.url" target="_blank">查看</a></el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 思考题 -->
        <template v-if="item.type === 3">
          {{ item.question_stem }}
          <div class="report-form-item__content" v-html="item.content"></div>
        </template>
        <div class="report-form-item-comment">
          <div class="report-form-item-comment_hd">
            <p>评语：</p>
            <div>
              <span>快速评语：</span>
              <el-button
                type="primary"
                size="small"
                @click="item.comment = '此部分内容填写完善，内容充实，符合本实验相应要求。'"
                >很好</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="
                  item.comment = '此部分内容填写较为完善，内容较为充实，比较符合本实验相应要求，但仍然有提升空间。'
                "
                >一般</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="item.comment = '此部分内容仍然有提升空间，建议继续针对该实验进行相应训练，加油！'"
                >鼓励</el-button
              >
            </div>
          </div>
          <el-input
            type="textarea"
            maxlength="200"
            v-model="item.comment"
            placeholder="请填写评语"
            :autosize="{ minRows: 3 }"></el-input>
        </div>
      </el-form-item>
      <el-form-item prop="comment">
        <p class="t2">实验整体评语</p>
        <el-input
          type="textarea"
          maxlength="500"
          v-model="form.comment"
          placeholder="请填写评语"
          :autosize="{ minRows: 8 }"></el-input>
      </el-form-item>
    </el-form>
    <el-row justify="center" style="margin: 40px 0">
      <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      <el-button round auto-insert-space @click="handleClose">关闭</el-button>
    </el-row>
  </AppCard>
</template>

<style lang="scss" scoped>
.report-title {
  padding: 20px;
  font-size: 20px;
  text-align: center;
}
.report-score {
  text-align: right;
  font-size: 24px;
  font-weight: bold;
  color: var(--main-color);
  margin: 40px 0;
}
.report-form-item {
  margin-bottom: 40px;
  .form-hd {
    display: flex;
    width: 100%;
    font-size: 14px;
    font-weight: bold;
    justify-content: space-between;
    span {
      padding: 0 40px;
    }
  }
}
.report-form-item__content {
  margin: 5px 0;
  clear: both;
  width: 100%;
  padding: 10px;
  background-color: #efefef;
  border-radius: 6px;
  box-sizing: border-box;
}
.report-form-item-comment {
  width: 100%;
  padding: 20px 0;
}
.report-form-item-comment_hd {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 32px;
}

.t2 {
  margin: 40px 0 20px;
  width: 100%;
  color: #fff;
  background-color: var(--main-color);
  text-align: center;
  line-height: 40px;
}
</style>
