<template>
  <div class="node__container" :class="props.model.id">
    <keep-alive>
      <NodeState :state="nodeOperatingStatus" :runtimes="runtimes" ref="nodeStateRef">
        <template #input>
          <JsonViewer :value="inputJsonData" copyable boxed sort theme="light" />
        </template>
        <!-- <template #output>
        <JsonViewer :value="outputJsonData" copyable boxed sort theme="light" />
      </template> -->
      </NodeState>
    </keep-alive>
    <div class="terminal-node">
      <div class="terminal-node__icon"><img src="../../icon/start.svg" alt="" /></div>
      <div class="terminal-node__content">
        <div class="terminal-node__title">流程开始</div>
        <div class="terminal-node__description">接收流程输入并启动工作流</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import NodeState from "../../components/NodeState.vue";
import "vue3-json-viewer/dist/index.css";
import { useFlowEvents } from "../../composables/useFlowEvents";

const { onFlowEvent } = useFlowEvents();

const props = defineProps({
  model: Object,
  properties: Object,
});
const emits = defineEmits(["contentChange"]);


const nodeOperatingStatus = ref("NORMAL");
const runtimes = ref(0);
const inputJsonData = ref({});
const outputJsonData = ref({});

const nodeStateRef = ref(null);

const closePopover = () => {
  if (nodeStateRef.value) {
    nodeStateRef.value.closePopover();
  }
}

onMounted(() => {
  onFlowEvent("changeNodeState", (data) => {
    if (data.nodeId === props.model.id) {
      nodeOperatingStatus.value = data.status;
      if (data.endTime && data.startTime) {
        runtimes.value = data.endTime - data.startTime;
      }
      let inputData = {};
      let output = {};
      try {
        inputData = JSON.parse(data.paramsIn) || {};
        output = JSON.parse(data.paramsOut) || {};
      } catch (error) {
        inputData = data.paramsIn || {};
        output = data.paramsOut || {};
      }
      inputJsonData.value = inputData;
      outputJsonData.value = output;

      emits("contentChange");
    }
  });

  onFlowEvent("contentChange", (data) => {
    if (data.id === props.model.id) {
      nodeOperatingStatus.value = "NORMAL";
      inputJsonData.value = {};
      outputJsonData.value = {};

      emits("contentChange");
    }
  });

  onFlowEvent("setProperties", (data) => {
    if (data.id === props.model.id) {
      emits("contentChange");
    }
  });
});


defineExpose({ closePopover })

</script>
