<template>
  <div class="designer-container">
    <!-- 流程信息栏（新增/编辑模式显示） -->
    <div v-if="flowInfoVisible" class="flow-info-bar">
      <el-tag v-if="mode === 'create'" type="primary">新增流程</el-tag>
      <el-tag v-else-if="mode === 'edit'" type="warning">编辑流程</el-tag>
      <span class="flow-info-item"><strong>编码：</strong>{{ flowCode }}</span>
      <span class="flow-info-item"><strong>名称：</strong>{{ flowName }}</span>
      <span v-if="flowCategory" class="flow-info-item"><strong>分类：</strong>{{ flowCategory }}</span>
    </div>

    <DesignerCanvas
      :set-container="setContainer"
      :lf="lfRef"
      :selected-node="selectedNode"
      :node-props="nodeProps"
      :role-list="roleList"
      :selected-sub-node-index="selectedSubNodeIndex"
      :drawer-visible="drawerVisible"
      @drop="handleDrop"
      @save="handleSave"
      @clear="handleClear"
      @back="goBack"
      @update:drawer-visible="drawerVisible = $event"
      @select-sub-node="selectedSubNodeIndex = $event; drawerVisible = true"
      @add-sub-node="addSubNodeFromCanvas"
      @remove-sub-node="removeSubNodeFromCanvas"
    />

    <DesignerPropertyPanel
      :selected-node="selectedNode"
      :node-props="nodeProps"
      :outgoing-edges="outgoingEdges"
      :role-list="roleList"
      :get-edge-target-name="getEdgeTargetName"
      :update-node-name="updateNodeName"
      :on-default-change="onDefaultChange"
      :on-branch-blur="onBranchBlur"
      :generate-sub-node-id="generateSubNodeId"
      :save-current-node-props="saveCurrentNodeProps"
      :selected-sub-node-index="selectedSubNodeIndex"
      :drawer-visible="drawerVisible"
      @update:selected-sub-node-index="selectedSubNodeIndex = $event"
      @update:drawer-visible="drawerVisible = $event"
      @delete-node="deleteSelectedNode"
    />

    <DesignerSaveDialog
      :visible="saveDialogVisible"
      @update:visible="saveDialogVisible = $event"
      :option-dialog-visible="optionDialogVisible"
      @update:optionDialogVisible="optionDialogVisible = $event"
      :save-form="saveForm"
      :save-form-rules="saveFormRules"
      :form-fields="formFields"
      :field-type-options="fieldTypeOptions"
      :option-editing-field="optionEditingField"
      :option-list="optionList"
      @submit="submitSave"
      @add-field="addFormField"
      @remove-field="removeFormField"
      @open-option-dialog="openOptionDialog"
      @add-option="addOption"
      @remove-option="removeOption"
      @save-options="saveOptions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { ComponentPublicInstance } from 'vue'
import { useFlowDesigner } from './useFlowDesigner'
import DesignerCanvas from './DesignerCanvas.vue'
import DesignerPropertyPanel from './DesignerPropertyPanel.vue'
import DesignerSaveDialog from './DesignerSaveDialog.vue'

const lfContainer = ref<HTMLDivElement>()

function setContainer(el: Element | ComponentPublicInstance | null) {
  lfContainer.value = el as HTMLDivElement | undefined
}

const {
  mode,
  flowInfoVisible,
  flowCode,
  flowName,
  flowCategory,
  selectedNode,
  nodeProps,
  outgoingEdges,
  roleList,
  lfRef,
  getEdgeTargetName,
  updateNodeName,
  onDefaultChange,
  onBranchBlur,
  generateSubNodeId,
  saveCurrentNodeProps,
  deleteSelectedNode,
  selectNodeById,
  saveDialogVisible,
  optionDialogVisible,
  saveForm,
  saveFormRules,
  formFields,
  fieldTypeOptions,
  optionEditingField,
  optionList,
  handleDrop,
  handleSave,
  handleClear,
  goBack,
  submitSave,
  addFormField,
  removeFormField,
  openOptionDialog,
  addOption,
  removeOption,
  saveOptions
} = useFlowDesigner(lfContainer)

const selectedSubNodeIndex = ref<number | null>(null)
const drawerVisible = ref(false)

function addSubNodeFromCanvas() {
  if (!Array.isArray(nodeProps.subNodes)) {
    nodeProps.subNodes = []
  }
  nodeProps.subNodes.push({
    id: generateSubNodeId(),
    name: '',
    assigneeType: 'ROLE',
    assigneeValue: '',
    approveMode: 'or',
    timeoutHours: undefined,
    timeoutAction: 'remind',
  })
  selectedSubNodeIndex.value = nodeProps.subNodes.length - 1
  drawerVisible.value = true
  saveCurrentNodeProps()
}

function removeSubNodeFromCanvas(index: number) {
  if (!Array.isArray(nodeProps.subNodes)) return
  nodeProps.subNodes.splice(index, 1)
  if (selectedSubNodeIndex.value === index) {
    selectedSubNodeIndex.value = null
  } else if (selectedSubNodeIndex.value !== null && selectedSubNodeIndex.value > index) {
    selectedSubNodeIndex.value = selectedSubNodeIndex.value - 1
  }
  saveCurrentNodeProps()
}

// 选中节点或子节点开关变化时，自动展开/收起画布抽屉
watch(
  () => [selectedNode.value, nodeProps.subNodesEnabled],
  ([node]) => {
    selectedSubNodeIndex.value = null
    if (node && node.type === 'approval-node' && nodeProps.subNodesEnabled) {
      drawerVisible.value = true
    } else {
      drawerVisible.value = false
    }
  }
)
</script>

<style scoped>
.designer-container {
  display: flex;
  height: calc(100vh - 100px);
  background: #fff;
}
.flow-info-bar {
  position: absolute;
  top: 60px;
  left: 220px;
  right: 0;
  height: 40px;
  background: #f0f9ff;
  border-bottom: 1px solid #d9ecff;
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 0 16px;
  z-index: 100;
}
.flow-info-item {
  font-size: 13px;
  color: #303133;
}
</style>
