<!-- 大作业 -->
<script setup lang="ts">
import AppUpload from '@/components/base/AppUpload.vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import AppEditor from '@/components/base/AppEditor.vue'

import { getCourseWork, submitCourseWork } from '../api'

const { query } = useRoute()
const courseId = $ref(query.course_id as string)
const semesterId = $ref(query.semester_id as string)

const formRef = $ref<FormInstance>()
const form = reactive({
  id: '',
  course_id: courseId,
  semester_id: semesterId,
  title: '',
  content: '',
  attachments: [],
  is_critiqued: 0,
  reviews: '',
  score: ''
})

const rules = ref<FormRules>({
  title: [{ required: true, message: '请输入作业标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入作业正文', trigger: 'blur' }]
})

const disabled = computed(() => !!form.id)
// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  const params = Object.assign({}, form, { attachments: JSON.stringify(form.attachments) })
  submitCourseWork(params).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
  })
}
// 获取作业
let workInfo = $ref('')

function fetchInfo() {
  getCourseWork({ course_id: courseId, semester_id: semesterId }).then(res => {
    const { detail, essay } = res.data
    workInfo = essay
    Object.assign(form, detail)
  })
}
onMounted(() => {
  fetchInfo()
})
</script>

<template>
  <div class="course-work">
    <div class="course-work-item" v-if="form.is_critiqued">
      <h2>作业评价</h2>
      <h3>分数：{{ form.score }}</h3>
      <div v-html="form.reviews"></div>
    </div>
    <div class="course-work-item">
      <h2>作业说明</h2>
      <div v-html="workInfo"></div>
    </div>
    <div class="course-work-item">
      <h2>上传作业</h2>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        hide-required-asterisk
        label-position="top"
        :disabled="disabled"
      >
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="作业正文" prop="content">
          <AppEditor v-model="form.content" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="上传附件" prop="attachments">
          <AppUpload v-model="form.attachments" :disabled="disabled"></AppUpload>
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.course-work {
  h2 {
    font-size: 16px;
    font-weight: 500;
    line-height: 28px;
    color: #333;
    padding-bottom: 10px;
  }
}
.course-work-item {
  padding: 20px 0;
}
.course-work-item + .course-work-item {
  border-top: 1px dashed #e6e6e6;
}
</style>
