<template>
  <div class="team-management-container">
    <div class="page-header">
      <h1 class="page-title">团队成员管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchText"
          placeholder="搜索成员姓名、岗位"
          clearable
          style="width: 300px"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="inviteMember">
          <el-icon class="el-icon--left"><Plus /></el-icon>
          邀请成员
        </el-button>
      </div>
    </div>

    <!-- 团队统计卡片 -->
    <div class="team-stats">
      <div class="stat-card card" v-for="stat in teamStats" :key="stat.label">
        <div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
          <el-icon :size="24" :color="stat.color">
            <component :is="stat.icon" />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
    </div>

    <!-- 成员列表 -->
    <div class="member-list card">
      <div class="list-header">
        <h3 class="list-title">成员列表</h3>
        <div class="list-filters">
          <el-select v-model="filterForm.status" placeholder="状态" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="活跃" value="active" />
            <el-option label="学习中" value="learning" />
            <el-option label="休息" value="rest" />
          </el-select>
          <el-select v-model="filterForm.position" placeholder="岗位" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="销售专员" value="sales" />
            <el-option label="销售主管" value="manager" />
            <el-option label="销售助理" value="assistant" />
          </el-select>
        </div>
      </div>

      <el-table :data="filteredMemberList" style="width: 100%" v-loading="loading">
        <el-table-column label="成员信息" min-width="200">
          <template #default="scope">
            <div class="member-info">
              <el-avatar :size="40" :src="scope.row.avatar">
                {{ scope.row.name.charAt(0) }}
              </el-avatar>
              <div class="info-content">
                <div class="member-name">{{ scope.row.name }}</div>
                <div class="member-position">{{ scope.row.position }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学习进度" width="200">
          <template #default="scope">
            <div class="progress-info">
              <el-progress :percentage="scope.row.progress" :color="getProgressColor(scope.row.progress)" />
              <span class="progress-text">{{ scope.row.completedCourses }}/{{ scope.row.totalCourses }} 课程</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="avgScore" label="平均成绩" width="120">
          <template #default="scope">
            <span :style="{ color: getScoreColor(scope.row.avgScore) }">
              {{ scope.row.avgScore }}分
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="studyTime" label="学习时长" width="120">
          <template #default="scope">
            {{ scope.row.studyTime }}小时
          </template>
        </el-table-column>
        <el-table-column prop="lastActive" label="最近活跃" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="viewDetail(scope.row)">
              查看详情
            </el-button>
            <el-button link type="primary" size="small" @click="assignTask(scope.row)">
              分配任务
            </el-button>
            <el-dropdown trigger="click" style="margin-left: 12px">
              <el-button link size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="sendMessage(scope.row)">
                    <el-icon><ChatDotRound /></el-icon>
                    发送消息
                  </el-dropdown-item>
                  <el-dropdown-item @click="viewReport(scope.row)">
                    <el-icon><DataAnalysis /></el-icon>
                    学习报告
                  </el-dropdown-item>
                  <el-dropdown-item @click="adjustPosition(scope.row)">
                    <el-icon><User /></el-icon>
                    调整岗位
                  </el-dropdown-item>
                  <el-dropdown-item @click="removeMember(scope.row)" divided>
                    <el-icon><Delete /></el-icon>
                    移出团队
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 成员详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentMember?.name} - 学习详情`"
      width="80%"
      top="5vh"
    >
      <div v-if="currentMember" class="member-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">基本信息</h4>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="姓名">{{ currentMember.name }}</el-descriptions-item>
            <el-descriptions-item label="岗位">{{ currentMember.position }}</el-descriptions-item>
            <el-descriptions-item label="加入时间">{{ currentMember.joinTime }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentMember.email }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ currentMember.phone }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentMember.status)">
                {{ getStatusText(currentMember.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 学习情况 -->
        <div class="detail-section">
          <h4 class="section-title">学习情况</h4>
          <div class="learning-stats">
            <div class="stat-item">
              <div class="stat-label">总学习时长</div>
              <div class="stat-value">{{ currentMember.studyTime }}小时</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">完成课程</div>
              <div class="stat-value">{{ currentMember.completedCourses }}门</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">平均成绩</div>
              <div class="stat-value">{{ currentMember.avgScore }}分</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">考试通过率</div>
              <div class="stat-value">{{ currentMember.passRate }}%</div>
            </div>
          </div>
        </div>

        <!-- 最近学习记录 -->
        <div class="detail-section">
          <h4 class="section-title">最近学习记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="record in currentMember.recentRecords"
              :key="record.id"
              :timestamp="record.time"
              :type="record.type"
            >
              {{ record.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 发送消息弹窗 -->
    <el-dialog
      v-model="messageDialogVisible"
      title="发送消息"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="messageForm" label-width="100px">
        <el-form-item label="消息类型" prop="type">
          <el-radio-group v-model="messageForm.type">
            <el-radio label="notice">通知消息</el-radio>
            <el-radio label="task">任务提醒</el-radio>
            <el-radio label="reminder">学习提醒</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="messageForm.title" placeholder="请输入消息标题" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            placeholder="请输入消息内容"
            :rows="5"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="预设模板">
          <el-select placeholder="选择预设模板" @change="useTemplate">
            <el-option label="学习任务提醒" value="task1" />
            <el-option label="考试通知" value="exam" />
            <el-option label="课程更新通知" value="course" />
            <el-option label="表扬鼓励" value="praise" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="messageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSendMessage">发送</el-button>
      </template>
    </el-dialog>

    <!-- 学习报告弹窗 -->
    <el-dialog
      v-model="reportDialogVisible"
      :title="`${currentMember?.name} - 学习报告`"
      width="90%"
      top="5vh"
    >
      <div v-if="reportData" class="learning-report">
        <!-- 报告概览 -->
        <div class="report-overview">
          <div class="overview-item" v-for="item in reportData.overview" :key="item.label">
            <div class="item-icon" :style="{ backgroundColor: item.bgColor }">
              <el-icon :size="24" :color="item.color">
                <component :is="item.icon" />
              </el-icon>
            </div>
            <div class="item-content">
              <div class="item-value">{{ item.value }}</div>
              <div class="item-label">{{ item.label }}</div>
            </div>
          </div>
        </div>

        <!-- 学习进度图表 -->
        <div class="report-section">
          <h4 class="section-title">学习进度趋势</h4>
          <div class="chart-container" ref="progressTrendChartRef" style="height: 300px;"></div>
        </div>

        <!-- 能力评估 -->
        <div class="report-section">
          <h4 class="section-title">能力评估</h4>
          <div class="ability-assessment">
            <div class="ability-chart" ref="abilityChartRef" style="height: 300px;"></div>
            <div class="ability-list">
              <div class="ability-item" v-for="ability in reportData.abilities" :key="ability.name">
                <div class="ability-header">
                  <span class="ability-name">{{ ability.name }}</span>
                  <span class="ability-score">{{ ability.score }}分</span>
                </div>
                <el-progress :percentage="ability.score" :color="getScoreColor(ability.score)" />
                <div class="ability-desc">{{ ability.description }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 学习记录 -->
        <div class="report-section">
          <h4 class="section-title">详细学习记录</h4>
          <el-table :data="reportData.records" style="width: 100%">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="course" label="课程名称" min-width="200" />
            <el-table-column prop="duration" label="学习时长" width="100">
              <template #default="scope">
                {{ scope.row.duration }}分钟
              </template>
            </el-table-column>
            <el-table-column prop="score" label="成绩" width="100">
              <template #default="scope">
                <span v-if="scope.row.score" :style="{ color: getScoreColor(scope.row.score) }">
                  {{ scope.row.score }}分
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'completed' ? 'success' : ''">
                  {{ scope.row.status === 'completed' ? '已完成' : '学习中' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="reportDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportReport">
          <el-icon class="el-icon--left"><Download /></el-icon>
          导出报告
        </el-button>
      </template>
    </el-dialog>

    <!-- 调整岗位弹窗 -->
    <el-dialog
      v-model="positionDialogVisible"
      title="调整岗位"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="positionForm" label-width="100px">
        <el-form-item label="当前岗位">
          <el-input :value="currentMember?.position" disabled />
        </el-form-item>
        <el-form-item label="调整至" prop="newPosition">
          <el-select v-model="positionForm.newPosition" placeholder="请选择新岗位">
            <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="reason">
          <el-input
            v-model="positionForm.reason"
            type="textarea"
            placeholder="请输入岗位调整原因"
            :rows="4"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="positionForm.effectiveDate"
            type="date"
            placeholder="选择生效日期"
            :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="positionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdjustPosition">确认调整</el-button>
      </template>
    </el-dialog>

    <!-- 分配任务弹窗 -->
    <el-dialog
      v-model="taskDialogVisible"
      title="分配学习任务"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="taskForm" label-width="100px">
        <el-form-item label="选择课程" prop="courses">
          <el-checkbox-group v-model="taskForm.courses">
            <div class="course-group" v-for="category in groupedCourses" :key="category.name">
              <div class="category-title">{{ category.name }}</div>
              <div class="course-list">
                <el-checkbox 
                  v-for="course in category.courses" 
                  :key="course.id"
                  :label="course.id"
                  class="course-item"
                >
                  <div class="course-info">
                    <span class="course-name">{{ course.name }}</span>
                    <span class="course-duration">{{ course.duration }}</span>
                  </div>
                </el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="完成期限" prop="deadline">
          <el-date-picker
            v-model="taskForm.deadline"
            type="datetime"
            placeholder="选择完成期限"
            :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        
        <el-form-item label="任务说明" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            placeholder="请输入任务说明（选填）"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="学习要求">
          <div class="task-requirements">
            <el-checkbox label="必须完成所有课程学习">必须完成所有课程学习</el-checkbox>
            <el-checkbox label="需要通过课程考试">需要通过课程考试</el-checkbox>
            <el-checkbox label="完成后提交学习报告">完成后提交学习报告</el-checkbox>
          </div>
        </el-form-item>
      </el-form>
      
      <div class="task-summary">
        <div class="summary-item">
          <span class="label">已选课程：</span>
          <span class="value">{{ taskForm.courses.length }} 门</span>
        </div>
        <div class="summary-item">
          <span class="label">预计学习时长：</span>
          <span class="value">{{ calculateTotalDuration() }}</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAssignTask">确认分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { 
  getTeamStatistics, 
  getTeamMembers, 
  getMemberDetail, 
  getMemberReport,
  type TeamMember,
  type MemberListParams
} from '@/api/teamManagement'

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

// 筛选表单
const filterForm = reactive({
  status: '',
  position: ''
})

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

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(85)

// 详情弹窗
const detailDialogVisible = ref(false)
const currentMember = ref<any>(null)

// 发送消息弹窗
const messageDialogVisible = ref(false)
const messageForm = reactive({
  title: '',
  content: '',
  type: 'notice' // notice通知, task任务, reminder提醒
})

// 学习报告弹窗
const reportDialogVisible = ref(false)
const reportData = ref<any>(null)

// 图表引用
const progressTrendChartRef = ref()
const abilityChartRef = ref()
let progressTrendChart: any = null
let abilityChart: any = null

// 调整岗位弹窗
const positionDialogVisible = ref(false)
const positionForm = reactive({
  currentPosition: '',
  newPosition: '',
  reason: '',
  effectiveDate: null as Date | null
})

// 分配任务弹窗
const taskDialogVisible = ref(false)
const taskForm = reactive({
  courses: [] as string[],
  deadline: null as Date | null,
  description: ''
})

// 可选课程列表
const availableCourses = ref([
  { id: '1', name: '销售技巧基础', category: '基础课程', duration: '2小时' },
  { id: '2', name: '客户沟通技巧', category: '基础课程', duration: '1.5小时' },
  { id: '3', name: '产品知识详解', category: '产品培训', duration: '3小时' },
  { id: '4', name: '需求挖掘方法', category: '进阶课程', duration: '2小时' },
  { id: '5', name: '异议处理技巧', category: '进阶课程', duration: '2.5小时' },
  { id: '6', name: '成交技巧进阶', category: '进阶课程', duration: '2小时' },
  { id: '7', name: '大客户管理', category: '高级课程', duration: '4小时' },
  { id: '8', name: '团队协作与管理', category: '管理课程', duration: '3小时' }
])

// 团队统计数据
const teamStats = ref([
  {
    label: '团队总人数',
    value: '0',
    icon: 'User',
    color: '#667eea',
    bgColor: 'rgba(102, 126, 234, 0.1)'
  },
  {
    label: '活跃成员',
    value: '0',
    icon: 'CircleCheck',
    color: '#67c23a',
    bgColor: 'rgba(103, 194, 58, 0.1)'
  },
  {
    label: '平均学习进度',
    value: '0%',
    icon: 'TrendCharts',
    color: '#e6a23c',
    bgColor: 'rgba(230, 162, 60, 0.1)'
  },
  {
    label: '团队平均分',
    value: '0',
    icon: 'Trophy',
    color: '#f56c6c',
    bgColor: 'rgba(245, 108, 108, 0.1)'
  }
])

// 成员列表数据
const memberList = ref<TeamMember[]>([])

// 成员列表直接使用，筛选由后端处理
const filteredMemberList = computed(() => memberList.value)

/**
 * 加载团队统计数据
 */
const loadTeamStatistics = async () => {
  try {
    const res = await getTeamStatistics()
    if (res.code === 200 && res.data) {
      teamStats.value[0].value = String(res.data.teamCount)
      teamStats.value[1].value = String(res.data.activeMembers)
      teamStats.value[2].value = `${res.data.avgProgress}%`
      teamStats.value[3].value = String(res.data.avgScore)
    }
  } catch (error) {
    console.error('加载团队统计失败:', error)
    ElMessage.error('加载团队统计失败')
  }
}

/**
 * 加载团队成员列表
 */
const loadTeamMembers = async () => {
  try {
    loading.value = true
    const params: MemberListParams = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加搜索条件
    if (searchText.value) {
      params.search_text = searchText.value
    }
    
    // 添加筛选条件
    if (filterForm.status) {
      params.status = filterForm.status as 'active' | 'learning' | 'rest'
    }
    
    if (filterForm.position) {
      params.position = filterForm.position
    }
    
    const res = await getTeamMembers(params)
    if (res.code === 200 && res.data) {
      memberList.value = res.data.items
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载团队成员失败:', error)
    ElMessage.error('加载团队成员失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  currentPage.value = 1
  loadTeamMembers()
}

/**
 * 筛选处理
 */
const handleFilter = () => {
  currentPage.value = 1
  loadTeamMembers()
}

/**
 * 邀请成员
 */
const inviteMember = () => {
  ElMessage.info('邀请成员功能开发中')
}

/**
 * 查看详情
 */
const viewDetail = async (member: any) => {
  try {
    const res = await getMemberDetail(member.id)
    if (res.code === 200 && res.data) {
      currentMember.value = res.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取成员详情失败:', error)
    ElMessage.error('获取成员详情失败')
  }
}

/**
 * 分配任务
 */
const assignTask = (member: any) => {
  currentMember.value = member
  taskForm.courses = []
  taskForm.deadline = null
  taskForm.description = ''
  taskDialogVisible.value = true
}

/**
 * 分组后的课程列表
 */
const groupedCourses = computed(() => {
  const groups: Record<string, any[]> = {}
  availableCourses.value.forEach(course => {
    if (!groups[course.category]) {
      groups[course.category] = []
    }
    groups[course.category].push(course)
  })
  
  return Object.entries(groups).map(([name, courses]) => ({
    name,
    courses
  }))
})

/**
 * 计算总学习时长
 */
const calculateTotalDuration = () => {
  const selectedCourses = availableCourses.value.filter(course => 
    taskForm.courses.includes(course.id)
  )
  
  let totalMinutes = 0
  selectedCourses.forEach(course => {
    const duration = course.duration
    if (duration.includes('小时')) {
      totalMinutes += parseFloat(duration) * 60
    } else if (duration.includes('分钟')) {
      totalMinutes += parseFloat(duration)
    }
  })
  
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  
  if (hours > 0 && minutes > 0) {
    return `${hours}小时${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时`
  } else {
    return `${minutes}分钟`
  }
}

/**
 * 发送消息
 */
const sendMessage = (member: any) => {
  currentMember.value = member
  messageForm.title = ''
  messageForm.content = ''
  messageForm.type = 'notice'
  messageDialogVisible.value = true
}

/**
 * 查看报告
 */
const viewReport = async (member: any) => {
  try {
    currentMember.value = member
    const res = await getMemberReport(member.id)
    if (res.code === 200 && res.data) {
      reportData.value = res.data
      reportDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取学习报告失败:', error)
    ElMessage.error('获取学习报告失败')
  }
}

/**
 * 调整岗位
 */
const adjustPosition = (member: any) => {
  currentMember.value = member
  positionForm.currentPosition = member.position
  positionForm.newPosition = ''
  positionForm.reason = ''
  positionForm.effectiveDate = null
  positionDialogVisible.value = true
}

/**
 * 移出团队
 */
const removeMember = async (member: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要将 ${member.name} 移出团队吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    ElMessage.success('已移出团队')
  } catch {
    ElMessage.info('已取消操作')
  }
}

/**
 * 获取状态类型
 */
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'success',
    learning: '',
    rest: 'info'
  }
  return statusMap[status] || ''
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '活跃',
    learning: '学习中',
    rest: '休息'
  }
  return statusMap[status] || ''
}

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

/**
 * 获取分数颜色
 */
const getScoreColor = (score: number) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#409eff'
  if (score >= 60) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadTeamMembers()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadTeamMembers()
}

/**
 * 使用消息模板
 */
const useTemplate = (templateId: string) => {
  const templates: Record<string, { title: string; content: string }> = {
    task1: {
      title: '学习任务提醒',
      content: '您好！您有新的学习任务待完成，请及时登录系统查看并完成相关课程学习。'
    },
    exam: {
      title: '考试通知',
      content: '您好！您有一场考试即将开始，请提前做好准备。考试时间：明天上午9:00。'
    },
    course: {
      title: '课程更新通知',
      content: '您好！《销售技巧进阶》课程已更新，新增了实战案例分析模块，请及时学习。'
    },
    praise: {
      title: '表扬鼓励',
      content: '您好！恭喜您在本周的学习中表现优异，继续保持！您的努力是团队进步的动力。'
    }
  }
  
  const template = templates[templateId]
  if (template) {
    messageForm.title = template.title
    messageForm.content = template.content
  }
}

/**
 * 确认发送消息
 */
const confirmSendMessage = () => {
  if (!messageForm.title || !messageForm.content) {
    ElMessage.warning('请填写消息标题和内容')
    return
  }
  
  ElMessage.success(`消息已发送给 ${currentMember.value?.name}`)
  messageDialogVisible.value = false
}

/**
 * 导出报告
 */
const exportReport = () => {
  ElMessage.success('报告导出成功')
}

/**
 * 确认调整岗位
 */
const confirmAdjustPosition = () => {
  if (!positionForm.newPosition) {
    ElMessage.warning('请选择新岗位')
    return
  }
  
  if (!positionForm.reason) {
    ElMessage.warning('请填写调整原因')
    return
  }
  
  ElMessage.success(`已将 ${currentMember.value?.name} 的岗位调整为 ${positionForm.newPosition}`)
  positionDialogVisible.value = false
}

/**
 * 确认分配任务
 */
const confirmAssignTask = () => {
  if (taskForm.courses.length === 0) {
    ElMessage.warning('请至少选择一门课程')
    return
  }
  
  if (!taskForm.deadline) {
    ElMessage.warning('请设置完成期限')
    return
  }
  
  const courseNames = availableCourses.value
    .filter(course => taskForm.courses.includes(course.id))
    .map(course => course.name)
    .join('、')
  
  ElMessage.success(`已向 ${currentMember.value?.name} 分配了 ${taskForm.courses.length} 门课程：${courseNames}`)
  taskDialogVisible.value = false
}

/**
 * 初始化学习进度趋势图
 */
const initProgressTrendChart = () => {
  if (!progressTrendChartRef.value) return
  
  progressTrendChart = echarts.init(progressTrendChartRef.value)
  
  // 使用真实数据
  const dates = reportData.value?.progressTrend?.dates || []
  const progressData = reportData.value?.progressTrend?.data || []
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '进度(%)',
      max: 100
    },
    series: [
      {
        name: '学习进度',
        type: 'line',
        smooth: true,
        data: progressData,
        itemStyle: { color: '#667eea' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102, 126, 234, 0.3)' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
          ])
        }
      }
    ]
  }
  
  progressTrendChart.setOption(option)
}

/**
 * 初始化能力雷达图
 */
const initAbilityChart = () => {
  if (!abilityChartRef.value) return
  
  abilityChart = echarts.init(abilityChartRef.value)
  
  const option = {
    radar: {
      indicator: reportData.value.abilities.map((item: any) => ({
        name: item.name,
        max: 100
      })),
      center: ['50%', '50%'],
      radius: '65%'
    },
    series: [
      {
        name: '能力评估',
        type: 'radar',
        data: [
          {
            value: reportData.value.abilities.map((item: any) => item.score),
            name: '当前能力',
            itemStyle: {
              color: '#667eea'
            },
            areaStyle: {
              color: 'rgba(102, 126, 234, 0.2)'
            }
          }
        ]
      }
    ]
  }
  
  abilityChart.setOption(option)
}

// 监听报告弹窗打开
watch(reportDialogVisible, (newVal) => {
  if (newVal && reportData.value) {
    nextTick(() => {
      initProgressTrendChart()
      initAbilityChart()
    })
  } else {
    // 关闭时销毁图表
    if (progressTrendChart) {
      progressTrendChart.dispose()
      progressTrendChart = null
    }
    if (abilityChart) {
      abilityChart.dispose()
      abilityChart = null
    }
  }
})

// 页面加载时获取数据
onMounted(() => {
  loadTeamStatistics()
  loadTeamMembers()
})
</script>

<style lang="scss" scoped>
.team-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;
    }

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

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

  .team-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    .stat-card {
      display: flex;
      align-items: center;
      gap: 20px;
      padding: 24px;

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .stat-content {
        .stat-value {
          font-size: 28px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
        }

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

  .member-list {
    padding: 24px;

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

      .list-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }

      .list-filters {
        display: flex;
        gap: 12px;
      }
    }

    .member-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .info-content {
        .member-name {
          font-size: 15px;
          font-weight: 500;
          color: #333;
        }

        .member-position {
          font-size: 13px;
          color: #909399;
          margin-top: 2px;
        }
      }
    }

    .progress-info {
      .progress-text {
        font-size: 12px;
        color: #666;
        margin-top: 4px;
        display: block;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }

  .member-detail {
    .detail-section {
      margin-bottom: 32px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 1px solid #ebeef5;
      }

      .learning-stats {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 24px;

        .stat-item {
          text-align: center;
          padding: 20px;
          background: #f5f7fa;
          border-radius: 8px;

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

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

  // 学习报告样式
  .learning-report {
    .report-overview {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 32px;

      .overview-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 20px;
        background: #f5f7fa;
        border-radius: 8px;

        .item-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .item-content {
          .item-value {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }

          .item-label {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }

    .report-section {
      margin-bottom: 32px;

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 1px solid #ebeef5;
      }

      .ability-assessment {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 48px;

        .ability-list {
          .ability-item {
            margin-bottom: 24px;

            .ability-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 8px;

              .ability-name {
                font-size: 15px;
                font-weight: 500;
                color: #333;
              }

              .ability-score {
                font-size: 14px;
                color: #666;
              }
            }

            .ability-desc {
              font-size: 13px;
              color: #999;
              margin-top: 8px;
            }
          }
        }
      }
    }
  }

  // 分配任务弹窗样式
  .course-group {
    margin-bottom: 20px;

    .category-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
      margin-bottom: 12px;
      padding-left: 4px;
    }

    .course-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;

      .course-item {
        display: block;
        margin-right: 0;

        .course-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;

          .course-name {
            font-size: 14px;
            color: #333;
          }

          .course-duration {
            font-size: 12px;
            color: #999;
            margin-left: 12px;
          }
        }
      }
    }
  }

  .task-requirements {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .el-checkbox {
      margin-right: 0;
    }
  }

  .task-summary {
    display: flex;
    gap: 32px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
    margin-top: 20px;

    .summary-item {
      .label {
        font-size: 14px;
        color: #666;
      }

      .value {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-left: 8px;
      }
    }
  }
}

// 响应式
@media (max-width: 1024px) {
  .team-management-container {
    .learning-stats {
      grid-template-columns: repeat(2, 1fr) !important;
    }

    .report-overview {
      grid-template-columns: repeat(2, 1fr) !important;
    }

    .ability-assessment {
      grid-template-columns: 1fr !important;
    }
  }
}

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

      .header-actions {
        width: 100%;
        flex-direction: column;

        > * {
          width: 100%;
        }
      }
    }

    .team-stats {
      grid-template-columns: 1fr;
    }

    .list-header {
      flex-direction: column;
      align-items: flex-start !important;
      gap: 16px;

      .list-filters {
        width: 100%;
        
        .el-select {
          flex: 1;
        }
      }
    }

    .report-overview {
      grid-template-columns: 1fr !important;
    }
  }
}
</style>
