<template>
  <div
    :style="{width:props.dimensions.width*props.ratioWidth+'px',height:props.dimensions.height*props.ratioHeight+'px'}">
    <NodeResizer @resizeEnd="(e) => $emit('resize', e)" color="#fff"
                 v-if="!props.isView && !props.isHideHandle && props.selected" @resize="resize" />

    <div class="custom-node"
         :style="{width:props.dimensions.width*props.ratioWidth+'px',height:props.dimensions.height*props.ratioHeight+'px',pointerEvents:props.isView?'auto': 'none'}">
      <el-button :type="isErr ? 'danger':'primary'"
                 :style="{width:props.dimensions.width*props.ratioWidth  +'px',height:props.dimensions.height*props.ratioHeight+'px'}"
                 :icon="Connection">{{ props.data.customData.name }}
      </el-button>
      <span style="color:#fff">
      </span>
    </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 { Connection } from '@element-plus/icons-vue';
import { Handle, Position } from '@vue-flow/core';
import request from '@/utils/request';
import axios from 'axios';
import { options } from '../../tool.js';
import { querySql, querySql1 } from '@/views/boardGenerate/api/dataSource.js';

const isErr = ref(false);
const props = defineProps({
  ratioWidth: {
    type: Number,
    required: false,
    default: 1
  },
  ratioHeight: {
    type: Number,
    required: false,
    default: 1
  },
  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
  }
});
const anyFun = (data, fun, key) => {
  switch (fun) {
    case 'map':
      return data.map(e => e[key]);
    default:
      return null;
  }
};
const parseData = (data, rule) => {
  let resData = data;
  let step = rule.split(',');
  step.forEach((item) => {
    if (resData) {
      let fun = item.split('%');
      if (fun.length === 1) {
        resData = resData[fun[0]];
      }
      if (fun.length === 2) {
        resData = anyFun(resData, fun[0], fun[1]);
      }
    }
  });
  return resData;

};
const formulaFun = (formula) => {
  let data = formula.replace(/\$\{\s*([^}]+?)\s*\}/g, (_, key) => {
    let infos = key.split(',');
    if (infos.length === 1) {
      return props.inputData[infos[0]] || '%%';
    }
    if (infos.length === 2) {
      return `AND ${infos[0]} = ${props.inputData[infos[1]] || '%%'}`;
    }
  });
  return data;
};
let timestamp = Date.now();
const getOutputData = () => {
  if (Date.now() < timestamp + 900) {
    return;
  }
  let params = props.inputData;
  (Object.keys(props.inputData) || []).forEach((item) => {
    params[item.name] = props.inputData[item.name];
  });
  if (props.data.customData.type === '1' || !props.data.customData.type) {
  (options.isD ? request : axios.request)({
    method: props.data.customData.method,
    url: props.data.customData.url,
    params: props.data.customData.method === 'get' ? params : '',
    data: props.data.customData.method === 'post' ? params : ''
  }).then(res => {
    isErr.value = false;
    let data = (options.isD ? res : res.data || res.rows);
    let output = {};
    props.data.customData.outputData.forEach(item => {
      output[item.fieldOne] = parseData(data, item.fieldTwo);
    });
    props.data.outputData = output;
  }).catch(e => {
    isErr.value = true;
  });
  }
  if (props.data.customData.type === '2') {
    console.log('props.data.customData.type', props.data.customData.isPage);
    if (props.data.customData.isPage) {

      querySql1({
        sql: formulaFun(props.data.customData.SQL),
        linkId: props.data.customData.db,
        pageSize: props.inputData.pageSize,
        pageNum: props.inputData.pageNum
      }).then((res) => {
        isErr.value = false;
        let data = res;
        let output = {};
        props.data.customData.outputData.forEach(item => {
          output[item.fieldOne] = parseData(data, item.fieldTwo);
        });
        props.data.outputData = output;
        console.log(output);
      }).catch(e => {
        isErr.value = true;
      });
    } else {
      querySql(formulaFun(props.data.customData.SQL), props.data.customData.db).then((res) => {
        isErr.value = false;
        let data = res;
        let output = {};
        props.data.customData.outputData.forEach(item => {
          output[item.fieldOne] = parseData(data, item.fieldTwo);
        });
        props.data.outputData = output;
      }).catch(e => {
        isErr.value = true;
      });
    }
  }
};
onMounted(() => {
  setTimeout(() => {
    getOutputData();
  }, 1000);

});


watch(() => JSON.parse(JSON.stringify([props.inputData])), (obj1, obj2) => {
  if (JSON.stringify(obj1) !== JSON.stringify(obj2)) {
    getOutputData();
  }
}, { deep: true, immediate: true });

let interval = props.data.options?.timeout === -1 ? null : setInterval(() => {
  getOutputData();
}, Math.max((props.data.options?.timeout || 5) * 1000, 1000));

onBeforeUnmount(() => {
  clearInterval(interval);
  interval = null;
});
const emit = defineEmits(['resize']);
const resize = (e) => {
  emit('resize', e, props.id);
};
</script>
<style scoped>
.custom-node {
  width: 100%;
  height: 100%;
}

</style>
