<template>
  <div class="ai-box">
    <div class="left-box" v-if="state.list.length > 0">
      <div class="content answer-box" id="answer-box">
        <div class="item-box" v-for="(item, index) in state.list" :key="index">
          <div class="item right">
            <span class="text"> {{ item.question }} </span>
          </div>
          <div class="item left">
            <MarkdownViewer :value="item.answer" />
            <div v-if="isShowFill && item.answer" class="mt-1.5">
              <a-tag
                :color="isReadOnly ? 'default' : 'blue'"
                :class="['!border-0', isReadOnly ? 'cursor-not-allowed' : 'cursor-pointer']"
                @click="handleFillComponent(item.answer)"
              >
                填充至组件
              </a-tag>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="left-box" v-else>
      <div class="content answer-box p-2.5">暂无答案,请先输入问题</div>
    </div>
    <div class="right-box">
      <div class="title"><span>Ai</span>解题答疑</div>
      <div class="content" @keypress.enter="sendSseAi">
        <FormItemRest>
          <a-textarea
            :bordered="false"
            v-model:value="question"
            :readonly="isReadOnly"
            placeholder="请输入需要咨询的问题"
            :rows="4"
          />
        </FormItemRest>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { Form } from 'ant-design-vue';
  import { getAppEnvConfig } from '/@/utils/env';
  import { MarkdownViewer } from '/@/components/Markdown';
  import { useUserStore } from '/@/store/modules/user';

  defineProps({
    isShowFill: {
      type: Boolean,
      default: false,
    },
  });

  const FormItemRest = Form.ItemRest;

  const userStore = useUserStore();
  const emits = defineEmits(['getFillVal']);
  const question = ref<string>('');
  const answer = ref<string>('');
  const isReadOnly = ref<boolean>(false);
  const state = reactive({
    list: [] as Array<{ question: string; answer?: string }>,
  });

  const sendSseAi = async () => {
    if (!answer.value && !!question.value.trim()) {
      const clientId = userStore.getToken; // 唯一客户端标识（可动态生成）
      const message = question.value; // 唯一客户端标识（可动态生成）
      const eventSource = new EventSource(
        `${
          getAppEnvConfig().VITE_GLOB_API_URL
        }/system/ai/kimi/chat?clientId=${clientId}&message=${encodeURIComponent(message)}`,
      );
      const obj = { question: question.value, answer: '' };
      state.list.push(obj);
      scrollToBottom();

      isReadOnly.value = true;
      question.value = '';

      // 通用消息监听（不指定事件名时触发）
      eventSource.onmessage = (event) => {
        const message = event.data;
        const info: string = message.replace('data: ', '').trim() || ''; // 去除前缀 "data: "
        if (info === '[DONE]') {
          answer.value = '';
          isReadOnly.value = false;
        } else {
          if (info.includes('```')) {
            answer.value += '\r\n' + info;
          } else if (info === '') {
            answer.value += '\r\n';
          } else {
            answer.value += info;
          }
          console.log('answer:', answer.value);
          state.list[state.list.length - 1].answer = answer.value;
          scrollToBottom();
        }
      };

      // 错误处理
      eventSource.onerror = () => {
        // console.error('SSE Error:', error);
        isReadOnly.value = false;
        answer.value = '';
        eventSource.close();
      };
    }
  };

  const scrollToBottom = () => {
    const divElement = document.getElementById('answer-box');
    if (divElement) {
      divElement.scrollTop = divElement?.scrollHeight;
    }
  };

  const handleFillComponent = (info) => {
    if (isReadOnly.value) return;
    emits('getFillVal', info);
  };
</script>
<style lang="less" scoped>
  .ai-box {
    border: 1px solid #f2f2f2;
    font-size: 14px;
    background: #fff;

    .left-box {
      display: flex;
      align-items: center;
    }

    .right-box {
      border: 1px solid #f3f3f3;
      border-radius: 10px;
      margin: 10px;
      box-shadow: 0 5px 5px 0 #f3f3f3;

      .title {
        padding: 5px 10px;
        font-weight: bold;
        background: #fcfcfc;
        border-radius: 10px 10px 0 0;

        span {
          font-size: 18px;
          margin-right: 5px;
        }
      }

      .content {
        overflow: auto;
        padding: 10px 5px;
        height: 110px;
      }
    }

    .answer-box {
      color: rgb(0 0 0 / 80%);
    }

    .content {
      flex: 1;
      display: flex;
      flex-flow: column;
      min-height: 46px;
      box-sizing: border-box;
      max-width: 100%;
      position: relative;
      height: 170px;
      overflow: scroll;
    }
  }

  .item-box {
    display: flex;
    flex-direction: column;

    .text {
      width: 100%;
    }

    .item {
      display: flex;
    }

    .left {
      align-self: flex-start;
      flex-direction: column;
      max-width: calc(100% - 10px);
      margin-left: 10px;
    }

    .right {
      align-self: flex-end;
      background: #f3f3f3;
      padding: 5px 15px;
      border-radius: 5px;
      margin: 15px 10px;
      max-width: calc(100% - 20px);
    }
  }

  :deep(.vditor-reset > p) {
    font-size: 14px;
  }
</style>
