<!--
 * @Author: HTangtang 1539880046@qq.com
 * @Date: 2025-01-21 14:41:20
 * @LastEditors: HTangtang 1539880046@qq.com
 * @LastEditTime: 2025-03-06 17:49:40
 * @FilePath: \dam_app_project\pages\smartAi\components\eventSource.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- #ifdef H5 -->
  <view id="event-source" :props="mergeProps" :change:props="eventSource.renderPropsChange" v-show="false">
  </view>
  <!-- #endif -->

  <!-- #ifdef MP-WEIXIN -->
  <view id="event-source" v-show="false">
  </view>
  <!-- #endif -->
</template>

<script>
export default {
  props: {
    url: {
      type: String,
      default: "",
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      isSend: false
    }
  },
  computed: {
    // 合并传入renderjs的数据
    mergeProps({ url, options, isSend }) {
      return {
        url,
        options,
        isSend
      };
    },
  },
  methods: {
    // 发送
    send() {
      // #ifdef H5
      this.isSend = true;
      this.$nextTick(() => {
        this.isSend = false;
      });
      // #endif

      // #ifdef MP-WEIXIN
      const { url, options = {} } = this;
      const { headers, method, body } = options;

      this.$emit("callback", { type: "onopen", msg: "Connection opened." });

      uni.request({
        url: url,
        method: method || 'POST',
        header: headers,
        data: JSON.parse(body),
        success: (res) => {
          if (res.statusCode === 200) {
            // 看起来返回的res.data是一个字符串,需要先处理掉开头的"data:"
            // const rawData = res.data.replace(/^data:/, '');
            // 然后解析JSON
            console.log('Raw data:', res.data.split('data:').filter(item => item.trim() !== ''));
            res.data.split('data:').filter(item => item.trim() !== '').forEach(item => {
              const parsedData = JSON.parse(item);
              console.log(item, parsedData, 5454545)
              this.$emit("callback", { type: "onmessage", msg: "Message received.", data: JSON.stringify(parsedData) });  // 发送解析后的数据
            });
            // const parsedData = JSON.parse(rawData);
            // this.$emit("callback", {
            //   type: "onmessage",
            //   msg: "Message received.",
            //   data: JSON.stringify(parsedData)  // 发送解析后的数据
            // });
          } else {
            this.$emit("callback", { type: "onerror", msg: "Request failed.", data: JSON.stringify(res) });
          }
        },
        fail: (error) => {
          this.$emit("callback", { type: "onerror", msg: "Request error.", data: JSON.stringify(error) });
        },
        complete: () => {
          this.$emit("callback", { type: "onclose", msg: "Connection closed." });
        }
      });
      // #endif
    },
    // 处理renderjs发回的数据
    emits(e) {
      this.$emit("callback", { ...e });
    },
  },
};
</script>

<script module="eventSource" lang="renderjs">
// #ifdef H5
import { fetchEventSource } from "@microsoft/fetch-event-source";
export default {
  methods: {
    // 传入数据变更
    renderPropsChange(nVal) {
      const { url, isSend } = nVal || {};
      if (!isSend) return;
      if (!url) return this.handleEmitData({ type: "tip", msg: "URL cannot be empty." });
      this.$nextTick(() => {
        this.handleSSE(nVal);
      });
    },
    // 发送数据到service层
    handleEmitData(data = {}) {
      this.$ownerInstance.callMethod('emits', data);
    },
    // 处理SSE (H5)
    handleSSE(opts = {}) {
      const that = this;
      if (!('EventSource' in window)) return this.handleEmitData({ type: "tip", msg: "The current device does not support EventSource." });
      const { url, options = {} } = opts || {};
      fetchEventSource(url, {
        ...options,
        async onopen() {
          that.handleEmitData({ type: "onopen", msg: "EventSource onopen." });
        },
        onmessage(res) {
          that.handleEmitData({ type: "onmessage", msg: "EventSource onmessage.", data: res.data });
        },
        onclose() {
          that.handleEmitData({ type: "onclose", msg: "EventSource onclose." });
        },
        onerror(error) {
          that.handleEmitData({ type: "onerror", msg: "EventSource onerror.", data: JSON.stringify(error) });
        }
      });
    }
  }
}
// #endif
</script>
