<script lang="tsx">
import { message as antdMessage, Tooltip } from 'ant-design-vue';
import { BubbleList } from '@/components/xt-chat/xt-bubble';
import SenderInput from './components/sender-input/index.vue';
import { Typography } from 'ant-design-vue';
import RightView from './components/right-view/index.vue';

import { useRoute } from 'vue-router';
import { genRandomId } from '@/utils/tools';
import { useChatStore } from '@/stores/modules/chat';
import querySSE from '@/utils/querySSE';

import useChatHandler from './useChatHandler';
import { QUESTION_ROLE, ANSWER_ROLE } from './constants';

export default {
  props: {
    inputInfo: {
      type: Object as () => CHAT.TInputInfo,
      default: null,
    },
  },
  setup(props, { emit, expose }) {
    const chatStore = useChatStore();

    const route = useRoute();

    const senderRef = ref(null);
    const rightViewRef = ref(null);
    const bubbleListRef = ref<any>(null);

    const { roles, showRightView, rightViewContent, currentTaskId, handleMessage, conversationList, generateLoading } =
      useChatHandler();

    const conversationId = computed(() => {
      return route.params.conversationId;
    });

    const handleSubmit = (message: string) => {
      if (generateLoading.value) {
        antdMessage.warning('停止生成后可发送');
        return;
      }

      initSse({ message });
    };

    const handleCancel = () => {
      generateLoading.value = false;
      // 中止当前正在输出的回答
      if (currentTaskId.value && bubbleListRef.value?.abortTypingByKey) {
        bubbleListRef.value.abortTypingByKey(currentTaskId.value);
      }
      if (showRightView.value) {
        rightViewRef.value?.abortTyping?.();
      }
      antdMessage.info('取消生成');
    };

    const initSse = (inputInfo: CHAT.TInputInfo) => {
      try {
        const { message } = inputInfo;

        generateLoading.value = true;
        conversationList.value.push({
          role: QUESTION_ROLE,
          content: message,
        });

        const taskId = genRandomId();
        currentTaskId.value = taskId;

        const url = `http://localhost:3000/agent/input?content=${message}&session_id=${conversationId.value}&agent_id=${chatStore.agentInfo?.agent_id}`;
        querySSE(
          {
            handleMessage,
          },
          url,
        );
      } catch (error) {
        console.error('Failed to initialize SSE:', error);
        antdMessage.error('初始化连接失败');
        generateLoading.value = false;
      }
    };

    watch(
      () => props.inputInfo,
      (newVal) => {
        newVal && initSse(newVal);
      },
      { deep: true },
    );

    return () => (
      <div class="chat-view-wrap w-full h-full flex">
        <section class="flex-1 flex flex-col pt-20px justify-center relative px-16px">
          <div class="flex-1 overflow-hidden pb-20px">
            <BubbleList
              ref={bubbleListRef}
              roles={roles}
              items={[
                ...conversationList.value,
                generateLoading.value ? { loading: true, role: ANSWER_ROLE } : null,
              ].filter(Boolean)}
            />
          </div>
          <div class="w-full flex flex-col justify-center items-center">
            <SenderInput
              class="w-600px"
              ref={senderRef}
              placeholder="继续追问..."
              loading={generateLoading.value}
              onSubmit={handleSubmit}
              onCancel={handleCancel}
            />
            <p class="cts !color-#939499 text-12px !lh-20px my-4px">内容由AI生成，仅供参考</p>
          </div>
        </section>

        {/* 右侧展示区域 */}
        {showRightView.value && (
          <RightView
            ref={rightViewRef}
            rightViewContent={rightViewContent.value}
            showRightView={showRightView.value}
            onClose={() => (showRightView.value = false)}
          />
        )}
      </div>
    );
  },
};
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
