/**
 * 钉钉风格流程设计器
 * 完全模仿钉钉审批流程设计器样式
 */

'use client';

import React, { useState, useCallback, useEffect, useRef } from 'react';
import {
  Plus,
  User,
  Users,
  UserCheck,
  UserCog,
  GitBranch,
  GitMerge,
  ChevronRight,
  X,
  Undo2,
  Redo2,
  Copy,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { DingStylePropertyPanel } from './DingStylePropertyPanel';
import {
  ProcessModel,
  ProcessNode,
  ProcessNodeType,
  ProcessNodeConfig,
  generateNodeId,
  generateEdgeId,
} from './types';
import { useTranslation } from '@/hooks/useTranslation';

// ============================================
// 颜色配置
// ============================================

const NODE_COLORS = {
  // 审批人 - 蓝色
  USER_TASK: {
    primary: '#1677ff',
    bg: '#e6f4ff',
    border: '#1677ff',
    text: '#1677ff',
  },
  // 执行人 - 绿色
  EXECUTOR: {
    primary: '#52c41a',
    bg: '#f6ffed',
    border: '#52c41a',
    text: '#52c41a',
  },
  // 抄送人 - 紫色
  CC: {
    primary: '#722ed1',
    bg: '#f9f0ff',
    border: '#722ed1',
    text: '#722ed1',
  },
  // 条件分支 - 橙色
  CONDITION: {
    primary: '#fa8c16',
    bg: '#fff7e6',
    border: '#fa8c16',
    text: '#fa8c16',
  },
  // 并行分支 - 青色
  PARALLEL: {
    primary: '#13c2c2',
    bg: '#e6fffb',
    border: '#13c2c2',
    text: '#13c2c2',
  },
};

// ============================================
// 类型定义
// ============================================

interface FlowNode {
  id: string;
  type: ProcessNodeType;
  name: string;
  config: ProcessNodeConfig;
  // 条件分支专用
  conditions?: ConditionBranch[];
  // 并行分支专用
  parallelBranches?: ParallelBranch[];
}

interface ParallelBranch {
  id: string;
  name: string;
  children: FlowNode[];
}

interface ConditionBranch {
  id: string;
  name: string;
  priority: number;
  condition?: string;
  isDefault?: boolean;
  children: FlowNode[];
}

interface NodeTypeOption {
  type: ProcessNodeType;
  label: string;
  icon: React.ElementType;
  color: typeof NODE_COLORS.USER_TASK;
  category: 'approver' | 'branch';
}

const getNodeTypeOptions = (t: any): NodeTypeOption[] => [
  { type: 'USER_TASK', label: t.approvals.dingProcessDesigner.approver, icon: UserCheck, color: NODE_COLORS.USER_TASK, category: 'approver' },
  { type: 'EXECUTOR', label: t.approvals.dingProcessDesigner.executor, icon: UserCog, color: NODE_COLORS.EXECUTOR, category: 'approver' },
  { type: 'CC', label: t.approvals.dingProcessDesigner.ccPerson, icon: Users, color: NODE_COLORS.CC, category: 'approver' },
  { type: 'EXCLUSIVE_GATEWAY', label: t.approvals.dingProcessDesigner.conditionalBranch, icon: GitBranch, color: NODE_COLORS.CONDITION, category: 'branch' },
  { type: 'PARALLEL_GATEWAY', label: t.approvals.dingProcessDesigner.parallelBranch, icon: GitMerge, color: NODE_COLORS.PARALLEL, category: 'branch' },
];

// ============================================
// 添加节点按钮
// ============================================

interface AddNodeButtonProps {
  onAdd: (type: ProcessNodeType) => void;
  size?: 'normal' | 'small';
}

function AddNodeButton({ onAdd, size = 'normal' }: AddNodeButtonProps) {
  const [isOpen, setIsOpen] = useState(false);

  const handleAdd = (type: ProcessNodeType) => {
    onAdd(type);
    setIsOpen(false);
  };

  const { t } = useTranslation();
  const nodeTypeOptions = getNodeTypeOptions(t);
  const approverOptions = nodeTypeOptions.filter((opt) => opt.category === 'approver');
  const branchOptions = nodeTypeOptions.filter((opt) => opt.category === 'branch');

  const buttonSize = size === 'small' ? 'w-5 h-5' : 'w-7 h-7';
  const iconSize = size === 'small' ? 'w-3 h-3' : 'w-4 h-4';

  return (
    <div className="relative flex flex-col items-center">
      {/* 上连接线 */}
      <div className="w-px h-5 bg-gray-300" />
      
      {/* 添加按钮 */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`
          ${buttonSize} rounded-full flex items-center justify-center
          transition-all duration-200 z-10 border-2 border-white
          ${isOpen 
            ? 'bg-blue-600 text-white shadow-lg' 
            : 'bg-blue-500 text-white hover:bg-blue-600 hover:shadow-md'
          }
        `}
      >
        <Plus className={`${iconSize} transition-transform duration-200 ${isOpen ? 'rotate-45' : ''}`} />
      </button>

      {/* 下连接线和箭头 */}
      <div className="flex flex-col items-center">
        <div className="w-px h-5 bg-gray-300" />
        <div 
          className="w-0 h-0" 
          style={{
            borderLeft: '4px solid transparent',
            borderRight: '4px solid transparent',
            borderTop: '5px solid #d1d5db',
          }}
        />
      </div>

      {/* 弹出菜单 */}
      <AnimatePresence>
        {isOpen && (
          <>
            <div className="fixed inset-0 z-20" onClick={() => setIsOpen(false)} />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: -5 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: -5 }}
              transition={{ duration: 0.15 }}
              className="absolute left-1/2 -translate-x-1/2 top-12 z-30 w-80 bg-[#1a1a1a] rounded-2xl shadow-2xl overflow-hidden"
            >
              {/* 人工节点 */}
              <div className="p-4">
                <div className="text-sm text-gray-400 mb-3 px-1 font-medium">{t.approvals.dingProcessDesigner.humanNodes}</div>
                <div className="grid grid-cols-2 gap-3">
                  {approverOptions.map((option) => (
                    <button
                      key={option.type}
                      onClick={() => handleAdd(option.type)}
                      className="flex items-center gap-3 px-4 py-3.5 rounded-xl bg-[#2a2a2a] hover:bg-[#383838] transition-colors"
                    >
                      <div
                        className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
                        style={{ backgroundColor: option.color.primary }}
                      >
                        <option.icon className="w-5 h-5 text-white" />
                      </div>
                      <span className="text-base text-white font-medium">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>

              {/* 分支节点 */}
              <div className="p-4 pt-0">
                <div className="text-sm text-gray-400 mb-3 px-1 font-medium">{t.approvals.dingProcessDesigner.branchNodes}</div>
                <div className="grid grid-cols-2 gap-3">
                  {branchOptions.map((option) => (
                    <button
                      key={option.type}
                      onClick={() => handleAdd(option.type)}
                      className="flex items-center gap-3 px-4 py-3.5 rounded-xl bg-[#2a2a2a] hover:bg-[#383838] transition-colors"
                    >
                      <div
                        className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
                        style={{ backgroundColor: option.color.primary }}
                      >
                        <option.icon className="w-5 h-5 text-white" />
                      </div>
                      <span className="text-base text-white font-medium">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

// ============================================
// 发起节点
// ============================================

function StartNode() {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center">
      <div className="flex items-center gap-2 px-5 py-2.5 bg-[#565656] rounded-full text-white shadow-sm">
        <User className="w-4 h-4" />
        <span className="text-sm font-medium">{t.approvals.dingProcessDesigner.initiator}</span>
        <ChevronRight className="w-4 h-4 opacity-60" />
      </div>
    </div>
  );
}

// ============================================
// 结束节点
// ============================================

function EndNode() {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center pt-2">
      <div className="w-3 h-3 rounded-full bg-gray-400" />
      <div className="px-6 py-2 mt-2 bg-[#f5f5f5] rounded-full text-gray-500 text-sm font-medium border border-gray-200">
        {t.approvals.dingProcessDesigner.processEnd}
      </div>
    </div>
  );
}

// ============================================
// 审批人/执行人/抄送人 节点卡片
// ============================================

interface TaskNodeCardProps {
  node: FlowNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
}

function TaskNodeCard({ node, isSelected, onSelect, onDelete }: TaskNodeCardProps) {
  const { t } = useTranslation();
  const color = node.type === 'USER_TASK' 
    ? NODE_COLORS.USER_TASK 
    : node.type === 'EXECUTOR' 
      ? NODE_COLORS.EXECUTOR 
      : NODE_COLORS.CC;

  const Icon = node.type === 'USER_TASK' 
    ? UserCheck 
    : node.type === 'EXECUTOR' 
      ? UserCog 
      : Users;

  const typeLabel = node.type === 'USER_TASK' 
    ? t.approvals.dingProcessDesigner.approver
    : node.type === 'EXECUTOR' 
      ? t.approvals.dingProcessDesigner.executor
      : t.approvals.dingProcessDesigner.ccPerson;

  const getConfigLabel = () => {
    const type = node.config?.approverType;
    if (!type) return t.approvals.dingProcessDesigner.pleaseSet.replace('{type}', typeLabel);
    
    const labels: Record<string, string> = {
      INITIATOR_MANAGER: node.config?.managerLevel 
        ? t.approvals.dingProcessDesigner.configLabels.initiatorManagerLevel.replace('{level}', String(node.config.managerLevel))
        : t.approvals.dingProcessDesigner.configLabels.initiatorManager,
      MANAGER_CHAIN: t.approvals.dingProcessDesigner.configLabels.managerChain,
      FIXED_USER: t.approvals.dingProcessDesigner.configLabels.fixedUser,
      ROLE: t.approvals.dingProcessDesigner.configLabels.role,
      DEPARTMENT: t.approvals.dingProcessDesigner.configLabels.department,
      FORM_FIELD: t.approvals.dingProcessDesigner.configLabels.formField,
    };
    return labels[type] || t.approvals.dingProcessDesigner.pleaseSet.replace('{type}', typeLabel);
  };

  return (
    <div
      onClick={(e) => {
        e.stopPropagation();
        onSelect();
      }}
      className={`
        group relative w-[220px] bg-white rounded-xl cursor-pointer
        transition-all duration-200 shadow-sm
        ${isSelected 
          ? 'shadow-lg' 
          : 'hover:shadow-md'
        }
      `}
      style={{
        border: `2px solid ${isSelected ? color.primary : color.border}`,
      }}
    >
      {/* 内容 */}
      <div className="p-3">
        <div className="flex items-center gap-2.5">
          <div
            className="w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0"
            style={{ backgroundColor: color.primary }}
          >
            <Icon className="w-5 h-5 text-white" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm font-medium text-gray-900 truncate">
              {node.name || typeLabel}
            </div>
            <div className="text-xs text-gray-400 mt-0.5 flex items-center">
              <span className="truncate">{getConfigLabel()}</span>
              <ChevronRight className="w-3.5 h-3.5 text-gray-300 flex-shrink-0 ml-0.5" />
            </div>
          </div>
        </div>
      </div>

      {/* 删除按钮 - 悬停时显示 */}
      <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity">
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-lg hover:scale-110 transition-all"
          title={t.approvals.dingProcessDesigner.deleteNode}
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}

// ============================================
// 条件分支容器
// ============================================

interface ConditionBranchContainerProps {
  node: FlowNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
  onAddBranch: () => void;
  onDeleteBranch: (branchId: string) => void;
  onSelectBranch: (branchId: string) => void;
  selectedBranchId: string | null;
  onAddNodeToBranch: (branchId: string, type: ProcessNodeType) => void;
  onSelectNodeInBranch: (branchId: string, nodeId: string) => void;
  onDeleteNodeInBranch: (branchId: string, nodeId: string) => void;
  selectedNodeId: string | null;
}

function ConditionBranchContainer({
  node,
  isSelected,
  onSelect,
  onDelete,
  onAddBranch,
  onDeleteBranch,
  onSelectBranch,
  selectedBranchId,
  onAddNodeToBranch,
  onSelectNodeInBranch,
  onDeleteNodeInBranch,
  selectedNodeId,
}: ConditionBranchContainerProps) {
  const { t } = useTranslation();
  const branches = node.conditions || [];
  const color = NODE_COLORS.CONDITION;

  return (
    <div className="flex flex-col items-center relative group">
      {/* 删除整个条件分支节点的按钮 */}
      <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity z-10">
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-lg hover:scale-110 transition-all"
          title={t.approvals.dingProcessDesigner.deleteCondition}
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 添加条件按钮 */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          onAddBranch();
        }}
        className="px-4 py-1.5 bg-white border border-gray-300 rounded-full text-sm text-gray-600 hover:bg-gray-50 hover:border-gray-400 transition-colors shadow-sm"
      >
        {t.approvals.dingProcessDesigner.addCondition}
      </button>

      {/* 连接线 - 顶部汇聚点 */}
      <div className="w-px h-3 bg-gray-300" />
      
      {/* 分支容器 */}
      <div className="relative flex">
        {/* 顶部横线 */}
        <div 
          className="absolute top-0 h-px bg-gray-300"
          style={{
            left: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
            right: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
          }}
        />

        {/* 各分支 */}
        {branches.map((branch, index) => (
          <div key={branch.id} className="flex flex-col items-center px-3">
            {/* 分支顶部连接线 */}
            <div className="w-px h-3 bg-gray-300" />
            
            {/* 条件卡片 */}
            <div
              onClick={(e) => {
                e.stopPropagation();
                onSelect();  // 同时选中网关节点
                onSelectBranch(branch.id);
              }}
              className={`
                group relative w-[200px] bg-white rounded-xl cursor-pointer
                transition-all duration-200 shadow-sm
                ${selectedBranchId === branch.id 
                  ? 'shadow-lg' 
                  : 'hover:shadow-md'
                }
              `}
              style={{
                border: `2px solid ${selectedBranchId === branch.id ? color.primary : color.border}`,
              }}
            >
              <div className="p-3">
                {/* 标题行 */}
                <div className="flex items-center justify-between mb-2">
                  <span 
                    className="text-sm font-medium"
                    style={{ color: color.text }}
                  >
                    {branch.isDefault ? t.approvals.dingProcessDesigner.otherCases : branch.name || t.approvals.dingProcessDesigner.condition}
                  </span>
                  <span className="text-xs text-gray-400">
                    {t.approvals.dingProcessDesigner.priority.replace('{priority}', String(branch.priority))}
                  </span>
                </div>
                {/* 条件描述 */}
                <div className="text-xs text-gray-500">
                  {branch.isDefault 
                    ? t.approvals.dingProcessDesigner.otherCasesDesc
                    : branch.condition || t.approvals.dingProcessDesigner.pleaseSetCondition}
                </div>
              </div>

              {/* 删除按钮 - 悬停时显示，至少保留1个分支 */}
              {branches.length > 1 ? (
                <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onDeleteBranch(branch.id);
                    }}
                    className="w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-lg hover:scale-110 transition-all"
                    title="删除分支"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                  <div 
                    className="w-7 h-7 bg-gray-400 text-white rounded-full flex items-center justify-center shadow-lg cursor-not-allowed"
                    title={t.approvals.dingProcessDesigner.minOneBranch}
                  >
                    <X className="w-4 h-4" />
                  </div>
                </div>
              )}
            </div>

            {/* 分支内的节点 */}
            <div className="flex flex-col items-center">
              {branch.children.map((childNode, childIndex) => (
                <React.Fragment key={childNode.id}>
                  <AddNodeButton 
                    onAdd={(type) => onAddNodeToBranch(branch.id, type)} 
                    size="small"
                  />
                  <TaskNodeCard
                    node={childNode}
                    isSelected={selectedNodeId === childNode.id}
                    onSelect={() => onSelectNodeInBranch(branch.id, childNode.id)}
                    onDelete={() => onDeleteNodeInBranch(branch.id, childNode.id)}
                  />
                </React.Fragment>
              ))}
              
              {/* 分支末尾添加按钮 */}
              <AddNodeButton 
                onAdd={(type) => onAddNodeToBranch(branch.id, type)} 
                size="small"
              />
            </div>

            {/* 分支底部连接线 */}
            <div className="w-px h-3 bg-gray-300" />
          </div>
        ))}

        {/* 底部横线 */}
        <div 
          className="absolute bottom-0 h-px bg-gray-300"
          style={{
            left: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
            right: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
          }}
        />
      </div>

      {/* 连接线 - 底部汇聚点 */}
      <div className="w-px h-3 bg-gray-300" />
    </div>
  );
}

// ============================================
// 并行分支容器
// ============================================

interface ParallelBranchContainerProps {
  node: FlowNode;
  isSelected: boolean;
  onSelect: () => void;
  onDelete: () => void;
  onAddBranch: () => void;
  onDeleteBranch: (branchId: string) => void;
  onAddNodeToBranch: (branchId: string, type: ProcessNodeType) => void;
  onSelectNodeInBranch: (branchId: string, nodeId: string) => void;
  onDeleteNodeInBranch: (branchId: string, nodeId: string) => void;
  selectedNodeId: string | null;
}

function ParallelBranchContainer({
  node,
  isSelected,
  onSelect,
  onDelete,
  onAddBranch,
  onDeleteBranch,
  onAddNodeToBranch,
  onSelectNodeInBranch,
  onDeleteNodeInBranch,
  selectedNodeId,
}: ParallelBranchContainerProps) {
  const { t } = useTranslation();
  const branches = node.parallelBranches || [];
  const color = NODE_COLORS.PARALLEL;

  return (
    <div className="flex flex-col items-center relative group">
      {/* 删除整个并行分支节点的按钮 */}
      <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity z-10">
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-lg hover:scale-110 transition-all"
          title={t.approvals.dingProcessDesigner.deleteParallel}
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 添加分支按钮 */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          onAddBranch();
        }}
        className="px-4 py-1.5 bg-white border border-gray-300 rounded-full text-sm text-gray-600 hover:bg-gray-50 hover:border-gray-400 transition-colors shadow-sm"
      >
        {t.approvals.dingProcessDesigner.addBranch}
      </button>

      {/* 连接线 - 顶部汇聚点 */}
      <div className="w-px h-3 bg-gray-300" />
      
      {/* 并行分支头部标识 */}
      <div 
        className="flex items-center gap-2 px-4 py-1.5 rounded-full text-sm font-medium shadow-sm"
        style={{ 
          backgroundColor: color.bg, 
          color: color.text,
          border: `1px solid ${color.border}`,
        }}
      >
        <GitMerge className="w-4 h-4" />
        <span>{t.approvals.dingProcessDesigner.parallelExecution}</span>
      </div>
      
      {/* 连接线 */}
      <div className="w-px h-3 bg-gray-300" />
      
      {/* 分支容器 */}
      <div className="relative flex">
        {/* 顶部横线 */}
        <div 
          className="absolute top-0 h-px"
          style={{
            backgroundColor: color.primary,
            left: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
            right: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
          }}
        />

        {/* 各并行分支 */}
        {branches.map((branch, index) => (
          <div key={branch.id} className="flex flex-col items-center px-3">
            {/* 分支顶部连接线 */}
            <div className="w-px h-3" style={{ backgroundColor: color.primary }} />
            
            {/* 分支名称卡片 */}
            <div
              className={`
                group relative w-[200px] bg-white rounded-xl cursor-pointer
                transition-all duration-200 shadow-sm hover:shadow-md
              `}
              style={{
                border: `2px solid ${color.border}`,
              }}
            >
              <div className="p-3">
                <div className="flex items-center justify-between">
                  <span 
                    className="text-sm font-medium"
                    style={{ color: color.text }}
                  >
                    {branch.name || t.approvals.dingProcessDesigner.branch.replace('{number}', String(index + 1))}
                  </span>
                  <span className="text-xs text-gray-400">
                    {t.approvals.dingProcessDesigner.parallel}
                  </span>
                </div>
                <div className="text-xs text-gray-500 mt-1">
                  {branch.children.length === 0 
                    ? t.approvals.dingProcessDesigner.clickToAddNode
                    : t.approvals.dingProcessDesigner.nodeCount.replace('{count}', String(branch.children.length))}
                </div>
              </div>

              {/* 删除按钮 - 悬停时显示，至少保留2个分支 */}
              {branches.length > 2 && (
                <div className="absolute -top-3 -right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onDeleteBranch(branch.id);
                    }}
                    className="w-7 h-7 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 shadow-lg hover:scale-110 transition-all"
                    title={t.approvals.dingProcessDesigner.deleteBranch}
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              )}
            </div>

            {/* 分支内的节点 */}
            <div className="flex flex-col items-center">
              {branch.children.map((childNode) => (
                <React.Fragment key={childNode.id}>
                  <AddNodeButton 
                    onAdd={(type) => onAddNodeToBranch(branch.id, type)} 
                    size="small"
                  />
                  <TaskNodeCard
                    node={childNode}
                    isSelected={selectedNodeId === childNode.id}
                    onSelect={() => onSelectNodeInBranch(branch.id, childNode.id)}
                    onDelete={() => onDeleteNodeInBranch(branch.id, childNode.id)}
                  />
                </React.Fragment>
              ))}
              
              {/* 分支末尾添加按钮 */}
              <AddNodeButton 
                onAdd={(type) => onAddNodeToBranch(branch.id, type)} 
                size="small"
              />
            </div>

            {/* 分支底部连接线 */}
            <div className="w-px h-3" style={{ backgroundColor: color.primary }} />
          </div>
        ))}

        {/* 底部横线 */}
        <div 
          className="absolute bottom-0 h-px"
          style={{
            backgroundColor: color.primary,
            left: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
            right: branches.length > 1 ? `${100 / branches.length / 2}%` : '50%',
          }}
        />
      </div>

      {/* 连接线 - 底部汇聚点 */}
      <div className="w-px h-3 bg-gray-300" />
      
      {/* 汇聚标识 */}
      <div 
        className="flex items-center gap-2 px-4 py-1.5 rounded-full text-sm font-medium shadow-sm"
        style={{ 
          backgroundColor: color.bg, 
          color: color.text,
          border: `1px solid ${color.border}`,
        }}
      >
        <GitMerge className="w-4 h-4 rotate-180" />
        <span>{t.approvals.dingProcessDesigner.continueAfterAll}</span>
      </div>
      
      {/* 底部连接线 */}
      <div className="w-px h-3 bg-gray-300" />
    </div>
  );
}

