<template>
  <div class="view-box"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave">
    <AiButton />
    <AiPane :aiContent="myParams.content" />
  </div>
</template>

<script setup lang="ts" name="AiReport">
import {reactive} from "vue"
import AiButton from '@/components/base/Ai/AiButton/index.vue';
import AiPane from '@/components/base/Ai/AiPane/index.vue';

const myParams = reactive({
  data: "",
  content: "",
  isState: false,
})

const onDataInfo = (event:any) => {
  console.log("需要分析的数据", event);
  myParams.isState = false;
  myParams.data = JSON.stringify(event);
}

let controller = null;
let reader = null;
// 鼠标进入监听
const handleMouseEnter = async () => {
  if (myParams.isState) return;

  myParams.content = "正在生成...";
  
  if (controller) controller.abort();
  controller = new AbortController();
  
  try {
    const res = await fetch('/aiAnalysis/chart_interpretation', {
      method: 'POST',
      headers: {
        "X-API-Key": "aircasKEY19491001",
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ text: myParams.data }),
      signal: controller.signal
    });

    if (!res.ok) throw new Error(`HTTP ${res.status}`);

    reader = res.body.getReader();
    const decoder = new TextDecoder();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      const chunk = decoder.decode(value, { stream: true });
      const match = chunk.match(/"解读":\s*"([^"]*)"/);
      if (match?.[1]) {
        myParams.content = match[1];
        myParams.isState = true;
        return; // 获取到结果直接返回
      }
    }
    myParams.content = "未获取到解读内容";
  } catch (err) {
    myParams.content = "系统异常，生成失败";
  } finally {
    reader?.cancel();
    reader = null;
  }
};

// 鼠标离开监听
const handleMouseLeave = () => {
  controller?.abort();
  reader?.cancel();
  controller = null;
  reader = null;
};

defineExpose({ onDataInfo })

</script>

<style scoped lang="scss">
.view-box {
  position: absolute;
  right: 0px;
  bottom: 15px;
  z-index: 2;

  :deep(.ai-pane-wrapper) {
    display: none;
  }

  :deep(.ai-button-wrapper) {
    display: flex;
  }

  &:hover {
    width: 100%;
    bottom: 0px;

    :deep(.ai-pane-wrapper) {
      display: block;
    }

    :deep(.ai-button-wrapper) {
      display: none;
    }
  }
}
</style>