<script setup lang="ts">
import type { RecordItem, FileItem } from '../types'
import { ElMessage, ElMessageBox } from 'element-plus'

import { getExperimentScore, getExperimentScoreTemplate, updateExperimentScore, getExperimentReport } from '../api'

const ScoreViewPicturesDialog = defineAsyncComponent(() => import('./ScoreViewPicturesDialog.vue'))
const ScoreViewPrepareDialog = defineAsyncComponent(() => import('./ScoreViewPrepareDialog.vue'))
const ScoreViewResultDialog = defineAsyncComponent(() => import('./ScoreViewResultDialog.vue'))

interface Props {
  data: RecordItem
}
const props = defineProps<Props>()

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

let experiment = $ref<any>()
let detail = $ref<any>()
async function fetchInfo() {
  await getExperimentScore({ experiment_id: props.data.experiment_id, student_id: props.data.student_id }).then(
    async res => {
      experiment = res.data.experiment
      detail = res.data.achievement
      if (detail.score_details) {
        try {
          form.score_details = JSON.parse(detail.score_details).map((item: any) => {
            return {
              ...item,
              percent: parseFloat(item.percent),
              score: parseFloat(item.score),
              commit_score: parseFloat(item.commit_score)
            }
          })
        } catch (error) {
          await fetchTemplate()
          console.log(error)
        }
      } else {
        await fetchTemplate()
      }
      if (experiment.report_upload_way === 2) {
        await fetchReport()
      }
    }
  )
}
watchEffect(() => {
  fetchInfo()
})

async function fetchTemplate() {
  await getExperimentScoreTemplate({ experiment_id: props.data.experiment_id }).then(res => {
    form.score_details = res.data.detail.rule_list.map((item: any) => {
      return {
        ...item,
        percent: parseFloat(item.percent),
        score: parseFloat(item.score),
        commit_score: parseFloat(item.commit_score)
      }
    })
  })
}

// 获取实验报告分数
let report = $ref<any>()
async function fetchReport() {
  await getExperimentReport({ experiment_id: props.data.experiment_id, student_id: props.data.student_id }).then(
    res => {
      report = res.data.detail
      const reportScore = parseFloat(report.score || 0)
      form.score_details = form.score_details.map((item: any) => {
        if (item.type === 1) {
          item.commit_score = reportScore
        }
        return item
      })
    }
  )
}

// 实验报告文件
const file = $computed<FileItem>(() => {
  try {
    return detail?.file ? JSON.parse(detail.file) : null
  } catch (error) {
    console.log(error)
  }
  return null
})

const form = reactive<any>({
  experiment_id: props.data.experiment_id,
  student_id: props.data.student_id,
  score_details: []
})

const score = $computed<number>(() => {
  const result = form.score_details.reduce((result: number, item: any) => {
    return result + item.commit_score * (item.percent / 100) * (experiment.score / 100)
  }, 0)
  return parseFloat(result.toFixed(2))
})

// 提交
function handleSubmit() {
  ElMessageBox.confirm('更改成绩之后将以最新成绩为准，您可以查看批改成绩历史数据，确定需要修改成绩吗？', '提示').then(
    () => {
      const params = { ...form, score_details: JSON.stringify(form.score_details) }
      updateExperimentScore(params).then(() => {
        ElMessage({ message: '保存成功', type: 'success' })
        emit('update')
        emit('update:modelValue', false)
      })
    }
  )
}

function scoreValue(value: any) {
  if (typeof value !== 'number' && !value) {
    return '--'
  } else {
    return value
  }
}

const pictureVisible = $ref(false)
const prepareVisible = $ref(false)
const resultVisible = $ref(false)

function getOperationUrl(type: number) {
  if (type === 1) {
    // 批改实验报告
    return `/admin/lab/score/report?experiment_id=${props.data.experiment_id}&student_id=${props.data.student_id}`
  } else if (type === 6) {
    // 用户标签
    return `${import.meta.env.VITE_DML_URL}/label?experiment_id=${props.data.experiment_id}&student_id=${
      props.data.student_id
    }`
  } else if (type === 7) {
    // 用户群组
    return `${import.meta.env.VITE_DML_URL}/group?experiment_id=${props.data.experiment_id}&student_id=${
      props.data.student_id
    }`
  } else if (type === 8) {
    // 用户旅程
    return `${import.meta.env.VITE_DML_URL}/trip/review?experiment_id=${props.data.experiment_id}&student_id=${
      props.data.student_id
    }`
  } else if (type === 9) {
    // 营销资料
    return `${import.meta.env.VITE_DML_URL}/material?experiment_id=${props.data.experiment_id}&student_id=${
      props.data.student_id
    }`
  }
}
</script>

