<template>
  <div class="process-panel__container" :style="{ width: `${this.width}px` }">
    <el-collapse v-model="activeTab">
      <el-collapse-item name="base">
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-info"></i>常规
        </div>
        <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"
      >
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-comment"></i>消息与信号
        </div>
        <signal-and-massage />
      </el-collapse-item>
      <el-collapse-item
        name="condition"
        v-if="conditionFormVisible"
        key="condition"
      >
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-promotion"></i>流转条件
        </div>
        <flow-condition
          :business-object="elementBusinessObject"
          :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item name="condition" v-if="formVisible" key="form">
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-order"></i>表单
        </div>
        <element-form :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="task"
        v-if="elementType.indexOf('Task') !== -1"
        key="task"
      >
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-claim"></i>任务
        </div>
        <element-task :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="multiInstance"
        v-if="elementType.indexOf('Task') !== -1 && elementType !== 'UserTask'"
        key="multiInstance"
      >
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-help"></i>多实例
        </div>
        <element-multi-instance
          :business-object="elementBusinessObject"
          :type="elementType"
        />
      </el-collapse-item>
      <el-collapse-item name="listeners" key="listeners">
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-message-solid"></i>执行监听器
        </div>
        <element-listeners :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item
        name="taskListeners"
        v-if="elementType === 'UserTask'"
        key="taskListeners"
      >
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-message-solid"></i>任务监听器
        </div>
        <user-task-listeners :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item name="extensions" key="extensions">
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-circle-plus"></i>扩展属性
        </div>
        <element-properties :id="elementId" :type="elementType" />
      </el-collapse-item>
      <el-collapse-item name="other" key="other">
        <div slot="title" class="panel-tab__title">
          <i class="el-icon-s-promotion"></i>其他
        </div>
        <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 } from "vue";
import useBpmnStore from "@/store/modules/bpmn";

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 bpmnStore = useBpmnStore();
// const data = reactive({
//   timer: undefined,
// });
// const { timer } = toRefs(data);

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 initModels() {
  // bpmnStore.count = 123;
  console.log(bpmnModeler.value);
  // 初始化 modeler 以及其他 moddle
  if (!bpmnModeler.value) {
    // 避免加载时 流程图 并未加载完成
    timer = setTimeout(() => initModels(), 10);
    return;
  }
  // console.log(timer);
  if (timer) clearTimeout(timer);
  // timer = null;
  console.log(bpmnModeler.value);
  // bpmnStore.bpmnInstances = {
  //   test: bpmnModeler.value,
  // };
  // bpmnModeler.value.get = undefined;
  // console.log(JSON.stringify(bpmnModeler.value));
  // bpmnStore.setBpmnInstances({
  //   modeler: { _container: bpmnModeler.value._container },
  //   // 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: {
  //     _elements: bpmnModeler.value.get("elementRegistry")._elements,
  //   },
  //   // replace: bpmnModeler.value.get("replace"),
  //   // selection: bpmnModeler.value.get("selection"),
  // });
  // bpmnStore.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"),
  // };
  console.log(bpmnStore.bpmnInstances, "167");
  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() {
  console.log("select first");
  // 初始第一个选中元素 bpmn:Process
  initFormOnChanged(null);
  bpmnModeler.value.on("import.done", (e) => {
    initFormOnChanged(null);
  });
  // 监听选择事件，修改当前激活的元素以及表单
  bpmnModeler.value.on("selection.changed", ({ newSelection }) => {
    console.log("selection.changed");
    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";
}
function beforeDestroy() {
  window.bpmnInstances = null;
}

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