<template>
  <div class="app-container">

    <!-- 流程设计器，负责绘制流程等 -->
    <my-process-designer
      v-if="xmlString !== undefined"
      :key="`designer-${reloadIndex}`"
      ref="processDesigner"
      v-model="xmlString"
      v-bind="controlForm"
      keyboard
      @init-finished="initModeler"
      @save="save"
      @publish="publish"
      @processUpdate="handleUpdateProcess"
      @element-click="elementClick"
    />

    <!-- 流程属性器，负责编辑每个流程节点的属性 -->
    <!-- <my-properties-panel
      :key="`penal-${reloadIndex}`"
      :bpmn-modeler="modeler"
      :prefix="controlForm.prefix"
      class="process-panel"
      :model="model"
    /> -->
    <EditPanel
      :key="`penal-${reloadIndex}`"
      :model="model"
      :bpmn-modeler="modeler"
      :element-base-info="elementBaseInfo"
      :prefix="controlForm.prefix"
      class="editPanel"
      @saveData="elementActionSaveData"
    />
    <!-- ========== 流程任务分配规则 ========== -->
    <taskAssignRuleDialog ref="taskAssignRuleDialog" />
    <!-- 修改流程 -->
    <ModifyProcess ref="modifyProcess" @updateModel="handleEnsureModify" />

  </div>
</template>

<script>
import translations from '@/components/BpmnProcessDesigner/src/translations'
// 自定义元素选中时的弹出菜单（修改 默认任务 为 用户任务）
import CustomContentPadProvider from '@/components/BpmnProcessDesigner/package/designer/plugins/content-pad'
// 自定义左侧菜单（修改 默认任务 为 用户任务）
import CustomPaletteProvider from '@/components/BpmnProcessDesigner/package/designer/plugins/palette'
// import xmlObj2json from "./utils/xml2json";
// import MyProcessPalette from '@/components/BpmnProcessDesigner/package/palette/ProcessPalette'
import { createModel, getModel, updateModel, deployModel, createTask } from '@/api/bpm/model'
// 自定义侧边栏
// import MyProcessPanel from "../package/process-panel/ProcessPanel";
import { getBeginEnd } from '@/api/bpm/processModel'
import EditPanel from './components/EditPanel.vue'
import taskAssignRuleDialog from '../taskAssignRule/taskAssignRuleDialog.vue'
import ModifyProcess from './components/ModifyProcess.vue'

