<!--
  Description: 写作界面右侧，侧边栏组件。
  Author: BaiQi
  Created Date: 2024-6-21
-->
<template>
  <div :class="rootClassName">
    <div class="slider-icons" @click="toggleShrink">
      <el-icon v-if="isShrink"><Expand/></el-icon>
      <el-icon v-if="!isShrink"><Fold/></el-icon>
    </div>
    <div class="slider-item-box">
      <!--折叠-->
      <template v-if="isShrink">
        <div class="slider-item" @click="toggleShrink">描述</div>
        <div v-if="data.assignment.descriptionFile" class="slider-item" @click="toggleShrink">要求</div>
        <div v-if="data.assignment.attachments" class="slider-item" @click="toggleShrink">附件</div>
        <div class="slider-item" @click="toggleShrink">批改</div>
      </template>
      <!--展开-->
      <template v-else>
        <!--作业名称-->
        <div>{{data.assignment.assignmentName}}</div>
        <!--作业描述-->
        <ExpandableParagraph :text="data.assignment.description" />
        <!--下载按钮-->
<!--        <div class="down">-->
<!--          <el-link type="primary">下载</el-link>-->
<!--        </div>-->
        <!--要求文件和附件-->
        <template v-if="data.assignment.descriptionFile || data.assignment.attachments">
          <div>作业附件</div>
          <div class="slider-tag">
            <template v-if="data.assignment.descriptionFile">
              <div class="slider-tag-item" @click="openEditor(data.assignment.descriptionFile, data.assignment.assignmentName)">作业要求</div>
            </template>
            <template v-if="data.assignment.attachments">
              <div v-for="(item, index) in data.assignment.attachments" :key="index" class="slider-tag-item" @click="openEditor(item, '附件' + index)">作业描述文件下载</div>
            </template>
          </div>
        </template>
        <div class="edit-box-header">
          智能批改
          <el-button @click="handleCorrect" :disabled="!showCorrectBtn" @mouseover="handleCorrectTip">开始批改</el-button>
          <el-button @click="handleCorrectToPage" :disabled="!showCorrectToPageBtn" @mouseover="handleCorrectToPageTip">查看完整批改报告</el-button>
        </div>
        <div class="capacity-item">
          <div v-loading="loading" element-loading-text="智能批改中" class="remark">{{ data.overallEvaluation?.evaluation }}</div>
        </div>
      </template>
    </div>
    <ViewsWordEditor v-if="data.assignment.descriptionFile" :alert="alertProps" :docxInfo="docxInfo"></ViewsWordEditor>
  </div>
</template>

<script lang="ts" setup>
import {defineProps, nextTick, onMounted, reactive, ref, watch, watchEffect} from 'vue'
  import "./index.scss"
import type {engagementVO, IAssignment} from "@/types/vo";
  import useApis from "@/apis";
  import {useStore} from "@/store";
  import {Expand, Fold} from "@element-plus/icons-vue"
  import ExpandableParagraph from "@/views/Home/component/Silder/component/ExpandableParagraph.vue";
