<!--
  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> -->
              <el-tooltip 
                v-for="(item, index) in data.assignment.attachments" 
                :key="index" 
                :content="!item || item.trim() === '' ? '暂无描述文件' : ''"
                :disabled="item && item.trim() !== ''"
                placement="top"
              >
                <div 
                  class="slider-tag-item" 
                  :class="{ 'disabled': !item || item.trim() === '' }"
                  @click="item && item.trim() !== '' && openEditor(item, '附件' + index)"
                >
                  作业描述文件下载
                </div>
              </el-tooltip>
            </template>
          </div>
        </template>
        <div>智能批改</div> 
        <div class="edit-box-header">
          <el-button @click="handleCorrect" :disabled="!showCorrectBtn" @mouseover="handleCorrectTip">开始批改</el-button>
          <el-button @click="handleCorrectToPage" :disabled="!showCorrectToPageBtn" @mouseenter="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, onUnmounted, 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";
import emitter from "@/utils/emitter";


  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)
  let hasStagedContent = 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 = (version?: number) => {
    // 如果没有传入version,使用props中的version
    const versionToUse = version !== undefined ? version : props.engagement.version;
    
    apis.getOverall(props.engagement.assignmentId, store.user.id, versionToUse)
        .then(res => {
          if (res.data.data) {
            data.overallEvaluation = res.data.data;
            console.log('成功获取评语:', data.overallEvaluation);
          }
          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){
            console.log('批改请求成功,等待后端处理完成...');
            
            // 延迟获取评语,确保后端已经保存,并获取最新版本号
            setTimeout(() => {
              // 先获取最新的版本列表
              apis.getEvaluationVersionList(props.engagement.assignmentId, store.user.id)
                  .then(versionRes => {
                    if (versionRes.data.data && versionRes.data.data.length > 0) {
                      // 获取最新版本号(列表第一个就是最新的)
                      const latestVersion = versionRes.data.data[0].version;
                      console.log('获取到最新版本号:', latestVersion);
                      
                      // 使用最新版本号获取评语
                      getEvaluation(latestVersion);
                      
                      // 允许查看详细报告
                      showCorrectToPageBtn.value = true;
                    } else {
                      // 如果获取不到版本列表,尝试使用当前版本+1
                      console.log('未获取到版本列表,使用当前版本+1');
                      const nextVersion = (props.engagement.version || 0) + 1;
                      getEvaluation(nextVersion);
                      showCorrectToPageBtn.value = true;
                    }
                  })
                  .catch(err => {
                    console.error('获取版本列表失败:', err);
                    // 如果获取版本列表失败,尝试使用当前版本+1
                    const nextVersion = (props.engagement.version || 0) + 1;
                    getEvaluation(nextVersion);
                    showCorrectToPageBtn.value = true;
                  });
            }, 1500); // 延迟1.5秒,确保后端处理完成
          }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)
          }
        })
        .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`,
    }).then(() => {
      window.location.reload()
    });
  }

  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) !== '{}'){
      // 检查是否已有暂存的作文内容
      const hasContent = props.engagement.content && props.engagement.content.trim() !== '';
      if (hasContent) {
        hasStagedContent.value = true;
      }
      
      apis.getEvaluationVersionList(props.engagement.assignmentId, store.user.id)
          .then(res => {
            // 从未批改过
            if(res.data.data.length === 0){
              // 修改：从未批改过时，只有当已有暂存内容时才能启用批改按钮
              showCorrectBtn.value = hasStagedContent.value
              showCorrectToPageBtn.value = false
            } else {
              showCorrectToPageBtn.value = true
              showCorrectBtn.value = (res.data.data[0].version !== props.engagement.version) && hasStagedContent.value
            }
          })
          .catch(err => {
            ElMessage.error("获取评价历史记录异常")
            console.log(err)
          })
    }

  }

  // 添加节流函数
  const throttle = (fn: Function, delay: number) => {
    let lastTime = 0;
    return function (...args: any[]) {
      const now = Date.now();
      if (now - lastTime >= delay) {
        fn.apply(this, args);
        lastTime = now;
      }
    };
  };

  // 使用节流包装 handleCorrectTip
  const handleCorrectTip = throttle(() => {
    if(!showCorrectBtn.value) {
      ElMessage.info("请更新作文内容并暂存后批改");
    }
  }, 2000); // 2秒的节流时间

  const handleCorrectToPageTip = throttle(() => {
    if(!showCorrectToPageBtn.value)
      ElMessage.info("批改后查看报告")
  },1000);

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

  // 监听暂存成功事件
  emitter.on('stage-success', () => {
    console.log('收到暂存成功事件，启用批改按钮')
    // 暂存成功后，标记已有暂存内容，并启用"开始批改"按钮
    hasStagedContent.value = true
    showCorrectBtn.value = true
  })

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

  onUnmounted(() => {
    // 清理事件监听器
    emitter.off('stage-success');
  });
</script>

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