export default {
  name: 'BpmModelEditor',
  components: { EditPanel, taskAssignRuleDialog, ModifyProcess },
  data() {
    return {
      xmlString: undefined, // BPMN XML
      modeler: null,
      reloadIndex: 0,
      controlDrawerVisible: false,
      translationsSelf: translations,
      elementBaseInfo: {},
      controlForm: {
        simulation: true,
        labelEditing: false,
        labelVisible: false,
        prefix: 'flowable',
        headerButtonSize: 'mini',
        additionalModel: [CustomContentPadProvider, CustomPaletteProvider]
      },
      addis: {
        CustomContentPadProvider,
        CustomPaletteProvider
      },
      // 执行动作的参数
      elementActionList: [],
      // 流程模型的信息
      model: {}
    }
  },
  created() {
    // 如果 modelId 非空，说明是修改流程模型
    const modelId = this.$route.query && this.$route.query.modelId
    if (modelId) {
      this.getModelList()
    } else {
      getBeginEnd().then(res => {
        this.xmlString = res.data
      })
    }
  },
  methods: {
    getModelList() {
      // 如果 modelId 非空，说明是修改流程模型
      const modelId = this.$route.query && this.$route.query.modelId
      getModel(modelId).then(response => {
        this.xmlString = response.data.bpmnXml
        this.model = {
          ...response.data,
          bpmnXml: undefined // 清空 bpmnXml 属性
        }
        // this.controlForm.processId = response.data.key
      })
    },
    initModeler(modeler) {
      setTimeout(() => {
        this.modeler = modeler
        // console.log(modeler)
      }, 10)
    },
    save(bpmnXml) {
      const data = {
        ...this.model,
        bpmnXml: bpmnXml // this.bpmnXml 只是初始化流程图，后续修改无法通过它获得
      }
      //this.handleSaveElementAction()
      // 修改的提交
      if (data.id) {
        updateModel(data).then(response => {
          this.$modal.msgSuccess('修改成功')
          // 跳转回去
          this.close()
        })
        return
      }
      // 添加的提交
      createModel(data).then(response => {
        this.$modal.msgSuccess('保存成功')
        // 跳转回去
        this.close()
      })
    },
    elementActionSaveData(data) {
      this.elementActionList = data
    },
    handleSaveElementAction() {
      // createTask
      const taskList = this.elementActionList.map(item => {
        // item.bpmModelDefId = this.$route.query.modelId
        item.eAction = 'UPDATE'
        const { activityId, eAction, eTableId, eChangeField, eValue } = item
        return {
          activityId,
          eAction,
          eTableId,
          eChangeField,
          eValue
        }
      })
      const saveUpdateParams = {
        bpmModelDefId: this.$route.query.modelId,
        updateReqVOList: taskList
      }
      createTask(saveUpdateParams).then(res => {
        console.log(res.data)
      })
    },
    publish() {
      const that = this
      this.$modal.confirm('是否部署该流程！！').then(function() {
        deployModel(that.$route.query.modelId).then(response => {
          console.log(response)
          that.$modal.msgSuccess('部署成功')
          this.close()
        })
      }).catch((err) => { console.log(err) })
    },
    // 修改流程
    handleUpdateProcess() {
      this.$refs.modifyProcess.form = this.model
      this.$refs.modifyProcess.title = '修改流程'
      this.$refs.modifyProcess.open = true
    },
    // 修改流程完成
    handleEnsureModify() {
      this.getModelList()
    },
    /** 关闭按钮 */
    close() {
      this.$tab.closeOpenPage({ path: '/bpm/manager/model', query: { id: this.$route.query.id }})
    },
    // 点击
    elementClick(element, internalEvent) {
      this.elementBaseInfo = element
      console.log('点击的元素信息',element);
      // 模拟双击事件
      const currentTime = new Date().getTime()
      // 计算事件间隔
      const timeDiff = currentTime - this.lastClickTime
      // 检查是否连续点击同一元素且时间间隔较短
      if (this.lastClickedElement === element && timeDiff < 300) {
        // 执行双击事件的逻辑
        // this.handleBpmnDblClick(element, internalEvent)
        this.$refs['taskAssignRuleDialog'].initModel(this.$route.query.modelId,element)
      } else {
        this.lastClickTime = currentTime
        this.lastClickedElement = element
      }
    }
  }
}
</script>

<style lang="scss">
//body {
//  overflow: hidden;
//  margin: 0;
//  box-sizing: border-box;
//}
//.app {
//  width: 100%;
//  height: 100%;
//  box-sizing: border-box;
//  display: inline-grid;
//  grid-template-columns: 100px auto max-content;
//}
.demo-control-bar {
  position: fixed;
  right: 8px;
  bottom: 8px;
  z-index: 1;
  .open-control-dialog {
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    font-size: 32px;
    background: rgba(64, 158, 255, 1);
    color: #ffffff;
    cursor: pointer;
  }
}

// TODO 芋艿：去掉多余的 faq
//.info-tip {
//  position: fixed;
//  top: 40px;
//  right: 500px;
//  z-index: 10;
//  color: #999999;
//}

.control-form {
  .el-radio {
    width: 100%;
    line-height: 32px;
  }
}
.element-overlays {
  box-sizing: border-box;
  padding: 8px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 4px;
  color: #fafafa;
}

.my-process-designer {
  height: calc(100vh - 84px);
}
.process-panel__container {
  position: absolute;
  right: 0;
  top: 100px;
  height: calc(100vh - 84px);
}
.editPanel {
  position: absolute;
  right: 0;
  top: 100px;
  height: calc(100vh - 84px);
  box-shadow: 0 0 8px #ccc;
  overflow-y: scroll;
}

</style>
