<script setup lang="ts">
import type { ExperimentItem } from '../types'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import ReportDesign from '../components/ReportDesign.vue'
import { getExperiment, getExperimentReportRule, updateExperimentReportRule } from '../api'

const ReportPreview = defineAsyncComponent(() => import('../components/ReportPreview.vue'))

interface Props {
  id: string
}
const props = defineProps<Props>()
const router = useRouter()

let detail = $ref<ExperimentItem>()
const teacherText = $computed(() => {
  if (!detail) return ''
  return detail.teacher.map(item => item.name).join('、')
})
// 获取实验信息
function fetchExperimentInfo() {
  getExperiment({ experiment_id: props.id }).then(res => {
    detail = res.data.info
  })
}

const formRef = $ref<FormInstance>()

const form = reactive({
  experiment_id: props.id,
  report_upload_way: 1,
  detail_list: []
})

// 获取报告信息
function fetchInfo() {
  getExperimentReportRule({ experiment_id: props.id }).then(res => {
    const { data } = res
    let detailList = []
    try {
      detailList = JSON.parse(data.info.detail_list).map((item: any) => {
        return { ...item, percent: parseFloat(item.percent) }
      })
    } catch (error) {
      console.log(error)
    }
    Object.assign(form, { report_upload_way: data.way, detail_list: detailList })
  })
}

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

// 合计
const total = $computed(() => {
  return form.detail_list.reduce((result: number, item: any) => {
    return result + (item.score || 0)
  }, 0)
})
watch(
  form.detail_list,
  () => {
    console.log(1)
  },
  { deep: true }
)

// 保存
function handleSubmit() {
  formRef?.validate().then(() => {
    const params = { ...form, detail_list: JSON.stringify(form.detail_list) }
    if (form.report_upload_way === 1) {
      ElMessageBox.confirm('确定将当前实验的实验报告提交方式保存为学生手工上传文件吗？', '提示', {
        type: 'warning'
      }).then(() => {
        updateExperimentReportRule(params).then(() => {
          ElMessage({ message: '保存成功', type: 'success' })
          router.replace('/admin/lab/experiment')
        })
      })
    } else {
      updateExperimentReportRule(params).then(() => {
        ElMessage({ message: '保存成功', type: 'success' })
      })
    }
  })
}

// 关闭
function handleClose() {
  ElMessageBox.confirm('此操作将不做任何修改，确认关闭该页面？', '提示').then(() => {
    window.close()
  })
}

// 预览
let previewVisible = $ref(false)
function handlePreview() {
  previewVisible = true
}
</script>

<template>
  <AppCard title="实验报告规则设置">
    <el-form ref="formRef" :model="form" label-suffix="：" hide-required-asterisk v-if="detail">
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验名称">{{ detail.name }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实验课程名称">{{ detail.course_name }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属机构/学校">{{ detail.organ_id_name }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="实验类型">{{ detail.type_name }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :span="3" label="指导教师">{{ teacherText }}</el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="实验报告提交方式" prop="report_upload_way">
        <el-switch
          v-model="form.report_upload_way"
          active-text="上传文件"
          :active-value="1"
          inactive-text="在线填写"
          :inactive-value="2"
          style="--el-switch-on-color: #ba143e; --el-switch-off-color: #ba143e" />
      </el-form-item>
      <ReportDesign v-model="form.detail_list" v-if="form.report_upload_way === 2">
        <template #header>
          <p class="report-header-item">实验总分：{{ detail.score }}</p>
          <p class="report-header-item">组件总分：{{ total }}</p>
        </template>
      </ReportDesign>
    </el-form>
    <el-row justify="center">
      <el-space :size="40">
        <el-button auto-insert-space @click="handleClose">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button type="primary" auto-insert-space @click="handlePreview" v-if="form.report_upload_way === 2"
          >预览</el-button
        >
      </el-space>
    </el-row>
    <ReportPreview v-model="previewVisible" :data="{ ...detail, ...form }"></ReportPreview>
  </AppCard>
</template>

<style lang="scss">
.report-header-item {
  flex: 1;
  text-align: center;
}
</style>
