<!--
  Description: 写作界面中间，主要的写作组件，内含onlyoffice
  Author: BaiQi
  Created Date: 2024-6-21
-->
<template>
  <div class="edit">
    <div class="edit-box">
      <div>编辑区</div>
      <div class="edit-root">
        <QuillEditor/>
      </div>
      <div class="button-right">
        <el-button type="primary" @click="handleSubmit"  color="#4A90C4" style="color: #FFFFFF; width: 70px;">提交</el-button>
        <el-button type="primary" @click="handleStage"  color="#4A90C4" style="color: #FFFFFF; width: 70px; margin-left: 15px;">暂存</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>

  import "./index.scss";
  import type {engagementVO, IAssignment} from "@/types/vo";
  import {defineProps, onMounted, reactive, ref} from 'vue'
  import router from '@/router'
  import useApis from "@/apis";
  import {useStore} from "@/store";
  import {ElMessage} from "element-plus";
  import emitter from "@/utils/emitter";
  import QuillEditor from "@/components/QuillEditor/QuillEditor.vue";
  import {useRoute} from "vue-router";
  import dayjs from "dayjs";

  interface IEditProps {
    engagement: engagementVO
  }
  const props = defineProps<{
    engagement: engagementVO
  }>()
  const apis = useApis()
  const store = useStore()

  let hasStage = ref(true)
  let data = reactive<{
    assignment: IAssignment
  }>({
    assignment: {} as IAssignment
  })
  const route = useRoute()
  const assignmentId = Number(route.params.assignmentId)
  let useBtn = ref(true)

  let getHTML = ref("")
  let getText = ref("")
  let getQuillContent = reactive({})

  emitter.on('get-html', (value: string) => {
    getHTML.value = value
  })

  const contentTest = ref('')
  emitter.on('get-text', (value: string) => {
    getText.value = value
  })

  emitter.on('get-quill-content', (value: Object) => {
    Object.assign(getQuillContent, value)
  })

  // 成功操作的消息提示
  const success = (msg: string) => {
    ElMessage.success(msg);
  };

  // 失败操作的消息提示
  const error = (msg: string) => {
    console.log('失败操作', msg);
    ElMessage.error(msg);
  };

  // 提交操作
  const handleSubmit = async () => {
    console.log(props)
    // 先自动暂存
    try {
      await handleStage();
   } catch (e) {
      ElMessage.error('暂存失败，无法提交！');
      return;
    }
    const endTime = dayjs(data.assignment.endTime); // 假设截止时间在 assignment 的 endTime 属性中
    const currentTime = dayjs();
    let supplementarySubmission = false
    if (currentTime.isAfter(endTime)) {
      supplementarySubmission = true
    }
    apis.engagementSubmit(store.user.id, props.engagement.assignmentId, supplementarySubmission)
    .then((_res: any) => {
      success(_res.data.data);
      router.push("/home/myHomework").then(() => {
        window.location.reload()
      })
    })
    .catch((error: any) => {
      console.error('提交失败', error);
      error('提交失败');
    });
   };

  // 暂存操作
  const handleStage = async () => {
    try {
      console.log(props)
      const _res = await apis.engagementStage(store.user.id, props.engagement.assignmentId, JSON.stringify(getQuillContent), getText.value, getHTML.value);
      emitter.emit('click-stage');
      // 通知 Silder 组件暂存成功，可以启用批改按钮
      emitter.emit('stage-success');
      success(_res.data.data);
      return _res;
    } catch (error) {
      console.error('暂存失败', error);
      error('暂存失败');
      throw error;
    }
  };

  // window.onbeforeunload = function(event) {
  //   console.log(data)
  //   if(data.isModified){
  //     alert("您编辑的信息尚未保存，您确定要离开吗？")//这里内容不会显示在提示框，为了增加语义化。
  //   } else {
  //     alert("再见")
  //   }
  // };
  /*
  用于提醒用户作业未保存
   */
  // window.addEventListener('beforeunload', (e) => {
  //   e.preventDefault();
  //   e.returnValue = '您编辑的信息尚未保存，您确定要离开吗？';
  // });

  const fetchData = () => {
    apis.getAssignmentById(assignmentId).then((res: any) => {
      data.assignment = res.data.data;
      const endTime = dayjs(data.assignment.endTime); // 假设截止时间在 assignment 的 endTime 属性中
      const currentTime = dayjs();
      if (currentTime.isBefore(endTime)) {
        useBtn.value = false
      }
    });
  };

  onMounted(() => {
    fetchData()
  });


</script>

<script lang="ts">
export default {
  name: "Edit"
}
</script>

