<template>
  <div class="process-panel__container" :style="{ width: `${width}px` }">
    <el-collapse v-model="activeTab">
      <el-collapse-item name="base">
        <template #title>
          <div class="panel-tab__title">
            <el-icon><InfoFilled /></el-icon>常规
          </div>
        </template>
        <element-base-info
          :id-edit-disabled="idEditDisabled"
          :business-object="elementBusinessObject"
          :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item
        name="condition"
        v-if="elementType === 'Process'"
        key="message"
      >
        <template #title>
          <div class="panel-tab__title">
            <el-icon><Comment /></el-icon>消息与信号
          </div>
        </template>
        <signal-and-massage />
      </el-collapse-item>
      <el-collapse-item
        name="condition"
        v-if="conditionFormVisible"
        key="condition"
      >
        <template #title>
          <div class="panel-tab__title">
            <el-icon><Promotion /></el-icon>流转条件
          </div>
        </template>
        <flow-condition
          :business-object="elementBusinessObject"
          :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item name="condition" v-if="formVisible" key="form">
        <template #title>
          <div class="panel-tab__title">
            <el-icon><Document /></el-icon>表单
          </div>
        </template>
        <element-form :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="task"
        v-if="elementType.indexOf('Task') !== -1"
        key="task"
      >
        <template #title
          ><div class="panel-tab__title">
            <el-icon><Checked /></el-icon>任务
          </div>
        </template>
        <element-task :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="multiInstance"
        v-if="elementType.indexOf('Task') !== -1 && elementType !== 'UserTask'"
        key="multiInstance"
      >
        <template #title
          ><div class="panel-tab__title">
            <el-icon><Help /></el-icon>多实例
          </div>
        </template>
        <element-multi-instance
          :business-object="elementBusinessObject"
          :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item name="listeners" key="listeners">
        <template #title
          ><div class="panel-tab__title">
            <el-icon><Message /></el-icon>执行监听器
          </div>
        </template>
        <element-listeners :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="taskListeners"
        v-if="elementType === 'UserTask'"
        key="taskListeners"
      >
        <template #title
          ><div class="panel-tab__title">
            <el-icon><Message /></el-icon>任务监听器
          </div></template
        >
        <user-task-listeners :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item name="extensions" key="extensions">
        <template #title
          ><div class="panel-tab__title">
            <el-icon><CirclePlus /></el-icon>扩展属性
          </div></template
        >
        <element-properties :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item name="other" key="other">
        <template #title
          ><div class="panel-tab__title">
            <el-icon><Promotion /></el-icon>其他
          </div></template
        >
        <element-other-config :id="elementId" />
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup name="BpmnPropertiesPanel">
import ElementBaseInfo from "./base/ElementBaseInfo";
import ElementOtherConfig from "./other/ElementOtherConfig";
import ElementTask from "./task/ElementTask";
import ElementMultiInstance from "./multi-instance/ElementMultiInstance";
import FlowCondition from "./flow-condition/FlowCondition";
import SignalAndMassage from "./signal-message/SignalAndMessage";
import ElementListeners from "./listeners/ElementListeners";
import ElementProperties from "./properties/ElementProperties";
import ElementForm from "./form/ElementForm";
import UserTaskListeners from "./listeners/UserTaskListeners";
import { provide, toRefs, watch, nextTick } from "vue";

const props = defineProps({
  bpmnModeler: Object,
  prefix: {
    type: String,
    default: "camunda",
  },
  width: {
    type: Number,
    default: 480,
  },
  idEditDisabled: {
    type: Boolean,
    default: false,
  },
});

const { bpmnModeler, prefix, width, idEditDisabled } = toRefs(props);
provide("prefix", prefix.value);
provide("width", width.value);

const activeTab = ref("base");
const elementId = ref("");
const elementType = ref("");
const elementBusinessObject = ref({}); // 元素 businessObject 镜像，提供给需要做判断的组件使用
const conditionFormVisible = ref(false); // 流转条件设置
const formVisible = ref(false); // 表单配置
let timer;
let bpmnElement;
function openFormColla() {
  nextTick(() => {
    activeTab.value = ["base", "condition"];
  });
}
function initModels() {
  // 初始化 modeler 以及其他 moddle
  if (!bpmnModeler.value) {
    // 避免加载时 流程图 并未加载完成
    timer = setTimeout(() => initModels(), 10);
    return;
  }

  if (timer) clearTimeout(timer);

  window.bpmnInstances = {
    modeler: bpmnModeler.value,
    modeling: bpmnModeler.value.get("modeling"),
    moddle: bpmnModeler.value.get("moddle"),
    eventBus: bpmnModeler.value.get("eventBus"),
    bpmnFactory: bpmnModeler.value.get("bpmnFactory"),
    elementFactory: bpmnModeler.value.get("elementFactory"),
    elementRegistry: bpmnModeler.value.get("elementRegistry"),
    replace: bpmnModeler.value.get("replace"),
    selection: bpmnModeler.value.get("selection"),
  };
  getActiveElement();
}
function getActiveElement() {
  // 初始第一个选中元素 bpmn:Process
  initFormOnChanged(null);
  bpmnModeler.value.on("import.done", (e) => {
    initFormOnChanged(null);
  });
  // 监听选择事件，修改当前激活的元素以及表单
  bpmnModeler.value.on("selection.changed", ({ newSelection }) => {
    initFormOnChanged(newSelection[0] || null);
  });
  bpmnModeler.value.on("element.changed", ({ element }) => {
    // 保证 修改 "默认流转路径" 类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
    if (element && element.id === elementId.value) {
      initFormOnChanged(element);
    }
  });
}
// 初始化数据
function initFormOnChanged(element) {
  let activatedElement = element;
  if (!activatedElement) {
    activatedElement =
      window.bpmnInstances.elementRegistry.find(
        (el) => el.type === "bpmn:Process"
      ) ??
      window.bpmnInstances.elementRegistry.find(
        (el) => el.type === "bpmn:Collaboration"
      );
  }
  if (!activatedElement) return;
  // console.log(`
  //             ----------
  //     select element changed:
  //               id:  ${activatedElement.id}
  //             type:  ${activatedElement.businessObject.$type}
  //             ----------
  //             `);
  // console.log("businessObject: ", activatedElement.businessObject);
  window.bpmnInstances.bpmnElement = activatedElement;
  bpmnElement = activatedElement;
  elementId.value = activatedElement.id;
  elementType.value = activatedElement.type.split(":")[1] || "";
  elementBusinessObject.value = JSON.parse(
    JSON.stringify(activatedElement.businessObject)
  );
  conditionFormVisible.value = !!(
    elementType.value === "SequenceFlow" &&
    activatedElement.source &&
    activatedElement.source.type.indexOf("StartEvent") === -1
  );
  formVisible.value =
    elementType.value === "UserTask" || elementType.value === "StartEvent";
}
onBeforeUnmount(() => {
  window.bpmnInstances = null;
});

watch(elementId, (val) => {
  activeTab.value = "base";
});
initModels();

defineExpose({
  initFormOnChanged,
  openFormColla,
});
</script>
