<template>
  <div class="custom-gpt-page">
    <div class="message-box"></div>
    <div class="input">
      <t-input v-model="gpt_input"></t-input>
      <t-button @click="submit">发送</t-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Input as TInput, Button as TButton } from 'tdesign-vue-next';
import { EventSourcePolyfill } from 'event-source-polyfill';
import { submitmessage } from '@/utils/api/gpt';
import { getUserCookie } from '@/utils/api/userApi';
import { ref } from 'vue';
const gpt_input = ref('');
// 提交消息
const submit = async () => {
  try {
    let res: any = await submitmessage({
      prompt: gpt_input.value,
      regen: false,
    });
    if (res.code == 0 && res.data.chat_id) {
      console.log('发送成功');
      //   发起会话
      const eventSource = new EventSourcePolyfill(
        `/api/gpt/stream?chat_id=${res.data.chat_id}`,
        {
          headers: {
            authorization: `Bearer ${getUserCookie()}`,
          },
        }
      );
      eventSource.onmessage = function (e: any) {
        if (e.data == '[DONE]') {
          eventSource.close();
        } else {
          let word = JSON.parse(e.data).choices[0].delta.content;
          if (word !== undefined) {
            console.log(word);
          }
        }
      };
      eventSource.onerror = function (e: any) {
        console.log(e);
        eventSource.close();
        console.log('报错了');
      };
    }
  } catch (e) {
    console.log(e);
  }
};
</script>

<style lang="less">
.custom-gpt-page {
  padding: 40px;
  box-sizing: border-box;
  .message-box {
  }
  .input {
    display: flex;
    & > :nth-child(2) {
      margin-left: 12px;
    }
  }
}
</style>
