import "../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                          */
/* empty css                                                                  */
/* empty css                                                               */
import "../../../../node_modules/element-plus/theme-chalk/el-tooltip.css.mjs";
/* empty css                                                               */
import { useCssVars, unref, computed, ref, provide, createBlock, openBlock, withCtx, createElementVNode, createVNode, renderSlot, toDisplayString, isRef } from "vue";
import _sfc_main$1 from "./nodes/TreeNode.vue.mjs";
import _sfc_main$2 from "./dialog/index.vue.mjs";
import { useDraggableScroll } from "./hooks/useDraggableScroll.mjs";
/* empty css               */
import _export_sfc from "../../../../_virtual/_plugin-vue_export-helper.mjs";
import { ElScrollbar } from "../../../../node_modules/element-plus/es/components/scrollbar/index.mjs";
import { ElTooltip } from "../../../../node_modules/element-plus/es/components/tooltip/index.mjs";
import { ElButton } from "../../../../node_modules/element-plus/es/components/button/index.mjs";
const _hoisted_1 = { class: "tool" };
const _hoisted_2 = { class: "zoom" };
const _hoisted_3 = { class: "node-container" };
const _sfc_main = {
  __name: "eventFlow",
  props: {
    process: Object,
    fields: Array,
    readOnly: {
      type: Boolean,
      default: false
    },
    defaultZoom: {
      type: Number,
      default: 100
    },
    bgColor: {
      type: String,
      default: "var(--el-bg-color-page)"
    }
  },
  setup(__props, { expose: __expose }) {
    useCssVars((_ctx) => ({
      "0134b47a": __props.bgColor,
      "4611d6e2": unref(getScale)
    }));
    const props = __props;
    const flatFields = computed(() => {
      const all = [];
      const loop = (children) => {
        children.forEach((field) => {
          if (field.type === "formItem") {
            all.push(field);
          }
          if (Array.isArray(field.children)) {
            loop(field.children);
          }
        });
      };
      loop(props.fields);
      return all;
    });
    const getScale = computed(() => zoom.value / 100);
    const zoom = ref(props.defaultZoom);
    const readOnly = computed(() => props.readOnly);
    const activeData = ref({ id: "", name: "", type: "start" });
    ref(false);
    const dialogVisible = ref(false);
    const nodesError = ref({});
    const designerContainerRef = ref(null);
    useDraggableScroll(designerContainerRef);
    provide("flowDesign", {
      readOnly,
      fields: flatFields,
      nodesError
    });
    const openDialog = (node) => {
      if (node.type === "start" || node.type === "end") {
        return;
      }
      activeData.value = node;
      dialogVisible.value = true;
    };
    const nextId = () => {
      let id = `node_${Math.random().toString(36).substring(2, 7)}`;
      const findId = (node, id2) => {
        if (node.id === id2) return true;
        if (node.next) return findId(node.next, id2);
        if ("branches" in node) {
          const branchNode = node;
          if (branchNode.branches && branchNode.branches.length > 0) {
            return branchNode.branches.some((item) => findId(item, id2));
          }
        }
        return false;
      };
      if (findId(props.process, id)) return nextId();
      return id;
    };
    const addExclusive = (node) => {
      const next = node.next;
      const id = nextId();
      const exclusiveNode = {
        id,
        pid: node.id,
        type: "exclusive",
        name: "独占网关",
        next,
        branches: []
      };
      if (next) next.pid = id;
      addCondition(exclusiveNode);
      addCondition(exclusiveNode);
      node.next = exclusiveNode;
      if (exclusiveNode.branches.length > 0) {
        const condition = exclusiveNode.branches[exclusiveNode.branches.length - 1];
        condition.def = true;
        condition.name = "默认条件";
      }
    };
    const addCondition = (node) => {
      const exclusive = node;
      exclusive.branches.splice(exclusive.branches.length - 1, 0, {
        id: nextId(),
        pid: exclusive.id,
        type: "condition",
        def: false,
        name: `条件${exclusive.branches.length}`,
        conditions: {
          operator: "and",
          conditions: [],
          groups: []
        },
        ruleMatchStrategy: "continue",
        next: void 0
      });
    };
    const addCc = (node) => {
      const next = node.next;
      const id = nextId();
      node.next = {
        id,
        pid: node.id,
        type: "cc",
        name: "抄送人",
        next,
        assigneeType: "user",
        formUser: "",
        formRole: "",
        users: [],
        roles: [],
        leader: 1,
        orgLeader: 1,
        choice: false,
        self: false,
        formProperties: []
      };
      if (next) next.pid = id;
    };
    const addTimer = (node) => {
      const next = node.next;
      const id = nextId();
      node.next = {
        id,
        pid: node.id,
        name: "计时等待",
        type: "timer",
        next,
        waitType: "duration",
        unit: "PT%sS",
        duration: 0,
        timeDate: void 0
      };
      if (next) next.pid = id;
    };
    const addNotify = (node) => {
      const next = node.next;
      const id = nextId();
      node.next = {
        id,
        pid: node.id,
        name: "消息通知",
        type: "notify",
        next,
        assigneeType: "user",
        formUser: "",
        formRole: "",
        users: [],
        roles: [],
        leader: 1,
        orgLeader: 1,
        choice: false,
        self: false,
        types: ["site"],
        subject: "",
        content: ""
      };
      if (next) next.pid = id;
    };
    const addService = (node) => {
      const next = node.next;
      const id = nextId();
      node.next = {
        id,
        pid: node.id,
        type: "service",
        name: "服务节点",
        next,
        implementationType: "",
        implementation: ""
      };
      if (next) next.pid = id;
    };
    const addApproval = (node) => {
      const next = node.next;
      const id = nextId();
      node.next = {
        id,
        pid: node.id,
        type: "approval",
        name: "动作",
        // executionListeners: [],
        next,
        actionType: "",
        basic: {},
        advanced: {}
        // assigneeType: "user",
        // formUser: "",
        // formRole: "",
        // users: [],
        // roles: [],
        // leader: 1,
        // orgLeader: 1,
        // choice: false,
        // self: false,
        // multi: "sequential",
        // multiPercent: 100,
        // nobody: "pass",
        // nobodyUsers: [],
        // formProperties: [],
        // operations: {
        //   complete: true,
        //   refuse: true,
        //   back: true,
        //   transfer: true,
        //   delegate: true,
        //   addMulti: false,
        //   minusMulti: false,
        // },
      };
      if (next) next.pid = id;
    };
    const addNode = (type, node) => {
      const addMap = {
        exclusive: addExclusive,
        condition: addCondition,
        cc: addCc,
        timer: addTimer,
        notify: addNotify,
        service: addService,
        approval: addApproval
      };
      const fun = addMap[type];
      fun && fun(node);
    };
    const delNode = (del) => {
      delete nodesError.value[del.id];
      delNodeNext(props.process, del);
    };
    const delNodeNext = (next, del) => {
      var _a;
      delete nodesError.value[del.id];
      if (next.id === del.pid) {
        if ("branches" in next && ((_a = next.next) == null ? void 0 : _a.id) !== del.id) {
          const branchNode = next;
          const index = branchNode.branches.findIndex((item) => item.id === del.id);
          if (index !== -1) {
            if (branchNode.branches.length <= 2) {
              delError(branchNode);
              delNode(branchNode);
            } else {
              delError(del);
              branchNode.branches.splice(index, 1);
            }
          }
        } else {
          if (del.next && del.next.pid) {
            del.next.pid = next.id;
          }
          next.next = del.next;
        }
      } else {
        if (next.next) delNodeNext(next.next, del);
        if ("branches" in next) {
          const nextBranch = next;
          if (nextBranch.branches && nextBranch.branches.length > 0) {
            nextBranch.branches.forEach((item) => delNodeNext(item, del));
          }
        }
      }
    };
    const delError = (node) => {
      delete nodesError.value[node.id];
      if (node.next) delError(node.next);
      if ("branches" in node) {
        const branchNode = node;
        if (branchNode.branches && branchNode.branches.length > 0) {
          branchNode.branches.forEach((item) => delError(item));
        }
      }
    };
    const validate = () => {
      return new Promise((resolve, reject) => {
        const errors = Object.values(nodesError.value).flat();
        if (errors.length > 0) {
          reject(errors);
        } else {
          resolve(true);
        }
      });
    };
    __expose({ validate });
    return (_ctx, _cache) => {
      const _component_el_button = ElButton;
      const _component_el_tooltip = ElTooltip;
      const _component_el_scrollbar = ElScrollbar;
      return openBlock(), createBlock(_component_el_scrollbar, { class: "event-scrollbar" }, {
        default: withCtx(() => [
          createElementVNode("div", {
            class: "designer-container cursor-default active:cursor-grabbing",
            ref_key: "designerContainerRef",
            ref: designerContainerRef
          }, [
            createElementVNode("div", _hoisted_1, [
              renderSlot(_ctx.$slots, "default", {}, void 0, true)
            ]),
            createElementVNode("div", _hoisted_2, [
              createVNode(_component_el_tooltip, {
                content: "放大",
                placement: "bottom-start"
              }, {
                default: withCtx(() => [
                  createVNode(_component_el_button, {
                    icon: "plus",
                    onClick: _cache[0] || (_cache[0] = ($event) => zoom.value += 10),
                    disabled: unref(zoom) >= 170,
                    circle: ""
                  }, null, 8, ["disabled"])
                ]),
                _: 1
              }),
              createElementVNode("span", null, toDisplayString(unref(zoom)) + "%", 1),
              createVNode(_component_el_tooltip, {
                content: "缩小",
                placement: "bottom-start"
              }, {
                default: withCtx(() => [
                  createVNode(_component_el_button, {
                    icon: "minus",
                    onClick: _cache[1] || (_cache[1] = ($event) => zoom.value -= 10),
                    circle: "",
                    disabled: unref(zoom) <= 50
                  }, null, 8, ["disabled"])
                ]),
                _: 1
              })
            ]),
            createElementVNode("div", _hoisted_3, [
              createVNode(_sfc_main$1, {
                node: __props.process,
                onAddNode: addNode,
                onDelNode: delNode,
                onActiveNode: openDialog
              }, null, 8, ["node"])
            ]),
            createVNode(_sfc_main$2, {
              modelValue: unref(dialogVisible),
              "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => isRef(dialogVisible) ? dialogVisible.value = $event : null),
              activeData: unref(activeData)
            }, null, 8, ["modelValue", "activeData"])
          ], 512)
        ]),
        _: 3
      });
    };
  }
};
const EventFlow = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-67c6ede7"]]);
export {
  EventFlow as default
};
