<script setup>
import AppEditor from '@/components/base/AppEditor.vue'
import { useMapStore } from '@/stores/map'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useFileDialog } from '@vueuse/core'
import { upload } from '@/utils/upload'
import { useNow, useDateFormat } from '@vueuse/core'
import {
  getExperimentReport,
  getExperimentReportTemplate,
  getExperimentReportCache,
  cacheExperimentReport,
  updateExperimentReport
} from '../api'
import BindCaptureDialog from '../components/BindCaptureDialog.vue'

const props = defineProps({ id: String })

const experimentAddress = useMapStore().getMapValuesByKey('experiment_address')

let experiment = $ref()
let report = $ref()
const disabled = $computed(() => {
  return experiment?.is_commit_report
})
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('、')
})

const formRef = $ref()
const form = reactive({
  experiment_id: props.id,
  experiment_address: '',
  experiment_date: useDateFormat(useNow(), 'YYYY-MM-DD').value,
  detail: []
})

function fetchInfo() {
  getExperimentReport({ experiment_id: props.id }).then(res => {
    experiment = res.data.experiment
    report = res.data.report
    if (experiment.is_commit_report) {
      let detail = []
      try {
        detail = JSON.parse(report.detail)
      } catch (error) {
        console.log(error)
      }
      Object.assign(form, report, { detail })
    } else {
      fetchCached()
    }
  })
}
function fetchTemplate() {
  getExperimentReportTemplate({ experiment_id: props.id }).then(res => {
    form.detail = res.data.template
  })
}
function fetchCached() {
  getExperimentReportCache({ experiment_id: props.id }).then(res => {
    const report = res.data.report
    if (!report.experiment_id) {
      fetchTemplate()
      return
    }
    let detail = []
    try {
      detail = JSON.parse(report.detail)
    } catch (error) {
      console.log(error)
    }
    Object.assign(form, report, { detail })
  })
}
onMounted(() => {
  fetchInfo()
})

// 关闭
function handleClose() {
  ElMessageBox.confirm('此操作将不做任何修改，确认关闭该页面？', '提示').then(() => {
    window.close()
  })
}
// 暂存
function handleCache() {
  const params = { ...form, detail: JSON.stringify(form.detail) }
  cacheExperimentReport(params).then(() => {
    ElMessage.success('暂存成功')
  })
}
// 提交
function handleSubmit() {
  formRef.validate().then(() => {
    const params = { ...form, detail: JSON.stringify(form.detail) }
    ElMessageBox.confirm('提交报告之后，您将不能进行修改报告，确认提交实验报告？', '提示').then(() => {
      updateExperimentReport(params).then(() => {
        ElMessage.success('提交成功')
        fetchInfo()
      })
    })
  })
}

// 附件
let currentRaw = $ref(null)

// 本地上传
const { files, open, reset } = useFileDialog()
function handleUpload(data) {
  currentRaw = data
  open({ multiple: false })
}
watchEffect(() => {
  if (!files.value?.length) return
  const [file] = files.value
  upload(file).then(url => {
    const formatted = useDateFormat(useNow(), 'YYYY-MM-DD HH:mm:ss')
    currentRaw.files.push({
      id: Date.now().toString(),
      url,
      name: file.name,
      type: '1',
      file_type: file.type || 'png',
      updated_time: formatted.value,
      upload_time: formatted.value
    })
    reset()
  })
})

// 关联截图
let bindCaptureVisible = $ref(false)
function handleBindCapture(data) {
  currentRaw = data
  bindCaptureVisible = true
}

// 删除文件
function handleRemoveFile(data, index) {
  data.files.splice(index, 1)
}

function handleUpdateBindCapture(files) {
  currentRaw.files = files
}
</script>

<template>
  <AppCard title="在线填写实验报告">
    <h1 class="report-title">在线填写实验报告</h1>
    <el-form
      ref="formRef"
      :model="form"
      :disabled="disabled"
      label-suffix="："
      hide-required-asterisk
      v-if="experiment">
      <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="实验地点">
            <el-select v-model="form.experiment_address">
              <el-option v-for="item in experimentAddress" v-bind="item" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验日期">
            <el-date-picker v-model="form.experiment_date" value-format="YYYY-MM-DD"></el-date-picker>
          </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 />
      <el-form-item :label="item.name" v-for="item in form.detail" :key="item.id" class="report-form-item">
        <!-- 内容 -->
        <template v-if="item.type === 1">
          {{ item.notice_message }}
          <AppEditor v-model="item.content" :disabled="disabled" :height="200"></AppEditor>
        </template>
        <!-- 附件 -->
        <template v-if="item.type === 2">
          <el-button type="primary" @click="handleUpload(item)" v-if="item.categories.includes(2)">上传附件</el-button>
          <el-button type="primary" @click="handleBindCapture(item)" v-if="item.categories.includes(1)"
            >关联截图</el-button
          >
          <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="200" align="center">
              <template #default="{ row, $index }">
                <el-button text type="primary"><a :href="row.url" target="_blank">查看</a></el-button>
                <el-button text type="danger" @click="handleRemoveFile(item, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 思考题 -->
        <template v-if="item.type === 3">
          {{ item.question_stem }}
          <AppEditor v-model="item.content" :disabled="disabled" :height="200"></AppEditor>
        </template>
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" auto-insert-space @click="handleClose">关闭</el-button>
        <el-button type="primary" auto-insert-space @click="handleCache">暂存</el-button>
        <el-button type="primary" auto-insert-space @click="handleSubmit">提交报告</el-button>
      </el-row>
    </el-form>
    <!-- 关联截图 -->
    <BindCaptureDialog
      v-model="bindCaptureVisible"
      :experiment="experiment"
      :data="currentRaw"
      @update="handleUpdateBindCapture"
      v-if="bindCaptureVisible && currentRaw"></BindCaptureDialog>
  </AppCard>
</template>

<style lang="scss">
.report-title {
  padding: 20px;
  font-size: 20px;
  text-align: center;
}
.report-form-item {
  flex-direction: column;
  .el-form-item__label {
    font-weight: bold;
    text-align: left;
    justify-content: flex-start;
  }
}
</style>