<template>
  <el-dialog
    title="学生实验评分"
    :close-on-click-modal="false"
    width="800px"
    @update:modelValue="$emit('update:modelValue')">
    <el-form label-width="120px" label-suffix="：" v-if="detail">
      <el-row>
        <el-col :span="12">
          <el-form-item label="实验名称">{{ data.experiment_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验课程名称">{{ experiment.course.name }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="学生姓名">{{ data.student_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学生学号">{{ data.sno_number }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属专业">{{ data.specialty_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">{{ data.class_name }}</el-form-item>
        </el-col>
      </el-row>
      <el-divider />
      <el-form-item label="实验成绩">
        <el-row justify="end" style="width: 100%">
          <el-button type="primary" @click="prepareVisible = true">查看实验准备</el-button>
          <el-button type="primary" @click="resultVisible = true">查看实验结果</el-button>
          <el-button type="primary" @click="pictureVisible = true">查看截图</el-button>
        </el-row>
      </el-form-item>
      <div class="score-result">
        <div class="score-result__total">
          <p class="t1">{{ scoreValue(score) }}</p>
          <p class="t2">满分：{{ experiment.score }}</p>
        </div>
        <el-table
          :data="form.score_details"
          stripe
          :header-cell-style="{ background: '#ededed' }"
          style="margin-top: 20px">
          <el-table-column label="实验成绩组成项" prop="name" align="center"></el-table-column>
          <el-table-column label="权重" prop="percent" align="center">
            <template #default="{ row }"> {{ row.percent }}% </template>
          </el-table-column>
          <el-table-column label="满分" prop="score" align="center">100</el-table-column>
          <el-table-column label="得分" prop="commit_score" align="center">
            <template #default="{ row }">
              <el-input-number
                v-model="row.commit_score"
                :min="0"
                :max="100"
                :controls="false"
                :step="0.01"
                step-strictly
                placeholder="请输入成绩"
                style="width: 100px"
                v-if="!(row.type === 1 && experiment.report_upload_way === 2)"></el-input-number>
              <span v-else>{{ row.commit_score }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="commit_score" align="center">
            <template #default="{ row }">
              <template v-if="row.type === 1">
                <el-button
                  text
                  type="primary"
                  @click="$emit('update:modelValue')"
                  v-if="experiment.report_upload_way === 2">
                  <a :href="getOperationUrl(row.type)" target="_blank">批改</a>
                </el-button>
                <template v-if="experiment.report_upload_way === 1">
                  <el-button text type="primary" v-if="file?.url">
                    <a :href="file.url" target="_blank">查阅报告</a>
                  </el-button>
                  <p style="color: red" v-else>未上传</p>
                </template>
              </template>
              <template v-else-if="[6, 7, 8, 9].includes(row.type)">
                <el-button text type="primary">
                  <a :href="getOperationUrl(row.type)" target="_blank">查看结果</a>
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template #footer>
      <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>
    </template>

    <!-- 实验准备 -->
    <ScoreViewPrepareDialog
      v-model="prepareVisible"
      :experiment_id="data.experiment_id"
      :student_id="data.student_id"
      v-if="prepareVisible"></ScoreViewPrepareDialog>
    <!-- 实验结果 -->
    <ScoreViewResultDialog
      v-model="resultVisible"
      :experiment_id="data.experiment_id"
      :student_id="data.student_id"
      v-if="resultVisible"></ScoreViewResultDialog>
    <!-- 实验截图 -->
    <ScoreViewPicturesDialog
      v-model="pictureVisible"
      :data="detail"
      v-if="pictureVisible && detail"></ScoreViewPicturesDialog>
  </el-dialog>
</template>

<style lang="scss" scoped>
.score-result {
  display: flex;
  align-items: center;
  justify-content: center;
}
.score-result__total {
  min-width: 120px;
  white-space: nowrap;
  text-align: center;
  .t1 {
    font-size: 30px;
    color: var(--main-color);
  }
}
</style>
