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

    <!-- 内容 -->
    <div class="content">
      <div class="content-title">类型:</div>
      <div class="node-list">
        <template v-for="(item, index) in optionalNodeList" :key="index">
          <new-node-item
            style="margin-bottom: 20px; width: 100px"
            :node-data="item"
            @click="changeItem(item)"
            :iconList="iconList"
            type="bpmn"
            :class="[{ active: item.type == currentNodeData.type }]"
          >
          </new-node-item>
        </template>
      </div>
      <a-form
        ref="formRef"
        style="padding-top: 10px"
        labelAlign="right"
        v-if="currentNodeData.data.nodeData?.bpmnConfig"
        :model="currentNodeData.data.nodeData.bpmnConfig"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item name="bpmnNodeId" label="bpmn节点id">
          <a-input v-model:value="currentNodeData.data.nodeData.bpmnConfig.bpmnNodeId" placeholder="请输入bpmn节点id" />
        </a-form-item>
        <a-form-item name="remark" label="注释">
          <a-textarea v-model:value="currentNodeData.data.nodeData.bpmnConfig.remark" placeholder="请输入" :rows="8" />
        </a-form-item>

        <!-- 事件 -->
        <template v-if="currentNodeType >= 100 && currentNodeType < 190">
          <a-form-item name="attachedToActivityRef" label="附加到活动">
            <a-input
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.attachedToActivityRef"
              placeholder="请输入附加到活动节点的id"
            />
          </a-form-item>
          <a-form-item name="interruptingType" label="中断类型">
            <a-select
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.interruptingType"
              allowClear
              placeholder="请选择中断类型"
              style="width: 100%"
            >
              <a-select-option value="Interrupting">Interrupting</a-select-option>
              <a-select-option value="Non-Interrupting">Non-Interrupting</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item name="triggerCondition" label="触发条件">
            <a-input v-model:value="currentNodeData.data.nodeData.bpmnConfig.triggerCondition" placeholder="请输入表达式" />
          </a-form-item>
        </template>

        <!-- 活动 -->
        <template v-if="currentNodeType >= 190 && currentNodeType < 230">
          <a-form-item name="attachedToActivityRef" label="执行者">
            <a-input
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.executorName"
              placeholder="请选择执行者"
              @focus="executorNameClick"
            />
          </a-form-item>
          <a-form-item name="inputData" label="输入数据">
            <a-textarea v-model:value="currentNodeData.data.nodeData.bpmnConfig.inputData" placeholder="请输入输入数据" :rows="4" />
          </a-form-item>
          <a-form-item name="outputData" label="输出数据">
            <a-textarea v-model:value="currentNodeData.data.nodeData.bpmnConfig.outputData" placeholder="请输入输出数据" :rows="4" />
          </a-form-item>
          <a-form-item name="priority" label="优先级">
            <a-input-number v-model:value="currentNodeData.data.nodeData.bpmnConfig.priority" style="width: 100%" />
          </a-form-item>
          <a-form-item name="condition" label="触发条件">
            <a-input v-model:value="currentNodeData.data.nodeData.bpmnConfig.condition" placeholder="请输入表达式" />
          </a-form-item>
          <a-form-item name="loopTime" label="循环次数">
            <a-input-number v-model:value="currentNodeData.data.nodeData.bpmnConfig.loopTime" :defaultValue="1" style="width: 100%" />
          </a-form-item>
        </template>

        <!-- 网关 -->
        <template v-if="currentNodeType >= 230 && currentNodeType < 260">
          <a-form-item name="defaultCondition" label="默认路径">
            <a-select
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.defaultCondition"
              allowClear
              placeholder="请选择默认路径"
              style="width: 100%"
            >
              <a-select-option :value="deItem.nodeId" v-for="deItem in defaultRouteList" :key="deItem.nodeId">{{
                deItem.nodeName
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item name="eventType" label="事件类型">
            <a-select
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.eventType"
              allowClear
              placeholder="请选择事件类型"
              style="width: 100%"
            >
              <a-select-option value="Exclusive">Exclusive</a-select-option>
              <a-select-option value="Parallel">Parallel</a-select-option>
            </a-select>
          </a-form-item>
        </template>

        <!-- 数据对象 -->
        <template v-if="currentNodeType >= 280 && currentNodeType < 290">
          <a-form-item name="dataType" label="数据类型">
            <a-select
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.dataType"
              allowClear
              placeholder="请选择数据类型"
              style="width: 100%"
            >
              <a-select-option value="String">String</a-select-option>
              <a-select-option value="Integer">Integer</a-select-option>
              <a-select-option value="Boolean">Boolean</a-select-option>
              <a-select-option value="Double">Double</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item name="initialValue" label="初始值">
            <a-textarea v-model:value="currentNodeData.data.nodeData.bpmnConfig.initialValue" placeholder="请输入初始值" :rows="4" />
          </a-form-item>
          <a-form-item name="arrayFlag" label="是否集合">
            <a-radio-group v-model:value="currentNodeData.data.nodeData.bpmnConfig.arrayFlag">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item name="visibility" label="可见性">
            <a-select
              v-model:value="currentNodeData.data.nodeData.bpmnConfig.visibility"
              allowClear
              placeholder="请选择可见性"
              style="width: 100%"
            >
              <a-select-option value="Public">Public</a-select-option>
              <a-select-option value="Private">Private</a-select-option>
            </a-select>
          </a-form-item>
        </template>
      </a-form>
    </div>

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

    <!-- 选择人员 -->
    <Selection
      v-model:visible="visibleFlowPick"
      v-if="visibleFlowPick"
      :data="selectedData"
      :showTab="['user']"
      title="选择执行者"
      @done="closeFlowPick"
    ></Selection>
  </common-drawer>
</template>

<script setup name="BpmnNodeEdit">
import { ref, onMounted, computed, inject } from 'vue';
import AllBpmnData from '../../data/all-bpmn.json';
import NewNodeItem from '../left/new_node_item.vue';
import { getBpmnFlowIcon } from '@/utils/common/util';

const props = defineProps({
  visible: Boolean,
  bpmnNodeData: Object
});

const emits = defineEmits(['update:visible', 'done']);

// 画布
const getGraph = inject('getGraph');

// 是否编辑标题
const titleEdit = ref(false);

const iconList = ref(getBpmnFlowIcon());

// 是否显示选择人员弹框
const visibleFlowPick = ref(false);

// 总数据
const selectedData = ref({
  selectUserList: []
});

// 节点类型
const currentNodeType = computed(() => {
  return props.bpmnNodeData.type;
});

// 默认路径列表
const defaultRouteList = ref([]);

// 可选节点列表
const optionalNodeList = computed(() => {
  const nodeData = AllBpmnData.nodeGroups.find(item => item.id == props.bpmnNodeData.parent);
  return nodeData.nodes.filter(item => item.id != 248);
});

const getGraphNode = computed(() => {
  return getGraph.value.getNodes().find(({ id }) => props.bpmnNodeData.data.nodeId === id);
});

onMounted(() => {
  if (JSON.stringify(currentNodeData.value.data.nodeData) == '{}') {
    currentNodeData.value.data.nodeData.bpmnConfig = {};
  }

  getDefaultRouteList();
});

// 获取默认路径列表
const getDefaultRouteList = () => {
  if (currentNodeType.value >= 230 && currentNodeType.value < 260) {
    const node = getGraph.value.getCellById(props.bpmnNodeData.data.nodeId); // 通过 ID 获取节点

    // 获取与当前节点相连的所有边
    const connectedEdges = getGraph.value.getConnectedEdges(node);
    // // 遍历每一条边，获取相连的节点数据
    let arr = [];
    connectedEdges.forEach(edge => {
      const sourceNode = edge.getSourceNode();
      const targetNode = edge.getTargetNode();

      // 来源
      const sourceNodeData = sourceNode ? JSON.parse(sourceNode.getData()) : null;
      // 目标
      const targetNodeData = targetNode ? JSON.parse(targetNode.getData()) : null;

      if (sourceNodeData.type == props.bpmnNodeData.type) {
        arr.push(targetNodeData.data);
      }
    });

    defaultRouteList.value = [...arr];
  }
};

// 获取当前node数据
const getNodeData = () => {
  return JSON.parse(getGraphNode.value.getData());
};

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

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

/**
 * 修改标题
 */
const editTitle = () => {
  // 关闭标题编辑框
  titleEdit.value = false;
};

// 设置节点数据
const setNodeData = getGraphNodeData => {
  getGraphNode.value.setData(JSON.stringify(getGraphNodeData), {
    // 必须覆盖，否则出错
    overwrite: true
  });
};

// 切换节点属性
const changeItem = item => {
  if (item.type != currentNodeData.value.type) {
    currentNodeData.value.type = item.type;
    currentNodeData.value.icon = item.icon;
    currentNodeData.value.data.nodeType = item.type;
  }
};

const save = () => {
  setNodeData(currentNodeData.value);
  updateVisible(false);
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 执行者点击
const executorNameClick = () => {
  const { executorName, executorId } = currentNodeData.value.data.nodeData.bpmnConfig;
  if (executorName && executorId) {
    selectedData.value.selectUserList = [{ bizId: executorId, name: executorName }];
  }
  visibleFlowPick.value = true;
};

// 关闭选择弹框
const closeFlowPick = data => {
  const { bizId, name } = data.selectUserList[0] || { bizId: '', name: '' };
  currentNodeData.value.data.nodeData.bpmnConfig.executorName = name;
  currentNodeData.value.data.nodeData.bpmnConfig.executorId = bizId;
};
</script>

<style lang="less" scoped>
.content {
  width: 100%;
  height: 100%;
}
.content-title {
  margin-bottom: 10px;
}
.node-list {
  display: flex;
  flex-wrap: wrap;
}
.active {
  box-shadow: 0 0 8px 1px var(--primary-color);
}
</style>
