<!--
  Description: AI对话组件。
  Author: BaiQi
  Created Date: 2024-6-21
-->
<template>
  <div :class="[{'teacher-view': props.isTeacher},$style.container]">
    <!--大语言模型选择器-->
    <!-- Update: 目前只有glm4可用 删掉其他选项 -->
     <div v-if="!props.isTeacher">
      <div :class="$style.header">
        <div :class="$style['model-selector']">
          <el-dropdown trigger="click" @command="handleCommand">
          <span style="font-size: 16px">
            {{ data.model }}<el-icon ><arrow-down/></el-icon>
          </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="model in modelOptions" :command="model">{{ model }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
     </div>

    <!-- 消息区域 -->
    <div :class="$style['message-box']" ref="containerTopRef">
      <div
          v-for="(item, index) in messageList"
          :key="index"
          :class="$style['message-group']"
      >
        <!-- 用户消息 -->
        <div v-if="item?.role === 'user'" :class="$style['user-message']">
          <div :class="$style['message-info']">
            <div :class="$style['user-name']">{{ props.isTeacher ? 'Student' : 'You' }}</div>
            <div :class="[$style['message-bubble'], $style['user-bubble']]">
              {{ item?.content }}
            </div>
          </div>
          <div :class="[$style['message-avatar'], $style['user-avatar']]">
            <span>{{ props.isTeacher ? 'S' : (store.user.name.charAt(0) || 'Y') }}</span>
          </div>
        </div>
        
        <!-- AI消息 -->
        <div v-if="item?.role === 'assistant'" :class="$style['ai-message']">
          <div :class="[$style['message-avatar'], $style['ai-avatar']]">
            <span>{{ data.model.charAt(0) }}</span>
          </div>
          <div :class="$style['message-info']">
            <div :class="$style['ai-name']">{{ data.model }}</div>
            <div :class="[$style['message-bubble'], $style['ai-bubble']]">
              {{ item?.content }}
            </div>
          </div>
        </div>
      </div>
      <div ref="messagesEndRef" />
    </div>

    <!-- 对话框区域，用于AI提问和提示词模版展现 -->
    <div v-if="!props.isTeacher">
      <div :class="$style['question-box']">
        <div :class="$style['input-group']">
          <el-input
              v-model="data.questionContent"
              ref="inputRef"
              :placeholder="`Message ${data.model} ...`"
              @focus="handleFocus"
          >
          </el-input>
          <el-button
              :disabled="data.questionContent === ''"
              @click="handleSendQuestion"
              style="width: 40px; border: none"
              v-loading="data.loading"
              :element-loading-spinner="svg"
              element-loading-svg-view-box="-10, -10, 50, 50"
              element-loading-background="rgba(122, 122, 122, 0.8)"
          >
            <el-icon><Top/></el-icon>
          </el-button>
          <el-dropdown @command="handleMenuClick">
            <el-button type="text" style="width: 40px;">
              <el-icon><ArrowDown/></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                    v-for="(template, index) in questionTemplates"
                    :key="index"
                    :command="index"
                >
                  {{ template }}
                </el-dropdown-item>
              </el-dropdown-menu>
              </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import "./AIChatter.module.scss";
  import type {IDialogue} from "@/types/dialogue.ts";
  import {useStore} from "@/store";
  import useApis from "@/apis";
  import {onMounted, reactive, ref, defineProps, watch, onUnmounted, nextTick} from "vue";
  import {ArrowDown, Top} from '@element-plus/icons-vue'
  import {ElMessage} from "element-plus";
  import emitter from "@/utils/emitter";
  import dayjs from "dayjs";

  // const svg = `
  //       <path class="path" d="
  //         M 30 15
  //         L 28 17
  //         M 25.61 25.61
  //         A 15 15, 0, 0, 1, 15 30
  //         A 15 15, 0, 1, 1, 27.99 7.5
  //         L 15 15
  //       " style="fill: rgba(0, 0, 0, 0)"/>
  //     `

  const svg = `
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; stroke: #0099FF; stroke-dasharray: 5 3; fill: url(#myGradient);">
  </path>
  <defs>
    <linearGradient id="myGradient" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stop-color="#FF5733" />
      <stop offset="100%" stop-color="#33FF57" />
    </linearGradient>
  </defs>
</svg>
`;
//update: 加入isTeacher属性，用于判断是否是教师批改界面
  interface IProps {
    dialogueId: string;
    messages: IDialogue[]
    isTeacher: boolean
  }

  const props = defineProps<{
    dialogueId: string,
    messages: IDialogue[]
    isTeacher: boolean
  }>()

  const apis = useApis()
  const store = useStore()
  //UPDATE: 目前只有ChatGLM4
  const modelOptions = ["ChatGLM4"]
  const questionTemplates = [
    "xxx是什么意思？",
    "英文如何描述xxx",
    "请用英文描述一个场景或一个观点：xxx",
    // 更多问题模板...
  ];
  let AICount = ref(0);

  const inputRef = ref(null);
  const messagesEndRef = ref(null);
  const containerTopRef = ref(null);

  // 用于处理ai对话展示异常问题
  let messageList:IDialogue[] = []

  let data = reactive<{
    model: string;
    questionContent: string;
    messages: IDialogue[];
    loading: boolean;
    loadedPage: number;
    pageSize: number;
  }>({
    model: modelOptions[0],
    questionContent: '',
    messages: [],
    loading: false,
    loadedPage: 0,
    pageSize: 20,
  });

  // 加载聊天记录，并滚动至最后
  onMounted(() => {
    if (props.messages) data.messages = props.messages;
    // console.log(props.messages)
    nextTick(scrollToEnd);
  });

  const scrollToEnd = () => {
    // messagesEndRef.value?.scrollIntoView({ behavior: 'smooth' });
    let container = containerTopRef.value
    container.scrollTo({ top: container.scrollHeight-1, behavior: 'smooth' });

  };

  watch(() => props.messages, (newMessages:any) => {
    if (newMessages)
      data.messages = newMessages;
    // console.log(newMessages)
    handleMessageList()
    nextTick(scrollToEnd);
  });

  watch(() => data.messages, () => {
    nextTick(scrollToEnd);
  });

  onMounted(() => {
    const handleScroll = () => {
      if (containerTopRef.value) {
        const { top } = containerTopRef.value.getBoundingClientRect() // 获取目标组件的位置
        const reachedTop = top >= 0;// 检查组件是否到达顶部

        // 确保，不重复加载数据
        if (reachedTop && !data.loading) {
          console.log("触顶了");
        }
      }
    };

    window.addEventListener('scroll', handleScroll);

    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });
  });

  // 发送问题
  const handleSendQuestion = () => {
    // 触发行为记录
    emitter.emit("click-ai-send-button", {
      insert: data.questionContent,
      type: "AIChatter",
      startTime: startTime,
      endTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss.SSS")
    })
    //限制会话次数
    if(AICount.value<10){
      AICount.value++
    } else {
      ElMessage.warning("单次只能使用10次对话功能")
      // AICount.value++
      return
    }
    data.loading = true;

    let requestBody:IDialogue[] = data.messages
    requestBody.push({
      role: 'user',
      content: data.questionContent
    })

    apis.requestAI(props.dialogueId, data.model, requestBody)
        .then((_res:any) => {
          const resDialogue = _res.data.data;
          data.messages.push(resDialogue);
          handleMessageList()
        })
        .catch((_err:any) => {
          console.log(_err);
        })
        .finally(() => {
          data.questionContent = '';
          data.loading = false;
          nextTick(scrollToEnd);
        });
  };

  const handleCommand = (command:string) => {
    data.model = command
  }

  // 选择模板问题
  const handleMenuClick = (key:any) => {
    data.questionContent = questionTemplates[key];
    inputRef.value.focus();// 设置焦点自动回到Input
  };

  // 处理ai对话显示异常问题
  const handleMessageList = () => {
    // console.log(data.messages)
    let count1 = 0
    let count2 = 1
    let userNum = 0
    let AssistantNum = 0
    //统计
    for(let message of data.messages){
      if(message == null){
        ElMessage.error("AI请求超时")
        return
      }
      if(message.role == "user"){
        userNum++
      } else {
        AssistantNum++
      }
    }
    if(userNum > AssistantNum) count2 = count2 + 2 * (userNum - AssistantNum)
    for(let message of data.messages){
      if(message.role == "user"){
        messageList[count1] = {
          role: "user",
          content: message.content
        }
        count1+=2
      }
      if(message.role == "assistant"){
        if(userNum == AssistantNum){
          messageList[count2] = {
            role: "assistant",
            content: message.content
          }
          count2+=2
        } else {
          messageList[count2] = {
            role: "assistant",
            content: message.content
          }
          count2+=2
        }
      }
    }
    // console.log(messageList)
  }

  // const recordKeyUp = (event:any) => {
  //   console.log(event)
  // }


  let startTime = null;
  // 用于记录AI对话的开始时间
  const handleFocus = () => {
    startTime = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss.SSS")
    console.log(startTime)
  }


</script>

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

<style module>
@import './AIChatter.module.scss';
</style>