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

import { getExperimentRecord, checkExperimentRecord } from '../api'

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

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

let detail = $ref<RecordItem>()
function fetchInfo() {
  getExperimentRecord({ experiment_id: props.data.experiment_id, student_id: props.data.student_id }).then(res => {
    detail = res.data
    const score = res.data.score_details || {}
    form.file = score.file ? parseFloat(score.file) : 0
    form.operate = score.operate ? parseFloat(score.operate) : 0
    form.result = score.result ? parseFloat(score.result) : 0
  })
}
watchEffect(() => {
  fetchInfo()
})
// 实验报告文件
const file = $computed<FileItem>(() => {
  try {
    return detail?.file ? JSON.parse(detail.file) : null
  } catch (error) {
    console.log(error)
  }
  return null
})
// 实验过程截图
const pictures = $computed<FileItem[]>(() => {
  try {
    return detail?.pictures ? JSON.parse(detail.pictures) : []
  } catch (error) {
    console.log(error)
  }
  return []
})

const formRef = $ref<FormInstance>()
const form = reactive<{ operate?: number; result?: number; file?: number }>({
  operate: undefined,
  result: undefined,
  file: undefined
})
const score = $computed<number>(() => {
  const result = ((form.operate || 0) + (form.result || 0) + (form.file || 0)) / 3
  return parseFloat(result.toFixed(2))
})
const rules = ref<FormRules>({
  operate: [{ required: true, message: '请输入1~100数字' }],
  result: [{ required: true, message: '请输入1~100数字' }],
  file: [{ required: true, message: '请输入1~100数字' }]
})

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

<template>
  <el-dialog
    title="学生实验评分"
    :close-on-click-modal="false"
    width="700px"
    @update:modelValue="$emit('update:modelValue')">
    <el-form :rules="rules" label-width="120px" label-suffix="：" v-if="detail">
      <el-row>
        <el-col :span="12">
          <el-form-item label="实验名称">{{ detail.experiment_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验课程名称">{{ detail.course_name }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="学生姓名">{{ detail.student_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学生学号">{{ detail.sno_number }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属专业">{{ detail.specialty_name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">{{ detail.class_name }}</el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="实验成绩" class="form-item-score">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          hide-required-asterisk
          inline
          label-position="top"
          style="padding: 5px 0 20px">
          <el-form-item label="实验操作" prop="operate">
            <el-input-number :min="1" :max="100" :controls="false" step-strictly v-model="form.operate" />
          </el-form-item>
          <el-form-item label="实验结果" prop="result">
            <el-input-number :min="1" :max="100" :controls="false" step-strictly v-model="form.result" />
          </el-form-item>
          <el-form-item label="实验报告" prop="file">
            <el-input-number :min="1" :max="100" :controls="false" step-strictly v-model="form.file" />
          </el-form-item>
          <el-form-item label="综合实验成绩">
            <el-input-number :min="0" :max="100" :controls="false" disabled v-model="score" />
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="实验报告文件">
        <div v-if="file">
          <a :href="file.url" target="_blank" class="file-item">
            <el-icon><Document /></el-icon>{{ file.name }}
          </a>
        </div>
      </el-form-item>
      <el-form-item label="实验过程截图">
        <ul class="picture-list">
          <li v-for="item in pictures" :key="item.url">
            <p class="t1">
              <a :href="item.url" target="_blank">{{ item.name }}</a>
            </p>
            <p class="t2">截图时间：{{ item.upload_time }}</p>
          </li>
        </ul>
      </el-form-item>
      <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-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.file-item {
  display: flex;
  align-items: center;
  color: var(--main-color);
  .el-icon {
    margin-right: 5px;
  }
}
.picture-list {
  width: 100%;
  li {
    display: flex;
    justify-content: space-between;
  }
  a {
    color: var(--main-color);
  }
  .t1 {
    flex: 1;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
.form-item-score {
  padding-top: 10px;
  background-color: #f8f9fb;
  border-radius: 16px;
  :deep(.el-form-item__label) {
    text-align: center;
  }
  .el-input-number {
    width: 100px;
  }
}
</style>