// ============================================
// 主组件
// ============================================

interface DingProcessDesignerProps {
  initialModel?: ProcessModel;
  onChange?: (model: ProcessModel) => void;
}

export function DingProcessDesigner({ initialModel, onChange }: DingProcessDesignerProps) {
  const { t } = useTranslation();
  const [nodes, setNodes] = useState<FlowNode[]>([]);
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
  const [selectedBranchId, setSelectedBranchId] = useState<string | null>(null);
  const [history, setHistory] = useState<FlowNode[][]>([[]]);
  const [historyIndex, setHistoryIndex] = useState(0);
  const [isInitialized, setIsInitialized] = useState(false);
  
  const onChangeRef = useRef(onChange);
  onChangeRef.current = onChange;

  // 初始化
  useEffect(() => {
    if (!isInitialized) {
      if (initialModel && initialModel.nodes.length > 0) {
        const workNodes = initialModel.nodes
          .filter((n) => n.type !== 'START' && n.type !== 'END')
          .map((n) => {
            const flowNode: FlowNode = {
              id: n.id,
              type: n.type as ProcessNodeType,
              name: n.name,
              config: n.config || {},
            };
            
            // 如果是条件分支网关，还原 conditions 结构
            if (n.type === 'EXCLUSIVE_GATEWAY' && n.config?.conditions) {
              flowNode.conditions = (n.config.conditions as any[]).map(condition => ({
                id: condition.id,
                name: condition.name,
                priority: condition.priority,
                condition: condition.condition,
                isDefault: condition.isDefault,
                children: [],
              }));
            }
            
            return flowNode;
          });
        setNodes(workNodes);
        setHistory([workNodes]);
      }
      setIsInitialized(true);
    }
  }, [initialModel, isInitialized]);

  // 通知变化
  useEffect(() => {
    if (!isInitialized) return;
    
    // 转换为 ProcessModel 格式
    const startNode: ProcessNode = {
      id: 'start',
      type: 'START',
      name: t.approvals.dingProcessDesigner.initiator,
      position: { x: 0, y: 0 },
      config: {},
    };
    const endNode: ProcessNode = {
      id: 'end',
      type: 'END',
      name: t.approvals.dingProcessDesigner.endNode,
      position: { x: 0, y: 0 },
      config: {},
    };
    
    // 递归转换 FlowNode 到 ProcessNode
    const convertNode = (flowNode: FlowNode): ProcessNode[] => {
      // 转换 approverType 到 assignees（如果需要）
      const config = { ...flowNode.config };
      let assignees: string[] = [];
      
      if (flowNode.type === 'USER_TASK' && config.approverType) {
        // 将前端的 approverType 转换为后端 Workflow 需要的 assignees 格式
        switch (config.approverType) {
          case 'INITIATOR_MANAGER':
            // 支持固定层级上级：initiator:manager 或 initiator:manager[N]
            const managerLevel = config.managerLevel || 1;
            if (managerLevel === 1) {
              assignees.push('initiator:manager');
            } else {
              assignees.push(`initiator:manager[${managerLevel}]`);
            }
            break;
          case 'DEPT_MANAGER':
            assignees.push('initiator:deptManager');
            break;
          case 'MANAGER_CHAIN':
            // 连续上级审批，支持终止条件
            const stopCondition = config.chainConfig?.stopCondition || 'deptHead';
            if (stopCondition === 'deptHead') {
              assignees.push('initiator:managerChain');
            } else {
              assignees.push(`initiator:managerChain:${stopCondition}`);
            }
            break;
          case 'FORM_FIELD':
            if (config.approverConfig?.formField) {
              assignees.push(`formField:${config.approverConfig.formField}`);
            }
            break;
          case 'FIXED_USER':
            // 使用 approvers 或 approverDetails
            if (config.approvers && config.approvers.length > 0) {
              assignees.push(...config.approvers.map((id: string) => `user:${id}`));
            }
            break;
          case 'ROLE':
            if (config.approverConfig?.roles && config.approverConfig.roles.length > 0) {
              assignees.push(...config.approverConfig.roles.map((role: string) => `role:${role}`));
            }
            break;
        }
      }
      
      const baseNode: ProcessNode = {
        id: flowNode.id,
        type: flowNode.type,
        name: flowNode.name,
        position: { x: 0, y: 0 },
        config,
        // assignees 放在顶层，不是在 config 里
        ...(assignees.length > 0 && { assignees }),
      };
      
      // 如果有条件分支，保存条件配置
      if (flowNode.conditions && flowNode.conditions.length > 0) {
        // 添加网关节点
        const gatewayNode: ProcessNode = {
          ...baseNode,
          type: 'EXCLUSIVE_GATEWAY',
          config: {
            ...baseNode.config,
            conditions: flowNode.conditions.map(condition => ({
              id: condition.id,
              name: condition.name,
              priority: condition.priority,
              condition: condition.condition,
              isDefault: condition.isDefault,
            })),
          },
        };
        
        return [gatewayNode];
      }
      
      return [baseNode];
    };
    
    // 转换所有节点
    const processNodes: ProcessNode[] = nodes.flatMap(convertNode);
    
    const allNodes = [startNode, ...processNodes, endNode];
    const edges = allNodes.slice(0, -1).map((node, index) => ({
      id: generateEdgeId(),
      source: node.id,
      target: allNodes[index + 1].id,
    }));
    
    onChangeRef.current?.({ nodes: allNodes, edges });
  }, [nodes, isInitialized]);

  // 添加节点
  const handleAddNode = useCallback((afterIndex: number, type: ProcessNodeType) => {
    if (type === 'EXCLUSIVE_GATEWAY') {
      // 添加条件分支（默认创建两个分支）
      const newNode: FlowNode = {
        id: generateNodeId(),
        type,
        name: '条件分支',
        config: {},
        conditions: [
          {
            id: generateNodeId(),
            name: '条件1',
            priority: 1,
            condition: '',
            children: [],
          },
          {
            id: generateNodeId(),
            name: '条件2',
            priority: 2,
            condition: '',
            children: [],
          },
        ],
      };
      
      setNodes((prev) => {
        const newNodes = [...prev];
        newNodes.splice(afterIndex, 0, newNode);
        return newNodes;
      });
    } else if (type === 'PARALLEL_GATEWAY') {
      // 添加并行分支
      const newNode: FlowNode = {
        id: generateNodeId(),
        type,
        name: t.approvals.dingProcessDesigner.parallelBranch,
        config: {},
        parallelBranches: [
          {
            id: generateNodeId(),
            name: t.approvals.dingProcessDesigner.branch1,
            children: [],
          },
          {
            id: generateNodeId(),
            name: t.approvals.dingProcessDesigner.branch2,
            children: [],
          },
        ],
      };
      
      setNodes((prev) => {
        const newNodes = [...prev];
        newNodes.splice(afterIndex, 0, newNode);
        return newNodes;
      });
    } else {
      const typeLabel = type === 'USER_TASK' ? t.approvals.dingProcessDesigner.approver : type === 'EXECUTOR' ? t.approvals.dingProcessDesigner.executor : t.approvals.dingProcessDesigner.ccPerson;
      const newNode: FlowNode = {
        id: generateNodeId(),
        type,
        name: typeLabel,
        config: type !== 'CC' ? { approverType: 'INITIATOR_MANAGER', approvalMode: 'SINGLE' } : {},
      };
      
      setNodes((prev) => {
        const newNodes = [...prev];
        newNodes.splice(afterIndex, 0, newNode);
        return newNodes;
      });
      setSelectedNodeId(newNode.id);
    }
  }, []);

  // 删除节点
  const handleDeleteNode = useCallback((nodeId: string) => {
    setNodes((prev) => prev.filter((n) => n.id !== nodeId));
    setSelectedNodeId(null);
  }, []);

  // 更新节点
  const handleUpdateNode = useCallback((nodeId: string, updates: Partial<FlowNode>) => {
    setNodes((prev) => {
      const updated = prev.map((n) => {
        // 更新主节点
        if (n.id === nodeId) {
          return { ...n, ...updates };
        }
        
        // 更新条件分支内的节点
        if (n.conditions) {
          const hasUpdatedBranch = n.conditions.some(branch => 
            branch.children?.some(child => child.id === nodeId)
          );
          
          if (hasUpdatedBranch) {
            return {
              ...n,
              conditions: n.conditions.map(branch => ({
                ...branch,
                children: branch.children?.map(child =>
                  child.id === nodeId
                    ? { ...child, ...updates }
                    : child
                ),
              })),
            };
          }
        }
        
        // 更新并行分支内的节点
        if (n.parallelBranches) {
          const hasUpdatedBranch = n.parallelBranches.some(branch => 
            branch.children?.some(child => child.id === nodeId)
          );
          
          if (hasUpdatedBranch) {
            return {
              ...n,
              parallelBranches: n.parallelBranches.map(branch => ({
                ...branch,
                children: branch.children?.map(child =>
                  child.id === nodeId
                    ? { ...child, ...updates }
                    : child
                ),
              })),
            };
          }
        }
        
        return n;
      });
      
      return updated;
    });
  }, []);

  // 更新节点配置
  const handleUpdateNodeConfig = useCallback((nodeId: string, config: Partial<ProcessNodeConfig>) => {
    setNodes((prev) =>
      prev.map((n) =>
        n.id === nodeId ? { ...n, config: { ...n.config, ...config } } : n
      )
    );
  }, []);

  // 添加分支
  const handleAddBranch = useCallback((nodeId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.conditions) {
          const newPriority = n.conditions.length + 1;
          const newConditions = [...n.conditions, {
            id: generateNodeId(),
            name: t.approvals.dingProcessDesigner.condition + newPriority,
            priority: newPriority,
            condition: '',
            children: [],
          }];
          return { ...n, conditions: newConditions };
        }
        return n;
      })
    );
  }, []);

  // 删除分支
  const handleDeleteBranch = useCallback((nodeId: string, branchId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.conditions && n.conditions.length > 1) {
          return {
            ...n,
            conditions: n.conditions.filter((c) => c.id !== branchId),
          };
        }
        return n;
      })
    );
  }, []);

  // 向分支添加节点
  const handleAddNodeToBranch = useCallback((nodeId: string, branchId: string, type: ProcessNodeType) => {
    if (type === 'EXCLUSIVE_GATEWAY' || type === 'PARALLEL_GATEWAY') return; // 分支内不允许再添加分支
    
    const typeLabel = type === 'USER_TASK' ? t.approvals.dingProcessDesigner.approver : type === 'EXECUTOR' ? t.approvals.dingProcessDesigner.executor : t.approvals.dingProcessDesigner.ccPerson;
    const newNode: FlowNode = {
      id: generateNodeId(),
      type,
      name: typeLabel,
      config: type !== 'CC' ? { approverType: 'INITIATOR_MANAGER', approvalMode: 'SINGLE' } : {},
    };

    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.conditions) {
          return {
            ...n,
            conditions: n.conditions.map((c) => {
              if (c.id === branchId) {
                return {
                  ...c,
                  children: [...c.children, newNode],
                };
              }
              return c;
            }),
          };
        }
        return n;
      })
    );
    setSelectedNodeId(newNode.id);
  }, []);

  // 删除分支内的节点
  const handleDeleteNodeInBranch = useCallback((nodeId: string, branchId: string, childNodeId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.conditions) {
          return {
            ...n,
            conditions: n.conditions.map((c) => {
              if (c.id === branchId) {
                return {
                  ...c,
                  children: c.children.filter((child) => child.id !== childNodeId),
                };
              }
              return c;
            }),
          };
        }
        return n;
      })
    );
    setSelectedNodeId(null);
  }, []);

  // 添加并行分支
  const handleAddParallelBranch = useCallback((nodeId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.parallelBranches) {
          const branchCount = n.parallelBranches.length;
          return {
            ...n,
            parallelBranches: [
              ...n.parallelBranches,
              {
                id: generateNodeId(),
                name: t.approvals.dingProcessDesigner.branch.replace('{number}', String(branchCount + 1)),
                children: [],
              },
            ],
          };
        }
        return n;
      })
    );
  }, []);

  // 删除并行分支
  const handleDeleteParallelBranch = useCallback((nodeId: string, branchId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.parallelBranches && n.parallelBranches.length > 2) {
          return {
            ...n,
            parallelBranches: n.parallelBranches.filter((b) => b.id !== branchId),
          };
        }
        return n;
      })
    );
  }, []);

  // 向并行分支添加节点
  const handleAddNodeToParallelBranch = useCallback((nodeId: string, branchId: string, type: ProcessNodeType) => {
    if (type === 'EXCLUSIVE_GATEWAY' || type === 'PARALLEL_GATEWAY') return; // 分支内不允许再添加分支
    
    const typeLabel = type === 'USER_TASK' ? t.approvals.dingProcessDesigner.approver : type === 'EXECUTOR' ? t.approvals.dingProcessDesigner.executor : t.approvals.dingProcessDesigner.ccPerson;
    const newNode: FlowNode = {
      id: generateNodeId(),
      type,
      name: typeLabel,
      config: type !== 'CC' ? { approverType: 'INITIATOR_MANAGER', approvalMode: 'SINGLE' } : {},
    };

    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.parallelBranches) {
          return {
            ...n,
            parallelBranches: n.parallelBranches.map((b) => {
              if (b.id === branchId) {
                return {
                  ...b,
                  children: [...b.children, newNode],
                };
              }
              return b;
            }),
          };
        }
        return n;
      })
    );
    setSelectedNodeId(newNode.id);
  }, []);

  // 删除并行分支内的节点
  const handleDeleteNodeInParallelBranch = useCallback((nodeId: string, branchId: string, childNodeId: string) => {
    setNodes((prev) =>
      prev.map((n) => {
        if (n.id === nodeId && n.parallelBranches) {
          return {
            ...n,
            parallelBranches: n.parallelBranches.map((b) => {
              if (b.id === branchId) {
                return {
                  ...b,
                  children: b.children.filter((child) => child.id !== childNodeId),
                };
              }
              return b;
            }),
          };
        }
        return n;
      })
    );
    setSelectedNodeId(null);
  }, []);

  // 撤销
  const undo = useCallback(() => {
    if (historyIndex > 0) {
      setHistoryIndex((prev) => prev - 1);
      setNodes(history[historyIndex - 1]);
    }
  }, [historyIndex, history]);

  // 重做
  const redo = useCallback(() => {
    if (historyIndex < history.length - 1) {
      setHistoryIndex((prev) => prev + 1);
      setNodes(history[historyIndex + 1]);
    }
  }, [historyIndex, history]);

  // 获取选中的节点（包括分支内的节点）
  const getSelectedNode = (): FlowNode | null => {
    if (!selectedNodeId) return null;
    
    // 先在主节点中查找
    const mainNode = nodes.find((n) => n.id === selectedNodeId);
    if (mainNode) return mainNode;
    
    // 在条件分支内查找
    for (const node of nodes) {
      if (node.conditions) {
        for (const branch of node.conditions) {
          const childNode = branch.children.find((c) => c.id === selectedNodeId);
          if (childNode) return childNode;
        }
      }
      // 在并行分支内查找
      if (node.parallelBranches) {
        for (const branch of node.parallelBranches) {
          const childNode = branch.children.find((c) => c.id === selectedNodeId);
          if (childNode) return childNode;
        }
      }
    }
    
    return null;
  };

  const selectedNode = getSelectedNode();

  // 渲染节点
  const renderNode = (node: FlowNode, index: number) => {
    if (node.type === 'EXCLUSIVE_GATEWAY') {
      return (
        <ConditionBranchContainer
          key={node.id}
          node={node}
          isSelected={selectedNodeId === node.id}
          onSelect={() => setSelectedNodeId(node.id)}
          onDelete={() => handleDeleteNode(node.id)}
          onAddBranch={() => handleAddBranch(node.id)}
          onDeleteBranch={(branchId) => handleDeleteBranch(node.id, branchId)}
          onSelectBranch={(branchId) => setSelectedBranchId(branchId)}
          selectedBranchId={selectedBranchId}
          onAddNodeToBranch={(branchId, type) => handleAddNodeToBranch(node.id, branchId, type)}
          onSelectNodeInBranch={(branchId, nodeId) => setSelectedNodeId(nodeId)}
          onDeleteNodeInBranch={(branchId, nodeId) => handleDeleteNodeInBranch(node.id, branchId, nodeId)}
          selectedNodeId={selectedNodeId}
        />
      );
    }

    if (node.type === 'PARALLEL_GATEWAY') {
      return (
        <ParallelBranchContainer
          key={node.id}
          node={node}
          isSelected={selectedNodeId === node.id}
          onSelect={() => setSelectedNodeId(node.id)}
          onDelete={() => handleDeleteNode(node.id)}
          onAddBranch={() => handleAddParallelBranch(node.id)}
          onDeleteBranch={(branchId) => handleDeleteParallelBranch(node.id, branchId)}
          onAddNodeToBranch={(branchId, type) => handleAddNodeToParallelBranch(node.id, branchId, type)}
          onSelectNodeInBranch={(branchId, nodeId) => setSelectedNodeId(nodeId)}
          onDeleteNodeInBranch={(branchId, nodeId) => handleDeleteNodeInParallelBranch(node.id, branchId, nodeId)}
          selectedNodeId={selectedNodeId}
        />
      );
    }

    return (
      <TaskNodeCard
        key={node.id}
        node={node}
        isSelected={selectedNodeId === node.id}
        onSelect={() => setSelectedNodeId(node.id)}
        onDelete={() => handleDeleteNode(node.id)}
      />
    );
  };

  return (
    <div className="h-full flex bg-[#f7f8fa] overflow-hidden">
      {/* 主画布 */}
      <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
        {/* 工具栏 - 固定在顶部 */}
        <div className="flex-shrink-0 bg-white border-b border-gray-200 px-4 py-2 flex items-center justify-between z-10">
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                undo();
              }}
              disabled={historyIndex <= 0}
              className="h-8"
            >
              <Undo2 className="w-4 h-4 mr-1" />
              {t.forms.designer.actions.undo}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                redo();
              }}
              disabled={historyIndex >= history.length - 1}
              className="h-8"
            >
              <Redo2 className="w-4 h-4 mr-1" />
              {t.forms.designer.actions.redo}
            </Button>
          </div>
          <div className="text-sm text-gray-500">
            {t.approvals.dingProcessDesigner.clickToEdit}
          </div>
        </div>

        {/* 流程图 - 可滚动区域 */}
        <div 
          className="flex-1 min-h-0 overflow-auto"
          onClick={() => {
            setSelectedNodeId(null);
            setSelectedBranchId(null);
          }}
        >
          <div 
            className="min-h-full py-10 px-4"
            style={{
              backgroundImage: 'radial-gradient(circle, #e0e0e0 1px, transparent 1px)',
              backgroundSize: '16px 16px',
            }}
          >
            <div className="flex flex-col items-center pb-20">
              {/* 发起节点 */}
              <StartNode />
              
              {/* 添加第一个节点 */}
              <AddNodeButton onAdd={(type) => handleAddNode(0, type)} />

              {/* 工作节点 */}
              {nodes.map((node, index) => (
                <React.Fragment key={node.id}>
                  {renderNode(node, index)}
                  <AddNodeButton onAdd={(type) => handleAddNode(index + 1, type)} />
                </React.Fragment>
              ))}

              {/* 结束节点 */}
              <EndNode />
            </div>
          </div>
        </div>
      </div>

      {/* 属性面板 */}
      <AnimatePresence>
        {selectedNode && selectedNode.type !== 'EXCLUSIVE_GATEWAY' && selectedNode.type !== 'PARALLEL_GATEWAY' && (
          <motion.div
            initial={{ x: 420, opacity: 0 }}
            animate={{ x: 0, opacity: 1 }}
            exit={{ x: 420, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="flex-shrink-0 h-full overflow-hidden"
          >
            <DingStylePropertyPanel
              node={selectedNode}
              onUpdate={(nodeId, updates) => handleUpdateNode(nodeId, updates as Partial<FlowNode>)}
              onUpdateConfig={handleUpdateNodeConfig}
              onClose={() => setSelectedNodeId(null)}
            />
          </motion.div>
        )}
      </AnimatePresence>

      {/* 条件分支配置面板 */}
      <AnimatePresence>
        {selectedBranchId && selectedNode && selectedNode.conditions && (
          <motion.div
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 20 }}
            className="absolute top-0 right-0 h-full w-96 bg-white shadow-2xl border-l border-gray-200 z-50"
          >
            <div className="h-full flex flex-col">
              {/* 面板头部 */}
              <div className="px-4 py-3 border-b border-gray-200 flex items-center justify-between">
                <h3 className="text-base font-semibold text-gray-800">条件配置</h3>
                <button
                  onClick={() => setSelectedBranchId(null)}
                  className="p-1 hover:bg-gray-100 rounded transition-colors"
                >
                  <X className="w-5 h-5 text-gray-500" />
                </button>
              </div>

              {/* 面板内容 */}
              <div className="flex-1 overflow-y-auto p-4">
                {(() => {
                  const branch = selectedNode.conditions.find(c => c.id === selectedBranchId);
                  if (!branch) return null;

                  return (
                    <div className="space-y-4">
                      {/* 分支名称 */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1.5">
                          分支名称
                        </label>
                        <input
                          type="text"
                          value={branch.name}
                          onChange={(e) => {
                            setNodes((prev) =>
                              prev.map((n) =>
                                n.id === selectedNode.id && n.conditions
                                  ? {
                                      ...n,
                                      conditions: n.conditions.map((c) =>
                                        c.id === selectedBranchId
                                          ? { ...c, name: e.target.value }
                                          : c
                                      ),
                                    }
                                  : n
                              )
                            );
                          }}
                          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                          placeholder="输入分支名称"
                        />
                      </div>

                      {/* 优先级 */}
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1.5">
                          优先级
                        </label>
                        <div className="text-sm text-gray-600 px-3 py-2 bg-gray-50 rounded-md">
                          {branch.priority}
                          <span className="ml-2 text-xs text-gray-500">
                            (数字越小，优先级越高)
                          </span>
                        </div>
                      </div>

                      {/* 默认分支设置 */}
                      <div>
                        <label className="flex items-center gap-2 cursor-pointer p-3 border border-gray-200 rounded-md hover:bg-gray-50">
                          <input
                            type="checkbox"
                            checked={branch.isDefault || false}
                            onChange={(e) => {
                              setNodes((prev) =>
                                prev.map((n) =>
                                  n.id === selectedNode.id && n.conditions
                                    ? {
                                        ...n,
                                        conditions: n.conditions.map((c) =>
                                          c.id === selectedBranchId
                                            ? { ...c, isDefault: e.target.checked, condition: e.target.checked ? undefined : c.condition }
                                            : { ...c, isDefault: false } // 取消其他分支的默认标记
                                        ),
                                      }
                                    : n
                                )
                              );
                            }}
                            className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                          />
                          <div>
                            <div className="text-sm font-medium text-gray-700">设为默认分支</div>
                            <div className="text-xs text-gray-500">当所有条件都不满足时，执行此分支</div>
                          </div>
                        </label>
                      </div>

                      {/* 条件表达式 */}
                      {!branch.isDefault && (
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1.5">
                            条件表达式
                          </label>
                          <textarea
                            value={branch.condition || ''}
                            onChange={(e) => {
                              setNodes((prev) =>
                                prev.map((n) =>
                                  n.id === selectedNode.id && n.conditions
                                    ? {
                                        ...n,
                                        conditions: n.conditions.map((c) =>
                                          c.id === selectedBranchId
                                            ? { ...c, condition: e.target.value }
                                            : c
                                        ),
                                      }
                                    : n
                                )
                              );
                            }}
                            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
                            placeholder="例: ${amount} > 10000"
                            rows={4}
                          />
                          <p className="mt-1.5 text-xs text-gray-500">
                            使用 ${'{'}字段标识{'}'} 引用表单字段（如 amount、type），支持比较运算符 &gt; &lt; &gt;= &lt;= == !=
                          </p>
                        </div>
                      )}

                      {/* 默认分支提示 */}
                      {branch.isDefault && (
                        <div className="px-3 py-2 bg-amber-50 border border-amber-200 rounded-md">
                          <p className="text-sm text-amber-800">
                            ℹ️ 这是默认分支，当其他条件都不满足时执行。
                          </p>
                        </div>
                      )}

                      {/* 说明 */}
                      <div className="pt-4 border-t border-gray-200">
                        <h4 className="text-sm font-medium text-gray-700 mb-2">使用说明</h4>
                        <ul className="text-xs text-gray-600 space-y-1.5 list-disc list-inside">
                          <li>条件按优先级从上到下依次判断</li>
                          <li>满足条件的第一个分支会被执行</li>
                          <li>默认分支在最后执行（兜底）</li>
                          <li>字段标识是创建表单时设置的字段 key</li>
                          <li>表达式示例: ${'{'}amount{'}'} {'>'} 5000 或 ${'{'}type{'}'} == '交通费'</li>
                        </ul>
                      </div>
                    </div>
                  );
                })()}
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default DingProcessDesigner;
