<template>
  <common-drawer :width="1000" :visible="true" @close="close" :mask="true" :mask-closable="true" :isShowTab="false">
    <template #title>
      <template v-if="titleEdit">
        <a-input
          v-focus
          type="text"
          v-model:value="title"
          @blur="editTitle"
          @keydown.enter="editTitle"
          autofocus="autofocus"
          ref="titleInputRef"
        />
      </template>
      <template v-if="!titleEdit">
        <span style="cursor: pointer" @click="titleClick">{{ title }}</span>
        <span style="padding-left: 5px; cursor: pointer" @click="titleClick"><edit-outlined /></span>
      </template>
    </template>

    <template #footer>
      <a-button type="primary" @click="save" class="border-radius">确定</a-button>
    </template>

    <message-listening-form
      v-model:nodeListener="formData.nodeListener"
      v-if="formData"
      ref="messageListeningFormRef"
    ></message-listening-form>
  </common-drawer>
</template>

<script setup name="MessageListeningPanel">
import { onMounted, ref } from 'vue';
import loadNodeData from '../../../utils/utils';
import MessageListeningForm from './form/MessageListening/message_listening_form.vue';
import { message } from 'ant-design-vue/es';

// 公共方法
const { getNodeData, setNodeData, node } = loadNodeData();

const emits = defineEmits(['close']);
// 节点数据
const nodeData = ref({});

// 标题
const title = ref('');
// 标题输入框dom
const titleInputRef = ref(null);
// 是否编辑标题
const titleEdit = ref(false);

// 当前节点的数据
const currentNodeData = ref(getNodeData());

// 消息监听数据
const formData = ref(null);

// ref
const messageListeningFormRef = ref();

/**
 * 修改标题
 */
const editTitle = () => {
  let getGraphNodeData = getNodeData();
  getGraphNodeData.data.nodeName = title.value;

  setNodeData(getGraphNodeData);

  // 关闭标题编辑框
  titleEdit.value = false;
};

/**
 * 标题点击
 */
const titleClick = () => {
  titleEdit.value = true;
};

/**
 * 关闭
 */
const close = () => {
  emits('close', false);
};

// 点击保存
const save = () => {
  messageListeningFormRef.value.$refs.formRef
    .validate()
    .then(valid => {
      let saveData = getNodeData();
      saveData.data.nodeData = formData.value;
      setNodeData(saveData);
      close();
    })
    .catch(e => {
      message.warning(e.errorFields[0].errors[0]);
    });
};

onMounted(() => {
  nodeData.value = JSON.parse(node.value.data);

  // 设置弹窗标题
  title.value = nodeData.value.data.nodeName;

  if (JSON.stringify(currentNodeData.value?.data?.nodeData) != '{}') {
    formData.value = Object.assign({}, currentNodeData.value.data.nodeData);
    if (!formData.value?.nodeListener?.listenerUrl) {
      formData.value.nodeListener.listenerUrl = import.meta.env.VITE_API_URL;
    }
    if (!formData.value.nodeListener?.listenerHttpMethod) {
      formData.value.nodeListener.listenerHttpMethod = 'POST';
    }
  }
});
</script>

<style scoped></style>
