<!--
  Description: 写作界面。
  Author: BaiQi
  Created Date: 2024-6-22
-->
<template>

  <div class="my-work" >

    <div class="my-work-slider">
      <el-button class="back" color="#4A90C4" style="color: #FFFFFF;" @click="handleBack">返回</el-button>
      <AIChatter :dialogueId="dataForm.dialogueId" :messages="dataForm.messages" :is-teacher="false" />
      <Dictionaries />
    </div>
    <div class="my-work-input">
      <Edit
          :engagement="dataForm.engagement"
      />
    </div>
    <Slider :dialogueId="dataForm.dialogueId" :engagement="dataForm.engagement"/>
  </div>
</template>

<script setup lang="ts">
  import AIChatter from "@/components/AIChatter/AIChatter.vue";
  import Dictionaries from "@/views/Home/component/Dictionaries/index.vue";
  import useApis from "@/apis";
  import {useStore} from "@/store";
  import router from "@/router"
  import {onMounted, onUnmounted, reactive} from "vue";
  import type {engagementVO} from "@/types/vo";
  import type {IDialogue} from "@/types/dialogue.ts";
  import Edit from "@/views/Home/component/Edit/index.vue";
  import Slider from '@/views/Home/component/Silder/index.vue'
  import "./index.scss"
  import {useRoute} from 'vue-router'
  import {ElMessageBox} from "element-plus";
  import IndexedDB from "@/utils/indexedDBUtil";
  import {isModified, registerAllEventListeners, removeAllEventListeners} from "@/views/EditPage/userWritingRecord";
  import emitter from "@/utils/emitter";

  // 获得路由中的assignmentId
  const route = useRoute()
  const assignmentId = Number(route.params.assignmentId)

  const apis = useApis()
  const store = useStore()
  const indexedDB = new IndexedDB()

  const dataForm = reactive<{
    messages: IDialogue[],
    dialogueId: string;
    engagement: engagementVO
  }>({
    messages: [],
    dialogueId: '',
    engagement: {} as engagementVO
  })

  const handleBack = () => {
    if(isModified.value){
      ElMessageBox.confirm(
          '您编辑的信息尚未保存，您确定要离开吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            router.push(`/home/homeworkDetail/${assignmentId}`)
          }).then(() => {
            window.location.reload()
          })
          .catch(() => {
            return
          })
    }else {
      router.push(`/home/homeworkDetail/${assignmentId}`)
      .then(() => {
        window.location.reload()
      })
    }
  }

  // 获取数据
  async function fetchData(){
    await apis.getAIDialogues(assignmentId, store.user.id)
        .then((_res:any) => {
          const data = _res.data.data
          Object.assign(dataForm, {
            dialogueId: data == null ? '': data?.dialogueId,
            messages: data == null ? []: data?.messages.content,
            engagement: dataForm.engagement
          })

        })

    await apis.getEngagement(store.user.id, assignmentId)
        .then((_res:any) => {
          console.log(_res)
          Object.assign(dataForm, {
            dialogueId: dataForm.dialogueId,
            messages: dataForm.messages,
            engagement: _res.data.data
          })
          // if(!dataForm.engagement){
          //   fetchData()
          // }
        }).catch((_err:any) => {
          console.log("错误", _err)
        })
  }

  // 保存AI对话内容
  const saveAIDialogue = async () => {
    if (dataForm.dialogueId && dataForm.messages.length > 0) {
      try {
        await apis.requestAI(dataForm.dialogueId, 'ChatGLM4', dataForm.messages)
        console.log('AI对话内容已保存')
      } catch (error) {
        console.error('保存AI对话失败:', error)
      }
    }
  }

  // 监听提交前的保存对话事件
  emitter.on('save-ai-dialogue-before-submit', async () => {
    await saveAIDialogue()
  })

  onMounted( () => {
    fetchData()
    // indexedDB.initDB("eventId")
    registerAllEventListeners(indexedDB);
  })

  onUnmounted(() => {
    // indexedDB.clearDB()
    // indexedDB.closeDB()
    // indexedDB.deleteDBAll()
    removeAllEventListeners();
    // 清理事件监听器
    emitter.off('save-ai-dialogue-before-submit');
  })

</script>

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