<template>
  <div class="position-management-container">
    <div class="page-header">
      <h1 class="page-title">岗位管理</h1>
      <el-button type="primary" @click="createPosition">
        <el-icon class="el-icon--left"><Plus /></el-icon>
        新增岗位
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchText"
        placeholder="搜索岗位名称或描述"
        clearable
        style="width: 300px"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 岗位列表 -->
    <div class="position-list" v-loading="loading">
      <div class="position-card card" v-for="position in filteredPositionList" :key="position.id">
        <div class="card-header">
          <div class="position-title">
            <h3>{{ position.name }}</h3>
            <el-tag :type="position.status === 'active' ? 'success' : 'info'" size="small">
              {{ position.status === 'active' ? '启用' : '停用' }}
            </el-tag>
          </div>
          <el-dropdown trigger="click">
            <el-button link>
              <el-icon><More /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="editPosition(position)">
                  <el-icon><Edit /></el-icon>
                  编辑岗位
                </el-dropdown-item>
                <el-dropdown-item @click="viewMembers(position)">
                  <el-icon><User /></el-icon>
                  查看成员
                </el-dropdown-item>
                <el-dropdown-item @click="manageCourses(position)">
                  <el-icon><Collection /></el-icon>
                  管理课程
                </el-dropdown-item>
                <el-dropdown-item @click="toggleStatus(position)">
                  <el-icon><component :is="position.status === 'active' ? 'CircleClose' : 'CircleCheck'" /></el-icon>
                  {{ position.status === 'active' ? '停用岗位' : '启用岗位' }}
                </el-dropdown-item>
                <el-dropdown-item @click="deletePosition(position)" divided>
                  <el-icon><Delete /></el-icon>
                  删除岗位
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="card-content">
          <p class="position-desc">{{ position.description }}</p>
          
          <div class="position-info">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>人数：{{ position.memberCount }} 人</span>
            </div>
            <div class="info-item">
              <el-icon><Collection /></el-icon>
              <span>必修课程：{{ position.requiredCourses }} 门</span>
            </div>
            <div class="info-item">
              <el-icon><Reading /></el-icon>
              <span>选修课程：{{ position.optionalCourses }} 门</span>
            </div>
          </div>

          <div class="position-skills">
            <h4>核心技能要求</h4>
            <div class="skill-tags">
              <el-tag v-for="skill in position.skills" :key="skill" size="small" type="info">
                {{ skill }}
              </el-tag>
            </div>
          </div>

          <div class="position-stats">
            <div class="stat-item">
              <div class="stat-label">平均学习进度</div>
              <el-progress :percentage="position.avgProgress" :color="getProgressColor(position.avgProgress)" />
            </div>
            <div class="stat-item">
              <div class="stat-label">平均考试成绩</div>
              <div class="stat-value">{{ position.avgScore }} 分</div>
            </div>
          </div>
        </div>

        <div class="card-footer">
          <span class="create-time">创建时间：{{ position.createTime }}</span>
          <span class="update-time">最后更新：{{ position.updateTime }}</span>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="positionList.length === 0" description="暂无岗位数据" />

    <!-- 新增/编辑岗位弹窗 -->
    <el-dialog
      v-model="positionDialogVisible"
      :title="isEdit ? '编辑岗位' : '新增岗位'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="positionForm" :rules="rules" label-width="100px">
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="positionForm.name" placeholder="请输入岗位名称" maxlength="30" show-word-limit />
        </el-form-item>
        
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="positionForm.description"
            type="textarea"
            placeholder="请输入岗位描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="上级岗位" prop="parentId">
          <el-select v-model="positionForm.parentId" placeholder="请选择上级岗位（可选）" clearable style="width: 100%">
            <el-option label="无" :value="null" />
            <el-option
              v-for="pos in getAvailableParentPositions()"
              :key="pos.id"
              :label="pos.name"
              :value="pos.id"
              :disabled="pos.disabled"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="核心技能" prop="skills">
          <el-select
            v-model="positionForm.skills"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择核心技能"
            style="width: 100%"
          >
            <el-option label="沟通能力" value="沟通能力" />
            <el-option label="销售技巧" value="销售技巧" />
            <el-option label="产品知识" value="产品知识" />
            <el-option label="客户服务" value="客户服务" />
            <el-option label="团队协作" value="团队协作" />
            <el-option label="数据分析" value="数据分析" />
            <el-option label="项目管理" value="项目管理" />
          </el-select>
        </el-form-item>

        <el-form-item label="岗位等级" prop="level">
          <el-radio-group v-model="positionForm.level">
            <el-radio label="junior">初级</el-radio>
            <el-radio label="intermediate">中级</el-radio>
            <el-radio label="senior">高级</el-radio>
            <el-radio label="expert">专家</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="positionForm.status"
            active-value="active"
            inactive-value="inactive"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="positionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看成员弹窗 -->
    <el-dialog
      v-model="membersDialogVisible"
      :title="`${currentPosition?.name} - 岗位成员`"
      width="800px"
    >
      <el-table :data="membersList" style="width: 100%" max-height="400">
        <el-table-column prop="full_name" label="姓名" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="user_role" label="系统角色" width="100">
          <template #default="scope">
            <el-tag size="small">{{ getRoleLabel(scope.row.user_role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joined_at" label="加入时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.joined_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'" size="small">
              {{ scope.row.is_active ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeMember(scope.row)">
              移除成员
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 课程管理弹窗 -->
    <el-dialog
      v-model="courseManagementVisible"
      :title="`${currentPosition?.name} - 课程管理`"
      width="900px"
      top="5vh"
    >
      <div class="course-management-content" v-if="currentPosition">
        <!-- 课程统计 -->
        <div class="course-stats">
          <div class="stat-item">
            <div class="stat-value">{{ requiredCourses.length }}</div>
            <div class="stat-label">必修课程</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ optionalCourses.length }}</div>
            <div class="stat-label">选修课程</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ (requiredCourses.length + optionalCourses.length) }}</div>
            <div class="stat-label">总课程数</div>
          </div>
        </div>

        <el-tabs v-model="courseTabActive">
          <!-- 必修课程 -->
          <el-tab-pane label="必修课程" name="required">
            <div class="course-section">
              <div class="section-header">
                <h4>必修课程列表</h4>
                <el-button type="primary" size="small" @click="addRequiredCourse">
                  <el-icon><Plus /></el-icon>
                  添加必修课程
                </el-button>
              </div>
              <el-table :data="requiredCourses" style="width: 100%" max-height="300">
                <el-table-column prop="name" label="课程名称" min-width="200" />
                <el-table-column prop="category" label="分类" width="120">
                  <template #default="scope">
                    <el-tag size="small">{{ scope.row.category }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="duration" label="学时" width="80" />
                <el-table-column prop="priority" label="优先级" width="100">
                  <template #default="scope">
                    <el-tag :type="getPriorityTagType(scope.row.priority)" size="small">
                      {{ getPriorityText(scope.row.priority) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button link type="danger" size="small" @click="removeRequiredCourse(scope.row)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="requiredCourses.length === 0" description="该岗位暂无必修课程" :image-size="80" />
            </div>
          </el-tab-pane>

          <!-- 选修课程 -->
          <el-tab-pane label="选修课程" name="optional">
            <div class="course-section">
              <div class="section-header">
                <h4>选修课程列表</h4>
                <el-button type="primary" size="small" @click="addOptionalCourse">
                  <el-icon><Plus /></el-icon>
                  添加选修课程
                </el-button>
              </div>
              <el-table :data="optionalCourses" style="width: 100%" max-height="300">
                <el-table-column prop="name" label="课程名称" min-width="200" />
                <el-table-column prop="category" label="分类" width="120">
                  <template #default="scope">
                    <el-tag size="small">{{ scope.row.category }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="duration" label="学时" width="80" />
                <el-table-column prop="recommendLevel" label="推荐级别" width="120">
                  <template #default="scope">
                    <el-rate v-model="scope.row.recommendLevel" disabled show-score size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button link type="danger" size="small" @click="removeOptionalCourse(scope.row)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="optionalCourses.length === 0" description="该岗位暂无选修课程" :image-size="80" />
            </div>
          </el-tab-pane>

          <!-- 所有可用课程 -->
          <el-tab-pane label="所有课程" name="all">
            <div class="course-section">
              <div class="section-header">
                <h4>可用课程列表</h4>
                <el-input 
                  v-model="courseSearchText" 
                  placeholder="搜索课程名称"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              <el-table :data="filteredAllCourses" style="width: 100%" max-height="300">
                <el-table-column prop="name" label="课程名称" min-width="200" />
                <el-table-column prop="category" label="分类" width="120">
                  <template #default="scope">
                    <el-tag size="small">{{ scope.row.category }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="duration" label="学时" width="80" />
                <el-table-column prop="difficulty" label="难度" width="100">
                  <template #default="scope">
                    <el-tag :type="getDifficultyTagType(scope.row.difficulty)" size="small">
                      {{ getDifficultyText(scope.row.difficulty) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="当前状态" width="120">
                  <template #default="scope">
                    <el-tag v-if="isCourseRequired(scope.row.id)" type="danger" size="small">必修</el-tag>
                    <el-tag v-else-if="isCourseOptional(scope.row.id)" type="warning" size="small">选修</el-tag>
                    <span v-else class="text-muted">未分配</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button 
                      v-if="!isCourseRequired(scope.row.id)"
                      link 
                      type="danger" 
                      size="small" 
                      @click="assignCourse(scope.row, 'required')"
                    >
                      设为必修
                    </el-button>
                    <el-button 
                      v-if="!isCourseOptional(scope.row.id)"
                      link 
                      type="warning" 
                      size="small" 
                      @click="assignCourse(scope.row, 'optional')"
                    >
                      设为选修
                    </el-button>
                    <el-button 
                      v-if="isCourseRequired(scope.row.id) || isCourseOptional(scope.row.id)"
                      link 
                      type="info" 
                      size="small" 
                      @click="unassignCourse(scope.row)"
                    >
                      取消分配
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="courseManagementVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveCourseAssignment">
            保存更改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getPositionList, getPositionTree, createPosition as createPositionApi, updatePosition, deletePosition as deletePositionApi, checkPositionDeletable } from '@/api/admin/position'
import request from '@/api/request'

// 搜索文本
const searchText = ref('')

// 弹窗相关
const positionDialogVisible = ref(false)
const membersDialogVisible = ref(false)
const courseManagementVisible = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const isEdit = ref(false)
const currentPosition = ref<any>(null)

// 加载状态
const loading = ref(false)

// 全部岗位树
const allPositionTree = ref<any[]>([])

// 课程管理相关
const courseTabActive = ref('required')
const courseSearchText = ref('')
const requiredCourses = ref<any[]>([])
const optionalCourses = ref<any[]>([])
const allCourses = ref<any[]>([])

// 岗位表单
const positionForm = reactive({
  id: '',
  name: '',
  description: '',
  parentId: null as number | null,
  skills: [],
  level: 'junior',
  status: 'active'
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入岗位描述', trigger: 'blur' },
    { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
  ],
  skills: [
    { required: true, message: '请选择核心技能', trigger: 'change', type: 'array' }
  ],
  level: [
    { required: true, message: '请选择岗位等级', trigger: 'change' }
  ]
})

// 岗位列表数据
const positionList = ref<any[]>([])

// 搜索后的岗位列表
const filteredPositionList = computed(() => {
  if (!positionList.value || !Array.isArray(positionList.value)) {
    return []
  }
  if (!searchText.value.trim()) {
    return positionList.value
  }
  const keyword = searchText.value.toLowerCase()
  return positionList.value.filter(position => 
    position.name?.toLowerCase().includes(keyword) ||
    position.description?.toLowerCase().includes(keyword) ||
    position.code?.toLowerCase().includes(keyword)
  )
})

// 成员列表数据
const membersList = ref([])

/**
 * 搜索处理
 */
const handleSearch = () => {
  // 通过 computed 属性已经实现了响应式搜索
}

/**
 * 新增岗位
 */
const createPosition = () => {
  isEdit.value = false
  resetForm()
  positionDialogVisible.value = true
}

/**
 * 编辑岗位
 */
const editPosition = (position: any) => {
  isEdit.value = true
  // 使用深拷贝创建编辑副本
  const positionCopy = JSON.parse(JSON.stringify(position))
  Object.assign(positionForm, {
    id: positionCopy.id,
    name: positionCopy.name,
    description: positionCopy.description,
    parentId: positionCopy.parent_id || positionCopy.parentId || null,
    skills: positionCopy.skills || [],
    level: positionCopy.level || 'junior',
    status: positionCopy.status
  })
  // 保存原始数据，用于取消操作时恢复
  currentPosition.value = positionCopy
  positionDialogVisible.value = true
}

/**
 * 重置表单
 */
const resetForm = () => {
  positionForm.id = ''
  positionForm.name = ''
  positionForm.description = ''
  positionForm.parentId = null
  positionForm.skills = []
  positionForm.level = 'junior'
  positionForm.status = 'active'
  formRef.value?.resetFields()
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        if (isEdit.value) {
          // 编辑岗位
          const response = await updatePosition(Number(positionForm.id), {
            name: positionForm.name,
            code: positionForm.name, // 可以根据需要生成 code
            parentId: positionForm.parentId ? Number(positionForm.parentId) : null,
            description: positionForm.description,
            status: positionForm.status as 'active' | 'inactive',
            skills: positionForm.skills,
            level: positionForm.level
          })
          if (response.code === 200) {
            ElMessage.success('岗位编辑成功')
            positionDialogVisible.value = false
            loadPositionList()
          }
        } else {
          // 新增岗位
          const response = await createPositionApi({
            name: positionForm.name,
            code: positionForm.name, // 可以根据需要生成 code
            parentId: positionForm.parentId ? Number(positionForm.parentId) : null,
            description: positionForm.description,
            status: positionForm.status as 'active' | 'inactive',
            skills: positionForm.skills,
            level: positionForm.level
          })
          if (response.code === 200) {
            ElMessage.success('岗位创建成功')
            positionDialogVisible.value = false
            loadPositionList()
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(isEdit.value ? '岗位编辑失败' : '岗位创建失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/**
 * 查看成员
 */
const viewMembers = async (position: any) => {
  currentPosition.value = position
  membersDialogVisible.value = true
  
  // 加载岗位成员数据
  try {
    const response = await request.get(`/api/v1/admin/positions/${position.id}/members`)
    if (response && response.code === 200) {
      membersList.value = (response.data && (response.data as any).items) || []
    } else {
      membersList.value = []
    }
  } catch (error) {
    ElMessage.error('加载成员列表失败')
  }
}

/**
 * 管理课程
 */
const manageCourses = (position: any) => {
  currentPosition.value = position
  courseTabActive.value = 'required'
  courseSearchText.value = ''
  
  // 加载课程数据
  loadPositionCourses(position.id)
  loadAllCourses()
  
  courseManagementVisible.value = true
}

/**
 * 切换状态
 */
const toggleStatus = (position: any) => {
  const action = position.status === 'active' ? '停用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}岗位"${position.name}"吗？`,
    `${action}岗位`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 持久化更新状态
    const newStatus = position.status === 'active' ? 'inactive' : 'active'
    updatePosition(Number(position.id), {
      name: position.name,
      code: position.code || position.name,
      parentId: position.parent_id || position.parentId || null,
      description: position.description,
      status: newStatus,
      skills: position.skills || [],
      level: position.level || 'junior'
    }).then((resp: any) => {
      if (resp && resp.code === 200) {
        position.status = newStatus
        ElMessage.success(`岗位已${action}`)
      } else {
        ElMessage.error('状态更新失败')
      }
    }).catch(() => {
      ElMessage.error('状态更新失败')
    })
  }).catch(() => {})
}

/**
 * 删除岗位
 */
const deletePosition = async (position: any) => {
  try {
    // 先检查是否可删除
    const checkResponse = await checkPositionDeletable(position.id)
    if (checkResponse.code === 200 && !checkResponse.data.deletable) {
      ElMessage.warning(checkResponse.data.reason || '该岗位无法删除')
      return
    }
    
    await ElMessageBox.confirm(
      `确定要删除岗位"${position.name}"吗？删除后不可恢复。`,
      '删除岗位',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deletePositionApi(position.id)
    if (response.code === 200) {
      ElMessage.success('岗位已删除')
      loadPositionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除岗位失败:', error)
      ElMessage.error('删除岗位失败')
    }
  }
}

/**
 * 获取进度颜色
 */
const getProgressColor = (percentage: number) => {
  if (percentage >= 80) return '#67c23a'
  if (percentage >= 60) return '#409eff'
  if (percentage >= 40) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 获取角色标签
 */
const getRoleLabel = (role: string) => {
  const roleMap: any = {
    admin: '管理员',
    manager: '经理',
    trainee: '学员',
    trainer: '培训师'
  }
  return roleMap[role] || role
}

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

/**
 * 移除成员
 */
const removeMember = async (member: any) => {
  if (!currentPosition.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要将 ${member.full_name || member.username} 从该岗位移除吗？`,
      '移除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(
      `/api/v1/admin/positions/${currentPosition.value.id}/members/${member.user_id}`
    )
    
    if (response && response.code === 200) {
      await viewMembers(currentPosition.value)
      ElMessage.success('成员已移除')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除成员失败:', error)
      ElMessage.error('移除成员失败')
    }
  }
}

/**
 * 获取可用的父级岗位列表
 * 排除当前岗位及其所有子岗位，防止循环依赖
 */
const getAvailableParentPositions = () => {
  if (!isEdit.value) {
    // 新增时，所有岗位都可作为父级
    return positionList.value
  }
  
  // 编辑时，需要排除自己及子岗位
  const currentId = positionForm.id
  const excludeIds = new Set([currentId])
  
  // 递归查找所有子岗位
  const findChildrenIds = (parentId: number | string) => {
    positionList.value.forEach(pos => {
      if (pos.parent_id == parentId || pos.parentId == parentId) {
        excludeIds.add(pos.id)
        findChildrenIds(pos.id)
      }
    })
  }
  
  findChildrenIds(currentId)
  
  // 返回可用的岗位列表
  return positionList.value.filter(pos => !excludeIds.has(pos.id))
}

/**
 * 加载岗位列表
 */
const loadPositionList = async () => {
  try {
    loading.value = true
    // 获取所有岗位数据（设置较大的page_size以一次性获取全部）
    const response = await getPositionList({ page: 1, pageSize: 100 })
    if (response && response.code === 200) {
      // 使用真实接口数据；标准结构为 data.items
      const items = (response.data as any)?.items || (response.data as any) || []
      // 兼容字段映射与默认值，确保页面可显示
      positionList.value = items.map((p: any) => ({
        ...p,
        memberCount: p.memberCount ?? 0,
        requiredCourses: p.requiredCourses ?? 0,
        optionalCourses: p.optionalCourses ?? 0,
        createTime: p.createTime || p.created_at || p.createdAt || '',
        updateTime: p.updateTime || p.updated_at || p.updatedAt || ''
      }))
    } else {
      // 如果 API 调用失败，使用默认数据
      positionList.value = []
      console.warn('使用默认数据')
    }
  } catch (error) {
    console.error('加载岗位列表失败:', error)
    // 失败时使用空数组
    positionList.value = []
    ElMessage.error('加载岗位列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 加载岗位树
 */
const loadPositionTree = async () => {
  try {
    const response = await getPositionTree()
    if (response && response.code === 200) {
      allPositionTree.value = response.data || []
    } else {
      allPositionTree.value = []
    }
  } catch (error) {
    console.error('加载岗位树失败:', error)
    allPositionTree.value = []
  }
}

/**
 * 加载岗位课程
 */
const loadPositionCourses = async (positionId: number) => {
  try {
    // 加载岗位的必修和选修课程
    const response = await request.get(`/api/v1/admin/positions/${positionId}/courses`)
    if (response && response.code === 200) {
      const courses = (response.data as any)?.items || []
      requiredCourses.value = courses.filter((c: any) => c.course_type === 'required')
      optionalCourses.value = courses.filter((c: any) => c.course_type === 'optional')
      
      // 转换数据格式以适配前端
      requiredCourses.value = requiredCourses.value.map((c: any) => ({
        id: c.course_id,
        name: c.course_name,
        category: c.course_category,
        duration: c.course_duration_hours,
        priority: c.priority > 5 ? 'high' : c.priority > 2 ? 'medium' : 'low'
      }))
      
      optionalCourses.value = optionalCourses.value.map((c: any) => ({
        id: c.course_id,
        name: c.course_name,
        category: c.course_category,
        duration: c.course_duration_hours,
        recommendLevel: c.priority || 3
      }))
    }
  } catch (error) {
    console.error('加载岗位课程失败:', error)
    ElMessage.error('加载课程失败')
  }
}

/**
 * 加载所有课程
 */
const loadAllCourses = async () => {
  try {
    // 加载所有可用课程
  const response = await request.get('/api/v1/courses', {
      page: 1,
      size: 100,
      status: 'published'
    })
    if (response && response.code === 200) {
      const items = (response.data as any)?.items || []
      allCourses.value = items.map((course: any) => ({
        id: course.id,
        name: course.name,
        category: course.category,
        duration: course.duration_hours || 0,
        difficulty: course.difficulty_level === 1 ? 'easy' : course.difficulty_level === 3 ? 'hard' : 'medium'
      }))
    }
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  }
}

// 筛选后的课程列表
const filteredAllCourses = computed(() => {
  if (!courseSearchText.value.trim()) {
    return allCourses.value
  }
  const keyword = courseSearchText.value.toLowerCase()
  return allCourses.value.filter(course => 
    course.name.toLowerCase().includes(keyword) ||
    course.category.toLowerCase().includes(keyword)
  )
})

/**
 * 检查课程是否为必修
 */
const isCourseRequired = (courseId: number) => {
  return requiredCourses.value.some(course => course.id === courseId)
}

/**
 * 检查课程是否为选修
 */
const isCourseOptional = (courseId: number) => {
  return optionalCourses.value.some(course => course.id === courseId)
}

/**
 * 分配课程
 */
const assignCourse = async (course: any, type: 'required' | 'optional') => {
  if (!currentPosition.value) return
  
  try {
    const response = await request.post(`/api/v1/admin/positions/${currentPosition.value.id}/courses`, {
      course_ids: [course.id],
      course_type: type
    })
    
    if (response && response.code === 200) {
      // 重新加载岗位课程
      await loadPositionCourses(currentPosition.value.id)
      ElMessage.success(`已将「${course.name}」设为${type === 'required' ? '必修' : '选修'}课程`)
    }
  } catch (error) {
    console.error('分配课程失败:', error)
    ElMessage.error('分配课程失败')
  }
}

/**
 * 取消课程分配
 */
const unassignCourse = async (course: any) => {
  if (!currentPosition.value) return
  try {
    const response = await request.delete(`/api/v1/admin/positions/${currentPosition.value.id}/courses/${course.id}`)
    if (response && response.code === 200) {
      await loadPositionCourses(currentPosition.value.id)
      ElMessage.success(`已取消「${course.name}」的分配`)
    }
  } catch (error) {
    console.error('取消分配失败:', error)
    ElMessage.error('取消分配失败')
  }
}

/**
 * 添加必修课程
 */
const addRequiredCourse = () => {
  courseTabActive.value = 'all'
  ElMessage.info('请在“所有课程”标签中选择要添加的课程')
}

/**
 * 添加选修课程
 */
const addOptionalCourse = () => {
  courseTabActive.value = 'all'
  ElMessage.info('请在“所有课程”标签中选择要添加的课程')
}

/**
 * 移除必修课程
 */
const removeRequiredCourse = async (course: any) => {
  if (!currentPosition.value) return
  
  try {
    const response = await request.delete(`/api/v1/admin/positions/${currentPosition.value.id}/courses/${course.id}`)
    if (response && response.code === 200) {
      await loadPositionCourses(currentPosition.value.id)
      ElMessage.success(`已移除必修课程「${course.name}」`)
    }
  } catch (error) {
    console.error('移除课程失败:', error)
    ElMessage.error('移除课程失败')
  }
}

/**
 * 移除选修课程
 */
const removeOptionalCourse = async (course: any) => {
  if (!currentPosition.value) return
  
  try {
    const response = await request.delete(`/api/v1/admin/positions/${currentPosition.value.id}/courses/${course.id}`)
    if (response && response.code === 200) {
      await loadPositionCourses(currentPosition.value.id)
      ElMessage.success(`已移除选修课程「${course.name}」`)
    }
  } catch (error) {
    console.error('移除课程失败:', error)
    ElMessage.error('移除课程失败')
  }
}

/**
 * 保存课程分配
 */
const saveCourseAssignment = async () => {
  try {
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新岗位的课程数量
    if (currentPosition.value) {
      const positionIndex = positionList.value.findIndex(p => p.id === currentPosition.value.id)
      if (positionIndex > -1) {
        positionList.value[positionIndex].requiredCourses = requiredCourses.value.length
        positionList.value[positionIndex].optionalCourses = optionalCourses.value.length
      }
    }
    
    ElMessage.success('课程分配保存成功')
    courseManagementVisible.value = false
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

/**
 * 获取优先级标签类型
 */
const getPriorityTagType = (priority: string) => {
  const tagMap: Record<string, string> = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return tagMap[priority] || ''
}

/**
 * 获取优先级文本
 */
const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return textMap[priority] || priority
}

/**
 * 获取难度标签类型
 */
const getDifficultyTagType = (difficulty: string) => {
  const tagMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return tagMap[difficulty] || ''
}

/**
 * 获取难度文本
 */
const getDifficultyText = (difficulty: string) => {
  const textMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return textMap[difficulty] || difficulty
}

// 组件挂载时加载数据
onMounted(() => {
  loadPositionList()
  loadPositionTree()
})
</script>

<style lang="scss" scoped>
.position-management-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

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

    .el-button {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
  }

  .search-section {
    margin-bottom: 24px;
  }

  .position-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 24px;

    .position-card {
      padding: 24px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
      }

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

        .position-title {
          display: flex;
          align-items: center;
          gap: 12px;

          h3 {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
          }
        }
      }

      .card-content {
        .position-desc {
          font-size: 14px;
          color: #666;
          line-height: 1.6;
          margin-bottom: 16px;
        }

        .position-info {
          display: flex;
          gap: 24px;
          margin-bottom: 20px;

          .info-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            color: #909399;

            .el-icon {
              color: #c0c4cc;
            }
          }
        }

        .position-skills {
          margin-bottom: 20px;

          h4 {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-bottom: 10px;
          }

          .skill-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
          }
        }

        .position-stats {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16px;

          .stat-item {
            .stat-label {
              font-size: 13px;
              color: #666;
              margin-bottom: 8px;
            }

            .stat-value {
              font-size: 20px;
              font-weight: 600;
              color: #333;
            }
          }
        }
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .position-management-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .el-button {
        width: 100%;
      }
    }

    .position-list {
      grid-template-columns: 1fr;
    }

    .position-info {
      flex-direction: column;
      gap: 8px !important;
    }
  }
}

// 课程管理弹窗样式
.course-management-content {
  .course-stats {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
    
    .stat-item {
      flex: 1;
      text-align: center;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
      
      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #409eff;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
  }
  
  .course-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      h4 {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }
    }
    
    .text-muted {
      color: #909399;
    }
  }
}

</style>
