<template>
  <div
    :style="{width:props.dimensions.width+'px',height:props.dimensions.height+'px'}">
    <NodeResizer :color="dataIsJson?'#ff0000':'#fff'" v-if="!props.isView && !props.isHideHandle && props.selected"
                 @resize="resize" />

    <div class="custom-node"
         :style="{width:props.dimensions.width+'px',height:props.dimensions.height+'px',pointerEvents:props.isView?'auto': 'none'}">
      <el-input ref="textArea" type="textarea" v-model="input" placeholder="输入JSON"
                style="width: 100%;height: 100%;" />
    </div>
    <Handle v-if="!props.isView" :id="`${props.id}.-t`" type="target" :position="Position.Left" />
    <Handle v-if="!props.isView" :id="`${props.id}.-s`" type="source" :position="Position.Right" />
  </div>
</template>
<script setup>
import { defineEmits, defineProps, ref } from 'vue';
import { NodeResizer } from '@vue-flow/node-resizer';
import { Handle, Position } from '@vue-flow/core';
import { options } from '../../tool.js';

const { isJSON } = options;
const input = ref('');
const dataIsJson = ref(true);
const textArea = ref();
const props = defineProps({
  isView: {
    type: Boolean,
    required: false
  },
  inputData: {
    type: Object,
    required: false
  },
  id: {
    type: String,
    required: true
  },
  isHideHandle: {
    type: Boolean,
    required: false
  },
  selected: {
    type: Boolean,
    required: false
  },
  data: {
    type: Object,
    required: true
  },
  dimensions: {
    type: Object,
    required: true
  }
});

watch(() => [JSON.parse(JSON.stringify(props.data.options?.defaultInputArea || '')), JSON.parse(JSON.stringify(props.data.options?.field || ''))], (obj1, obj2) => {
  if (JSON.stringify(obj1) !== JSON.stringify(obj2)) {
    input.value = props.data.options.defaultInputArea;
    if (isJSON(input.value)) {
      dataIsJson.value = true;
      textArea.value && (textArea.value.textarea.style.backgroundColor = '#fff');
      textArea.value && (textArea.value.textarea.style.color = '#606266');
      let value = JSON.parse(input.value);
      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        Object.keys(value).forEach(key => {
          props.data.outputData[key] = value[key];
        });
      } else {
        props.data.outputData[props.data.options?.field || 'input'] = value;
      }

    } else {
      textArea.value && (textArea.value.textarea.style.backgroundColor = '#ff0000');
      textArea.value && (textArea.value.textarea.style.color = '#fff');
      dataIsJson.value = false;
    }
  }
}, { deep: true, immediate: true });
const emit = defineEmits(['resize']);
const resize = (e) => {
  emit('resize', e, props.id);
};
</script>
<style scoped>
.custom-node {
  position: absolute;
}

:deep(.el-textarea__inner) {
  height: 100%;
}
</style>