import ViewsWordEditor from "@/components/ViewsWordEditor/ViewsWordEditor.vue";
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import router from "@/router";
import * as path from "node:path";


  interface IPreviewProps {
    url: string;
    title: string;
  }

  const apis = useApis()
  const store = useStore()
  const props = defineProps<{
    dialogueId: string,
    engagement: engagementVO
  }>()

  let isShrink = ref(false)
  let aiRemark = ref("")
  let loading = ref(false)
  let open= ref(false)
  let showCorrectBtn = ref(false)
  let showCorrectToPageBtn = ref(false)

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

  let data = reactive<{
    assignment: IAssignment,
    currentPreview: IPreviewProps,
    overallEvaluation: OverallEvaluation | null;
    sentenceEvaluationList: SentenceEvaluation[];
  }>({
    assignment: {} as IAssignment,
    currentPreview: {} as IPreviewProps,
    overallEvaluation: null,
    sentenceEvaluationList: [],
  })

  const alertProps = reactive({
    open: open.value,
    onOk: () => (open.value = false),
    onCancel: () => (open.value = false),
  });

  const docxInfo = reactive({
    docxUrl: data.currentPreview.url,
    docxTitle: data.currentPreview.title,
  });

  let rootClassName = ref(`slider-content ${isShrink.value ? "shrink" : ""}`);

  const toggleShrink = () => {
    isShrink.value = !isShrink.value;
    rootClassName.value = `slider-content ${isShrink.value ? "shrink" : ""}`
  };

  // 获取作业信息
  const fetchData = () => {
    apis.getAssignmentById(assignmentId).then((res: any) => {
      data.assignment = res.data.data;
    });
  };

  const getEvaluation = () => {
    apis.getOverall(props.engagement.assignmentId, store.user.id,props.engagement.version)
        .then(res => {
          data.overallEvaluation = res.data.data
          loading.value = false;
        })
        .catch(err => {
          ElMessage.error("获取智能批改结果异常")
          console.log(err)
          loading.value = false;
        })
  }

  const toEvaluation = () => {
    apis.overAllEvaluation(props.engagement.assignmentId, store.user.id)
        .then(res => {
          if(res.data.code === 200){
            getEvaluation()
            // 允许查看详细报告
            showCorrectToPageBtn.value = true;
          }else{
            ElMessage.error("智能批改请求超时")
            loading.value = false;
          }
        })
        .catch(err => {
          ElMessage.error("智能批改请求异常")
          console.log(err)
          loading.value = false;
        })
    apis.sentenceEvaluation(props.engagement.assignmentId, store.user.id)
        .then(res => {
          if(res.data.code === 400){
            ElMessage.error(res.data.msg)
          }else{
            ElMessage.error("智能批改请求超时")
            loading.value = false;
          }
        })
        .catch(err => {
          ElMessage.error("智能批改请求异常")
          console.log(err)
        })
  }

  // 请求批改
  const handleCorrect = () => {
    loading.value = true;
    showCorrectBtn.value = !showCorrectBtn.value
    toEvaluation()
  };

  const handleCorrectToPage = () => {
    router.push({
      path: `/home/assignment/${props.engagement.assignmentId}/AIEvaluation`,
    })
  }

  const openEditor = (url: string, title: string) => {
    open.value = true;
    data.currentPreview.url = url;
    data.currentPreview.title = title;
    Object.assign(alertProps, {
      open: open.value,
      // onOk: () => (open.value = false),
      onCancel: () => {
        open.value = false
        Object.assign(alertProps,{
          open: open.value,
          onOk: () => (open.value = false),
          onCancel: () => (open.value = false),
        })
        Object.assign(docxInfo, {
          docxUrl: data.currentPreview.url,
          docxTitle: data.currentPreview.title,
        })
      },
    })
    Object.assign(docxInfo, {
      docxUrl: data.currentPreview.url,
      docxTitle: data.currentPreview.title,
    })
  };

  /**
   * 用于判断是否已存在历史批改记录
   */
  const getEvaluationVersionList = () => {
    if(JSON.stringify(props.engagement) !== '{}'){
      apis.getEvaluationVersionList(props.engagement.assignmentId, store.user.id)
          .then(res => {
            // 从未批改过
            if(res.data.data.length === 0){
              showCorrectBtn.value = true
              showCorrectToPageBtn.value = false
            } else {
              showCorrectToPageBtn.value = true
              showCorrectBtn.value = (res.data.data[0].version !== props.engagement.version)
            }
          })
          .catch(err => {
            ElMessage.error("获取评价历史记录异常")
            console.log(err)
          })
    }

  }

  const handleCorrectTip = () => {
    if(!showCorrectBtn.value)
      ElMessage.error("请更新作文内容并暂存后批改")
  }

  const handleCorrectToPageTip = () => {
    if(!showCorrectToPageBtn.value)
      ElMessage.error("批改后查看报告")
  }

  // 监听props变化
  watch(() => props.engagement, (newEngagement, oldEngagement) => {
    if (newEngagement) {
      getEvaluationVersionList();
    }
  }, { immediate: true });

  onMounted(() => {
    fetchData()
  });
</script>

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