<template>
  <div class="growth-path-management-container">
    <!-- 路径列表视图 -->
    <template v-if="!editingPath">
      <div class="page-header">
        <h1 class="page-title">成长路径管理</h1>
        <div class="header-actions">
          <el-select 
            v-model="filters.position_id" 
            placeholder="筛选岗位" 
            clearable 
            style="width: 180px"
            @change="handleFilterChange"
          >
            <el-option label="全部岗位" :value="undefined" />
            <el-option 
              v-for="pos in positions" 
              :key="pos.id" 
              :label="pos.name" 
              :value="pos.id" 
            />
          </el-select>
          <el-select 
            v-model="filters.is_active" 
            placeholder="状态" 
            clearable 
            style="width: 120px"
            @change="handleFilterChange"
          >
            <el-option label="全部状态" :value="undefined" />
            <el-option label="已启用" :value="true" />
            <el-option label="已禁用" :value="false" />
          </el-select>
          <el-button type="primary" @click="handleCreatePath">
            <el-icon class="el-icon--left"><Plus /></el-icon>
            新建路径
          </el-button>
        </div>
      </div>

      <!-- 路径列表 -->
      <div class="path-list-card">
        <el-table :data="growthPaths" v-loading="loading" stripe>
          <el-table-column prop="name" label="路径名称" min-width="200">
            <template #default="{ row }">
              <div class="path-name-cell">
                <span class="path-name">{{ row.name }}</span>
                <el-tag v-if="!row.is_active" size="small" type="info">已禁用</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="position_names" label="关联岗位" min-width="180">
            <template #default="{ row }">
              <template v-if="row.position_names && row.position_names.length > 0">
                <el-tag 
                  v-for="(name, idx) in row.position_names" 
                  :key="idx" 
                  type="primary" 
                  size="small"
                  style="margin-right: 4px;"
                >{{ name }}</el-tag>
              </template>
              <span v-else class="text-muted">未关联</span>
            </template>
          </el-table-column>
          <el-table-column prop="node_count" label="课程数" width="100" align="center" />
          <el-table-column prop="estimated_duration_days" label="预计天数" width="100" align="center">
            <template #default="{ row }">{{ row.estimated_duration_days || '-' }} 天</template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEditPath(row)">编辑</el-button>
              <el-button link type="primary" @click="handleToggleStatus(row)">
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button link type="danger" @click="handleDeletePath(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.page_size"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="loadGrowthPaths"
            @current-change="loadGrowthPaths"
          />
        </div>

        <el-empty v-if="!loading && growthPaths.length === 0" description="暂无成长路径">
          <el-button type="primary" @click="handleCreatePath">创建第一个路径</el-button>
        </el-empty>
      </div>
    </template>

    <!-- 画布编辑视图 -->
    <template v-else>
      <div class="page-header">
        <div class="header-left">
          <el-button link @click="handleBack">
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
          <h1 class="page-title">{{ editingPath.id ? '编辑成长路径' : '新建成长路径' }}</h1>
        </div>
        <div class="header-actions">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" @click="handleSavePath" :loading="saving">
            <el-icon class="el-icon--left"><Check /></el-icon>
            保存
          </el-button>
        </div>
      </div>

      <!-- 基本信息栏 -->
      <div class="path-info-bar">
        <el-form :inline="true" :model="editingPath" size="small">
          <el-form-item label="路径名称" required>
            <el-input v-model="editingPath.name" placeholder="请输入路径名称" style="width: 200px" />
          </el-form-item>
          <el-form-item label="关联岗位">
            <div class="position-select-wrapper">
              <el-select 
                v-model="editingPath.position_ids" 
                placeholder="选择岗位" 
                multiple
                collapse-tags
                collapse-tags-tooltip
                style="width: 200px"
              >
                <el-option v-for="pos in positions" :key="pos.id" :label="pos.name" :value="pos.id" />
              </el-select>
              <el-button link type="primary" size="small" @click="handleSelectAllPositions" class="select-all-btn">
                {{ isAllPositionsSelected ? '取消全选' : '全选' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="预计天数">
            <el-input-number v-model="editingPath.estimated_duration_days" :min="1" :max="365" />
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="editingPath.is_active" active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 阶段管理栏 -->
      <div class="stages-bar">
        <div class="stages-header">
          <span class="stages-title">学习阶段</span>
          <el-button link type="primary" size="small" @click="addStage">
            <el-icon><Plus /></el-icon> 添加阶段
          </el-button>
        </div>
        <div class="stages-list">
          <div v-for="(stage, index) in editingPath.stages" :key="index" class="stage-tag">
            <span class="stage-order">{{ index + 1 }}</span>
            <el-input 
              v-model="stage.name" 
              placeholder="阶段名称"
              size="small"
              style="width: 100px"
            />
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="removeStage(index)"
              :disabled="editingPath.stages.length <= 1"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 操作提示 -->
      <el-alert type="info" :closable="false" style="margin-bottom: 12px">
        <template #title>
          <span>操作提示：从左侧拖拽课程到画布 | 拖拽节点右侧圆点可连接到其他课程（箭头表示前置依赖） | 节点位置决定所属阶段 | 点击必修/选修标签可快速切换</span>
        </template>
      </el-alert>

      <div class="path-designer">
        <!-- 左侧课程库 -->
        <div class="course-library card">
          <div class="library-header">
            <h3>课程库</h3>
            <el-input
              v-model="courseSearch"
              placeholder="搜索课程"
              clearable
              size="small"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select 
              v-model="courseCategory" 
              placeholder="分类" 
              clearable 
              size="small"
              style="width: 100px; margin-top: 8px"
            >
              <el-option 
                v-for="cat in courseCategories" 
                :key="cat" 
                :label="cat" 
                :value="cat" 
              />
            </el-select>
          </div>
          
          <div class="library-content" v-loading="coursesLoading">
            <div
              v-for="course in filteredCourses"
              :key="course.id"
              class="course-item"
              :class="{ 'is-added': isNodeAdded(course.id) }"
              draggable="true"
              @dragstart="handleDragStart($event, course)"
            >
              <el-icon><Reading /></el-icon>
              <span class="course-name">{{ course.name || course.title }}</span>
              <el-tag size="small" type="info">{{ course.duration_hours || 0 }}h</el-tag>
              <el-icon v-if="isNodeAdded(course.id)" color="#67c23a" class="added-icon"><Check /></el-icon>
            </div>
            <el-empty v-if="filteredCourses.length === 0" description="暂无课程" :image-size="60" />
          </div>
        </div>

        <!-- 右侧画布 -->
        <div class="path-canvas card">
          <div class="canvas-header">
            <h3>路径设计画布</h3>
            <div class="canvas-actions">
              <el-button link type="primary" size="small" @click="clearCanvas">
                <el-icon><Delete /></el-icon>
                清空画布
              </el-button>
              <el-button link type="primary" size="small" @click="autoLayout">
                <el-icon><Grid /></el-icon>
                自动布局
              </el-button>
            </div>
          </div>
          
          <div 
            class="canvas-content"
            @dragover.prevent
            @drop="handleDrop"
            @mousemove="handleCanvasMouseMove"
            @mouseup="handleCanvasMouseUp"
            ref="canvasRef"
          >
            <div class="canvas-inner" ref="canvasInnerRef" :style="{ minHeight: canvasMinHeight + 'px' }">
              <!-- 阶段分隔线和区域 -->
              <div 
                v-for="(stage, index) in editingPath.stages" 
                :key="stage.name + index"
                class="stage-zone"
                :style="{ top: (index * stageHeight) + 'px', height: stageHeight + 'px' }"
                :class="{ 'stage-highlight': getStageAtY(draggedNode?.y || 0) === stage.name }"
              >
                <div class="stage-divider">
                  <span class="stage-label">{{ stage.name }}</span>
                </div>
              </div>

              <!-- 空状态 -->
              <div v-if="pathNodes.length === 0" class="empty-state">
                <el-icon :size="64" color="#c0c4cc"><FolderOpened /></el-icon>
                <p>拖拽课程到这里开始设计成长路径</p>
              </div>

              <!-- 连接线（箭头） -->
              <svg class="connections">
                <defs>
                  <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
                    <polygon points="0 0, 10 3.5, 0 7" fill="#667eea" />
                  </marker>
                  <marker id="arrowhead-drawing" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
                    <polygon points="0 0, 10 3.5, 0 7" fill="#f56c6c" />
                  </marker>
                </defs>
                <!-- 已建立的连接 -->
                <path
                  v-for="conn in connections"
                  :key="`${conn.from}-${conn.to}`"
                  :d="getConnectionPath(conn)"
                  stroke="#667eea"
                  stroke-width="2"
                  fill="none"
                  marker-end="url(#arrowhead)"
                  class="connection-line"
                />
                <!-- 正在绘制的连接线 -->
                <path
                  v-if="isDrawingConnection && drawingLine"
                  :d="drawingLine"
                  stroke="#f56c6c"
                  stroke-width="2"
                  stroke-dasharray="5,5"
                  fill="none"
                  marker-end="url(#arrowhead-drawing)"
                />
              </svg>

              <!-- 路径节点 -->
              <div
                v-for="node in pathNodes"
                :key="node.id"
                class="path-node"
                :class="{ 
                  'is-required': node.is_required, 
                  'is-selected': selectedNode?.id === node.id,
                  'is-dragging': draggedNode?.id === node.id,
                  'can-connect': isDrawingConnection && connectionStart?.id !== node.id
                }"
                :style="{ left: node.x + 'px', top: node.y + 'px' }"
                @mousedown.stop="startNodeDrag($event, node)"
              >
                <div class="node-header">
                  <span class="node-title">{{ node.title }}</span>
                  <el-dropdown trigger="click" @command="handleNodeCommand($event, node)">
                    <el-button link size="small" @click.stop>
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="required">
                          {{ node.is_required ? '设为选修' : '设为必修' }}
                        </el-dropdown-item>
                        <el-dropdown-item command="delete" divided>删除节点</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="node-info">
                  <el-tag 
                    size="small" 
                    :type="node.is_required ? 'danger' : ''"
                    style="cursor: pointer"
                    @click.stop="toggleNodeRequired(node)"
                  >
                    {{ node.is_required ? '必修' : '选修' }}
                  </el-tag>
                  <span class="node-stage">{{ node.stage_name }}</span>
                </div>
                <!-- 连接点：右侧拖出箭头 -->
                <div 
                  class="connection-handle output"
                  @mousedown.stop="startDrawConnection($event, node)"
                  title="拖拽到其他课程建立前置关系"
                >
                  <div class="handle-dot"></div>
                </div>
                <!-- 连接点：左侧接收箭头 -->
                <div 
                  class="connection-handle input"
                  @mouseup.stop="endDrawConnection(node)"
                  :class="{ 'can-drop': isDrawingConnection && connectionStart?.id !== node.id }"
                >
                  <div class="handle-dot"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 路径统计 -->
          <div class="canvas-footer">
            <div class="path-stats">
              <div class="stat-item">
                <span class="stat-label">课程总数：</span>
                <span class="stat-value">{{ pathNodes.length }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">必修课程：</span>
                <span class="stat-value">{{ requiredCount }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">总学时：</span>
                <span class="stat-value">{{ totalDuration }}h</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">连接数：</span>
                <span class="stat-value">{{ connections.length }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, ArrowLeft, Check, Delete, Search, More, Grid, Reading, FolderOpened
} from '@element-plus/icons-vue'
import { 
  getGrowthPathConfigs, 
  getGrowthPathDetail,
  createGrowthPath, 
  updateGrowthPath, 
  deleteGrowthPath,
  getManagerCourses,
  type GrowthPathListItem,
  type CreateGrowthPathNode,
  type StageConfig,
} from '@/api/manager'
import request from '@/api/request'

// 接口定义
interface Position {
  id: number
  name: string
}

interface Course {
  id: number
  name?: string
  title?: string
  duration_hours?: number
  category?: string
}

interface PathNode {
  id: string
  course_id: number
  title: string
  is_required: boolean
  estimated_days: number
  x: number
  y: number
  stage_name: string
}

interface Connection {
  from: string
  to: string
}

interface EditingPath {
  id?: number
  name: string
  description?: string
  position_ids: number[]
  stages: StageConfig[]
  estimated_duration_days?: number
  is_active: boolean
}

// ========== 常量 ==========
const stageHeight = 200 // 每个阶段的高度

// ========== 状态 ==========
const loading = ref(false)
const saving = ref(false)
const coursesLoading = ref(false)

// 列表
const growthPaths = ref<GrowthPathListItem[]>([])
const total = ref(0)
const pagination = ref({
  page: 1,
  page_size: 20
})
const filters = ref<{ position_id?: number; is_active?: boolean }>({})

// 编辑
const editingPath = ref<EditingPath | null>(null)
const courseSearch = ref('')
const courseCategory = ref('')
const canvasRef = ref<HTMLElement>()
const canvasInnerRef = ref<HTMLElement>()

// 画布节点和连接
const pathNodes = ref<PathNode[]>([])
const connections = ref<Connection[]>([])
const selectedNode = ref<PathNode | null>(null)

// 节点拖拽
const draggedNode = ref<PathNode | null>(null)
const dragOffset = ref({ x: 0, y: 0 })

// 连线绘制
const isDrawingConnection = ref(false)
const connectionStart = ref<PathNode | null>(null)
const drawingLine = ref('')
const mousePos = ref({ x: 0, y: 0 })

// 基础数据
const positions = ref<Position[]>([])
const courses = ref<Course[]>([])

// ========== 计算属性 ==========

// 课程分类列表
const courseCategories = computed(() => {
  const cats = new Set<string>()
  courses.value.forEach(c => {
    if (c.category) cats.add(c.category)
  })
  return Array.from(cats)
})

// 过滤后的课程
const filteredCourses = computed(() => {
  let result = courses.value
  if (courseSearch.value) {
    const keyword = courseSearch.value.toLowerCase()
    result = result.filter(c => 
      (c.name || c.title || '').toLowerCase().includes(keyword)
    )
  }
  if (courseCategory.value) {
    result = result.filter(c => c.category === courseCategory.value)
  }
  return result
})

const requiredCount = computed(() => pathNodes.value.filter(n => n.is_required).length)

const totalDuration = computed(() => {
  return pathNodes.value.reduce((sum, node) => {
    const course = courses.value.find(c => c.id === node.course_id)
    return sum + (course?.duration_hours || 0)
  }, 0)
})

// 是否全选岗位
const isAllPositionsSelected = computed(() => {
  if (!editingPath.value || positions.value.length === 0) return false
  return editingPath.value.position_ids.length === positions.value.length
})

// 画布最小高度（根据阶段数量动态计算）
const canvasMinHeight = computed(() => {
  if (!editingPath.value) return 700
  return Math.max(700, editingPath.value.stages.length * stageHeight + 100)
})

// ========== 工具方法 ==========

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 根据Y坐标获取所属阶段
 */
const getStageAtY = (y: number): string => {
  if (!editingPath.value) return ''
  const stageIndex = Math.floor(y / stageHeight)
  const clampedIndex = Math.max(0, Math.min(stageIndex, editingPath.value.stages.length - 1))
  return editingPath.value.stages[clampedIndex]?.name || ''
}

/**
 * 更新节点的阶段（根据位置）
 */
const updateNodeStage = (node: PathNode) => {
  node.stage_name = getStageAtY(node.y)
}

// ========== 阶段管理 ==========

const addStage = () => {
  if (!editingPath.value) return
  const newOrder = editingPath.value.stages.length + 1
  editingPath.value.stages.push({
    name: `阶段${newOrder}`,
    order: newOrder
  })
  ElMessage.success('已添加新阶段')
}

const removeStage = (index: number) => {
  if (!editingPath.value || editingPath.value.stages.length <= 1) return
  
  const stageName = editingPath.value.stages[index].name
  // 检查是否有节点在该阶段
  const nodesInStage = pathNodes.value.filter(n => n.stage_name === stageName)
  
  if (nodesInStage.length > 0) {
    ElMessageBox.confirm(
      `该阶段下有 ${nodesInStage.length} 个课程，删除后这些课程将移动到第一个阶段。确定删除吗？`,
      '删除确认',
      { type: 'warning' }
    ).then(() => {
      doRemoveStage(index, stageName)
    }).catch(() => {})
  } else {
    doRemoveStage(index, stageName)
  }
}

const doRemoveStage = (index: number, stageName: string) => {
  if (!editingPath.value) return
  
  // 移动该阶段的节点到第一个阶段
  const firstStageName = editingPath.value.stages[0]?.name
  pathNodes.value.forEach(node => {
    if (node.stage_name === stageName && firstStageName) {
      node.stage_name = firstStageName
      // 重新计算位置
      node.y = 30
    }
  })
  
  editingPath.value.stages.splice(index, 1)
  // 重新编号
  editingPath.value.stages.forEach((s, i) => s.order = i + 1)
  
  ElMessage.success('阶段已删除')
}

// ========== 岗位全选 ==========

const handleSelectAllPositions = () => {
  if (!editingPath.value) return
  if (isAllPositionsSelected.value) {
    editingPath.value.position_ids = []
  } else {
    editingPath.value.position_ids = positions.value.map(p => p.id)
  }
}

// ========== 数据加载 ==========

const loadPositions = async () => {
  try {
    const res = await request.get<{ data: { items: Position[] } }>('/api/v1/admin/positions', {
      params: { page_size: 100 }
    })
    positions.value = res.data?.items || []
  } catch (error) {
    console.error('加载岗位失败:', error)
  }
}

const loadCourses = async () => {
  coursesLoading.value = true
  try {
    // 后端限制每页最多100条，需要分页获取所有课程
    let allCourses: Course[] = []
    let page = 1
    const pageSize = 100
    let hasMore = true
    
    while (hasMore) {
      const res = await getManagerCourses({ page, size: pageSize })
      const items = res.data?.items || res.items || []
      allCourses = [...allCourses, ...items]
      
      // 检查是否还有更多数据
      const total = res.data?.total || res.total || 0
      hasMore = allCourses.length < total && items.length === pageSize
      page++
      
      // 安全限制：最多获取10页（1000门课程）
      if (page > 10) break
    }
    
    courses.value = allCourses
  } catch (error) {
    console.error('加载课程失败:', error)
  } finally {
    coursesLoading.value = false
  }
}

const handleFilterChange = () => {
  pagination.value.page = 1
  loadGrowthPaths()
}

const loadGrowthPaths = async () => {
  loading.value = true
  try {
    const res = await getGrowthPathConfigs({
      page: pagination.value.page,
      page_size: pagination.value.page_size,
      position_id: filters.value.position_id,
      is_active: filters.value.is_active,
    })
    growthPaths.value = res.items || []
    total.value = res.total || 0
  } catch (error) {
    console.error('加载路径失败:', error)
  } finally {
    loading.value = false
  }
}

const isNodeAdded = (courseId: number) => pathNodes.value.some(n => n.course_id === courseId)

const handleCreatePath = () => {
  editingPath.value = {
    name: '',
    position_ids: [],
    stages: [
      { name: '入门阶段', order: 1 },
      { name: '提升阶段', order: 2 },
      { name: '进阶阶段', order: 3 },
    ],
    estimated_duration_days: 30,
    is_active: true,
  }
  pathNodes.value = []
  connections.value = []
}

const handleEditPath = async (row: GrowthPathListItem) => {
  loading.value = true
  try {
    const detail = await getGrowthPathDetail(row.id)
    
    editingPath.value = {
      id: detail.id,
      name: detail.name,
      description: detail.description,
      position_ids: detail.position_ids || (detail.position_id ? [detail.position_id] : []),
      stages: detail.stages || [
        { name: '入门阶段', order: 1 },
        { name: '提升阶段', order: 2 },
        { name: '进阶阶段', order: 3 },
      ],
      estimated_duration_days: detail.estimated_duration_days,
      is_active: detail.is_active,
    }
    
    // 转换节点数据 - 使用保存的位置，如果没有则自动布局
    pathNodes.value = (detail.nodes || []).map((n: any, index: number) => {
      const hasPosition = n.position_x !== undefined && n.position_x !== null && n.position_x > 0
      return {
        id: `n${n.course_id}`,
        course_id: n.course_id,
        title: n.title,
        is_required: n.is_required,
        estimated_days: n.estimated_days || 1,
        stage_name: n.stage_name || editingPath.value!.stages[0]?.name || '入门阶段',
        x: hasPosition ? n.position_x : 50 + (index % 3) * 220,
        y: hasPosition ? n.position_y : 50 + Math.floor(index / 3) * stageHeight,
      }
    })
    
    // 转换前置课程为连接线
    connections.value = []
    ;(detail.nodes || []).forEach((n: any) => {
      if (n.prerequisites && n.prerequisites.length > 0) {
        n.prerequisites.forEach((preId: number) => {
          connections.value.push({
            from: `n${preId}`,
            to: `n${n.course_id}`
          })
        })
      }
    })
  } catch (error) {
    console.error('加载路径详情失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  ElMessageBox.confirm('确定要返回吗？未保存的更改将丢失。', '提示', {
    type: 'warning',
  }).then(() => {
    editingPath.value = null
    pathNodes.value = []
    connections.value = []
  }).catch(() => {})
}

const handleSavePath = async () => {
  if (!editingPath.value) return
  if (!editingPath.value.name?.trim()) {
    ElMessage.warning('请输入路径名称')
    return
  }

  saving.value = true
  try {
    // 转换节点数据，包含位置信息
    const nodes: CreateGrowthPathNode[] = pathNodes.value.map((node, index) => {
      // 获取前置课程
      const prerequisites = connections.value
        .filter(c => c.to === node.id)
        .map(c => {
          const fromNode = pathNodes.value.find(n => n.id === c.from)
          return fromNode?.course_id
        })
        .filter(Boolean) as number[]

      return {
        course_id: node.course_id,
        title: node.title,
        stage_name: node.stage_name,
        order_num: index + 1,
        is_required: node.is_required,
        estimated_days: node.estimated_days,
        prerequisites,
        position_x: Math.round(node.x),
        position_y: Math.round(node.y),
      }
    })

    const payload = {
      name: editingPath.value.name,
      description: editingPath.value.description,
      position_ids: editingPath.value.position_ids,
      stages: editingPath.value.stages,
      estimated_duration_days: editingPath.value.estimated_duration_days,
      is_active: editingPath.value.is_active,
      nodes,
    }

    if (editingPath.value.id) {
      await updateGrowthPath(editingPath.value.id, payload)
      ElMessage.success('更新成功')
    } else {
      await createGrowthPath(payload)
      ElMessage.success('创建成功')
    }

    editingPath.value = null
    pathNodes.value = []
    connections.value = []
    loadGrowthPaths()
  } catch (error: any) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleToggleStatus = async (row: GrowthPathListItem) => {
  try {
    await updateGrowthPath(row.id, { is_active: !row.is_active })
    ElMessage.success(row.is_active ? '已禁用' : '已启用')
    loadGrowthPaths()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleDeletePath = async (row: GrowthPathListItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除路径"${row.name}"吗？`, '删除确认', { type: 'warning' })
    await deleteGrowthPath(row.id)
    ElMessage.success('删除成功')
    loadGrowthPaths()
  } catch (error: any) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}

// ========== 画布操作 ==========

const handleDragStart = (event: DragEvent, course: Course) => {
  event.dataTransfer!.effectAllowed = 'copy'
  event.dataTransfer!.setData('course', JSON.stringify(course))
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  const courseData = event.dataTransfer!.getData('course')
  if (!courseData || !canvasRef.value) return

  const course = JSON.parse(courseData) as Course
  
  if (isNodeAdded(course.id)) {
    ElMessage.warning('该课程已在路径中')
    return
  }

  const rect = canvasRef.value.getBoundingClientRect()
  const scrollLeft = canvasRef.value.scrollLeft
  const scrollTop = canvasRef.value.scrollTop
  const x = event.clientX - rect.left + scrollLeft - 85
  const y = event.clientY - rect.top + scrollTop - 40

  const stageName = getStageAtY(Math.max(0, y))

  const newNode: PathNode = {
    id: `n${course.id}`,
    course_id: course.id,
    title: course.name || course.title || '',
    is_required: true,
    estimated_days: Math.ceil((course.duration_hours || 2) / 2),
    x: Math.max(0, x),
    y: Math.max(0, y),
    stage_name: stageName,
  }

  pathNodes.value.push(newNode)
  ElMessage.success(`已添加到"${stageName}"`)
}

const startNodeDrag = (event: MouseEvent, node: PathNode) => {
  if (!canvasRef.value) return
  
  // 检查是否点击的是连接点
  const target = event.target as HTMLElement
  if (target.closest('.connection-handle')) return
  
  draggedNode.value = node
  selectedNode.value = node
  
  const rect = canvasRef.value.getBoundingClientRect()
  const scrollLeft = canvasRef.value.scrollLeft
  const scrollTop = canvasRef.value.scrollTop
  
  dragOffset.value = {
    x: event.clientX - rect.left + scrollLeft - node.x,
    y: event.clientY - rect.top + scrollTop - node.y
  }

  document.addEventListener('mousemove', handleNodeMouseMove)
  document.addEventListener('mouseup', handleNodeMouseUp)
}

const handleNodeMouseMove = (e: MouseEvent) => {
  if (!draggedNode.value || !canvasRef.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const scrollLeft = canvasRef.value.scrollLeft
  const scrollTop = canvasRef.value.scrollTop
  
  draggedNode.value.x = Math.max(0, e.clientX - rect.left + scrollLeft - dragOffset.value.x)
  draggedNode.value.y = Math.max(0, e.clientY - rect.top + scrollTop - dragOffset.value.y)
  
  // 实时更新阶段
  updateNodeStage(draggedNode.value)
}

const handleNodeMouseUp = () => {
  if (draggedNode.value) {
    // 最终更新阶段
    updateNodeStage(draggedNode.value)
  }
  draggedNode.value = null
  document.removeEventListener('mousemove', handleNodeMouseMove)
  document.removeEventListener('mouseup', handleNodeMouseUp)
}

// ========== 连线绘制 ==========

const startDrawConnection = (event: MouseEvent, node: PathNode) => {
  event.preventDefault()
  isDrawingConnection.value = true
  connectionStart.value = node
  
  if (canvasRef.value) {
    const rect = canvasRef.value.getBoundingClientRect()
    const scrollLeft = canvasRef.value.scrollLeft
    const scrollTop = canvasRef.value.scrollTop
    mousePos.value = {
      x: event.clientX - rect.left + scrollLeft,
      y: event.clientY - rect.top + scrollTop
    }
    updateDrawingLine()
  }
}

const handleCanvasMouseMove = (event: MouseEvent) => {
  if (!isDrawingConnection.value || !canvasRef.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const scrollLeft = canvasRef.value.scrollLeft
  const scrollTop = canvasRef.value.scrollTop
  
  mousePos.value = {
    x: event.clientX - rect.left + scrollLeft,
    y: event.clientY - rect.top + scrollTop
  }
  updateDrawingLine()
}

const handleCanvasMouseUp = () => {
  if (isDrawingConnection.value) {
    // 取消连线
    isDrawingConnection.value = false
    connectionStart.value = null
    drawingLine.value = ''
  }
}

const endDrawConnection = (targetNode: PathNode) => {
  if (!isDrawingConnection.value || !connectionStart.value) return
  if (connectionStart.value.id === targetNode.id) return
  
  // 检查是否已存在连接
  const exists = connections.value.some(
    c => c.from === connectionStart.value!.id && c.to === targetNode.id
  )
  
  if (exists) {
    ElMessage.warning('该连接已存在')
  } else {
    // 检查是否会形成循环
    const wouldCycle = checkCycle(connectionStart.value.id, targetNode.id)
    if (wouldCycle) {
      ElMessage.warning('不能形成循环依赖')
    } else {
      connections.value.push({
        from: connectionStart.value.id,
        to: targetNode.id
      })
      ElMessage.success('连接已建立')
    }
  }
  
  isDrawingConnection.value = false
  connectionStart.value = null
  drawingLine.value = ''
}

const checkCycle = (fromId: string, toId: string): boolean => {
  // 简单的循环检测：检查是否 toId 能到达 fromId
  const visited = new Set<string>()
  const queue = [toId]
  
  while (queue.length > 0) {
    const current = queue.shift()!
    if (current === fromId) return true
    if (visited.has(current)) continue
    visited.add(current)
    
    // 找到所有从 current 出发的连接
    const outgoing = connections.value.filter(c => c.from === current)
    outgoing.forEach(c => queue.push(c.to))
  }
  
  return false
}

const updateDrawingLine = () => {
  if (!connectionStart.value) return
  
  const startX = connectionStart.value.x + 170 // 节点右侧
  const startY = connectionStart.value.y + 45 // 节点中间
  const endX = mousePos.value.x
  const endY = mousePos.value.y
  
  const midX = (startX + endX) / 2
  drawingLine.value = `M ${startX} ${startY} C ${midX} ${startY}, ${midX} ${endY}, ${endX} ${endY}`
}

const getConnectionPath = (conn: Connection) => {
  const fromNode = pathNodes.value.find(n => n.id === conn.from)
  const toNode = pathNodes.value.find(n => n.id === conn.to)
  
  if (!fromNode || !toNode) return ''

  const x1 = fromNode.x + 170 // 从右侧出
  const y1 = fromNode.y + 45
  const x2 = toNode.x // 到左侧入
  const y2 = toNode.y + 45

  const midX = (x1 + x2) / 2
  return `M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`
}

// 点击标签切换必修/选修
const toggleNodeRequired = (node: PathNode) => {
  node.is_required = !node.is_required
}

const handleNodeCommand = (command: string, node: PathNode) => {
  switch (command) {
    case 'required':
      node.is_required = !node.is_required
      break
    case 'delete':
      deleteNode(node)
      break
  }
}

const deleteNode = (node: PathNode) => {
  ElMessageBox.confirm(`确定要删除课程"${node.title}"吗？`, '删除确认', { type: 'warning' })
    .then(() => {
      const index = pathNodes.value.findIndex(n => n.id === node.id)
      if (index > -1) pathNodes.value.splice(index, 1)
      connections.value = connections.value.filter(c => c.from !== node.id && c.to !== node.id)
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const clearCanvas = () => {
  ElMessageBox.confirm('确定要清空画布吗？', '清空确认', { type: 'warning' })
    .then(() => {
      pathNodes.value = []
      connections.value = []
      ElMessage.success('画布已清空')
    })
    .catch(() => {})
}

const autoLayout = () => {
  if (pathNodes.value.length === 0) {
    ElMessage.warning('画布为空')
    return
  }

  const cols = 3
  const xSpacing = 220
  const yOffset = 30

  // 按阶段分组
  const stages = editingPath.value?.stages || []
  stages.forEach((stage, stageIndex) => {
    const stageNodes = pathNodes.value.filter(n => n.stage_name === stage.name)
    stageNodes.forEach((node, nodeIndex) => {
      const col = nodeIndex % cols
      const row = Math.floor(nodeIndex / cols)
      node.x = 50 + col * xSpacing
      node.y = stageIndex * stageHeight + yOffset + row * 100
    })
  })

  // 处理未分配阶段的节点
  const unassigned = pathNodes.value.filter(n => !stages.some(s => s.name === n.stage_name))
  unassigned.forEach((node, index) => {
    node.x = 50 + (index % cols) * xSpacing
    node.y = 30 + Math.floor(index / cols) * 100
    node.stage_name = stages[0]?.name || '入门阶段'
  })

  ElMessage.success('自动布局完成')
}

// ========== 生命周期 ==========
onMounted(() => {
  loadPositions()
  loadCourses()
  loadGrowthPaths()
})
</script>

<style lang="scss" scoped>
.growth-path-management-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-shrink: 0;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .path-list-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .path-name-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      .path-name { font-weight: 500; }
    }
    .text-muted { color: #909399; }

    .pagination-wrapper {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .path-info-bar {
    background: #fff;
    border-radius: 8px;
    padding: 12px 20px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;

    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 24px;
    }

    .position-select-wrapper {
      display: flex;
      align-items: center;
      gap: 8px;

      .select-all-btn {
        white-space: nowrap;
      }
    }
  }

  .stages-bar {
    background: #fff;
    border-radius: 8px;
    padding: 12px 20px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;

    .stages-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .stages-title {
        font-size: 14px;
        font-weight: 600;
        color: #333;
      }
    }

    .stages-list {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;

      .stage-tag {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 12px;
        background: #f5f7fa;
        border-radius: 6px;
        border: 1px solid #e4e7ed;

        .stage-order {
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
          border-radius: 50%;
          font-size: 12px;
          font-weight: 600;
        }
      }
    }
  }

  .path-designer {
    flex: 1;
    display: flex;
    gap: 16px;
    min-height: 0;

    .card {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    .course-library {
      width: 260px;
      display: flex;
      flex-direction: column;

      .library-header {
        padding: 12px 16px;
        border-bottom: 1px solid #ebeef5;

        h3 {
          font-size: 14px;
          font-weight: 600;
          margin-bottom: 10px;
        }
      }

      .library-content {
        flex: 1;
        overflow-y: auto;
        padding: 12px;

        .course-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 12px;
          background: #f5f7fa;
          border-radius: 6px;
          margin-bottom: 8px;
          cursor: grab;
          transition: all 0.2s;
          border: 1px solid transparent;

          &:hover {
            background: #e6e8eb;
            border-color: #667eea;
          }

          &:active { cursor: grabbing; }

          &.is-added {
            background: #f0f9eb;
            border-color: #67c23a;
            opacity: 0.7;
          }

          .course-name {
            flex: 1;
            font-size: 13px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .added-icon { margin-left: auto; }
        }
      }
    }

    .path-canvas {
      flex: 1;
      display: flex;
      flex-direction: column;

      .canvas-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #ebeef5;

        h3 {
          font-size: 14px;
          font-weight: 600;
        }

        .canvas-actions {
          display: flex;
          gap: 12px;
        }
      }

      .canvas-content {
        flex: 1;
        position: relative;
        background: #fafafa;
        overflow: auto;
        min-height: 400px;

        .canvas-inner {
          position: relative;
          width: 100%;
          min-width: 900px;
          background-image: 
            linear-gradient(rgba(102, 126, 234, .06) 1px, transparent 1px),
            linear-gradient(90deg, rgba(102, 126, 234, .06) 1px, transparent 1px);
          background-size: 20px 20px;
        }

        .stage-zone {
          position: absolute;
          left: 0;
          right: 0;
          border-bottom: 1px dashed rgba(102, 126, 234, 0.2);
          transition: background 0.2s;

          &.stage-highlight {
            background: rgba(102, 126, 234, 0.05);
          }

          .stage-divider {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;

            .stage-label {
              position: absolute;
              left: 12px;
              top: 8px;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: #fff;
              padding: 4px 12px;
              font-size: 12px;
              font-weight: 500;
              border-radius: 12px;
              box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
            }
          }
        }

        .empty-state {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          text-align: center;

          p {
            margin-top: 16px;
            font-size: 14px;
            color: #909399;
          }
        }

        .path-node {
          position: absolute;
          width: 170px;
          padding: 12px 14px;
          background: #fff;
          border: 2px solid #e4e7ed;
          border-radius: 10px;
          cursor: move;
          transition: all 0.2s;
          user-select: none;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          z-index: 10;

          &:hover {
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.25);
            border-color: #667eea;
            z-index: 20;
          }

          &.is-required {
            border-color: #f56c6c;
            background: linear-gradient(135deg, #fff 0%, #fff5f5 100%);
          }

          &.is-selected {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
          }

          &.is-dragging {
            opacity: 0.8;
            z-index: 100;
          }

          &.can-connect {
            .connection-handle.input {
              .handle-dot {
                transform: scale(1.5);
                background: #67c23a;
              }
            }
          }

          .node-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 8px;

            .node-title {
              font-size: 13px;
              font-weight: 600;
              color: #333;
              flex: 1;
              line-height: 1.4;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }
          }

          .node-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .node-stage {
              font-size: 11px;
              color: #909399;
            }
          }

          .connection-handle {
            position: absolute;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: crosshair;

            &.output {
              right: -10px;
              top: 50%;
              transform: translateY(-50%);
            }

            &.input {
              left: -10px;
              top: 50%;
              transform: translateY(-50%);
            }

            &.can-drop .handle-dot {
              transform: scale(1.5);
              background: #67c23a;
              box-shadow: 0 0 8px rgba(103, 194, 58, 0.5);
            }

            .handle-dot {
              width: 12px;
              height: 12px;
              background: #667eea;
              border-radius: 50%;
              border: 2px solid #fff;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
              transition: all 0.2s;

              &:hover {
                transform: scale(1.3);
                background: #f56c6c;
              }
            }
          }
        }

        .connections {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;
          z-index: 5;

          .connection-line {
            transition: stroke 0.2s;

            &:hover {
              stroke: #f56c6c;
              stroke-width: 3;
            }
          }
        }
      }

      .canvas-footer {
        padding: 12px 16px;
        border-top: 1px solid #ebeef5;
        background: #fff;

        .path-stats {
          display: flex;
          gap: 32px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 4px;

            .stat-label {
              font-size: 13px;
              color: #666;
            }

            .stat-value {
              font-size: 15px;
              font-weight: 600;
              color: #667eea;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1024px) {
  .growth-path-management-container {
    .path-designer {
      flex-direction: column;

      .course-library {
        width: 100%;
        max-height: 200px;
      }
    }
  }
}
</style>
