<template>
  <div class="teacher-detail">
    <div class="page-header">
      <h1>教师详情</h1>
      <div class="header-actions">
        <el-button @click="$router.push('/admin/teachers')">返回列表</el-button>
        <el-button type="primary" @click="$router.push(`/admin/teachers/${id}/edit`)">编辑</el-button>
      </div>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="info-card" v-loading="loading">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <div class="teacher-avatar">
            <el-avatar :size="100" :src="teacher.avatar" />
          </div>
          
          <div class="info-list">
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ teacher.name }}</span>
            </div>
            <div class="info-item">
              <span class="label">性别：</span>
              <span class="value">{{ teacher.gender === 'male' ? '男' : teacher.gender === 'female' ? '女' : '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ teacher.phone }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ teacher.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">所属部门：</span>
              <span class="value">{{ teacher.department }}</span>
            </div>
            <div class="info-item">
              <span class="label">职称：</span>
              <span class="value">{{ teacher.title }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态：</span>
              <span class="value">
                <el-tag :type="teacher.status === 'active' ? 'success' : 'danger'">
                  {{ teacher.status === 'active' ? '在职' : '离职' }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="label">入职时间：</span>
              <span class="value">{{ teacher.joinDate }}</span>
            </div>
          </div>
          
          <div class="teacher-bio" v-if="teacher.bio">
            <h3>教师简介</h3>
            <p>{{ teacher.bio }}</p>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card class="course-card">
          <template #header>
            <div class="card-header">
              <span>授课列表</span>
              <el-button type="primary" size="small" @click="showAssignCourseDialog">分配课程</el-button>
            </div>
          </template>
          
          <el-table
            v-loading="coursesLoading"
            :data="teacherCourses"
            border
            style="width: 100%"
          >
            <el-table-column type="index" width="50" />
            <el-table-column prop="title" label="课程名称" min-width="200" />
            <el-table-column prop="categoryName" label="分类" width="120" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="{ row }">
                {{ row.price > 0 ? `¥${row.price}` : '免费' }}
              </template>
            </el-table-column>
            <el-table-column prop="studentCount" label="学生数" width="100" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="danger" link @click="removeCourse(row.id)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="courseQueryParams.page"
              v-model:page-size="courseQueryParams.limit"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="courseTotal"
              @size-change="handleCourseSizeChange"
              @current-change="handleCourseCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 分配课程对话框 -->
    <el-dialog
      v-model="assignCourseDialogVisible"
      title="分配课程"
      width="700px"
    >
      <el-form :inline="true" :model="courseSearchForm" class="search-form">
        <el-form-item label="课程名称">
          <el-input v-model="courseSearchForm.keyword" placeholder="请输入课程名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCourses">搜索</el-button>
        </el-form-item>
      </el-form>
      
      <el-table
        v-loading="allCoursesLoading"
        :data="availableCourses"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="课程名称" min-width="200" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            {{ row.price > 0 ? `¥${row.price}` : '免费' }}
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignCourseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignCourses" :loading="assigningCourses">
            确认分配
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTeacherDetail, getTeacherCourses, assignCourses } from '../../../api/teacher'
import { getCourses } from '../../../api/course'

const route = useRoute()
const router = useRouter()
const id = route.params.id

const teacher = ref({})
const loading = ref(false)
const coursesLoading = ref(false)
const teacherCourses = ref([])
const courseTotal = ref(0)

const courseQueryParams = ref({
  page: 1,
  limit: 10
})

// 分配课程相关
const assignCourseDialogVisible = ref(false)
const allCoursesLoading = ref(false)
const availableCourses = ref([])
const selectedCourses = ref([])
const assigningCourses = ref(false)
const courseSearchForm = ref({
  keyword: ''
})

const fetchTeacherDetail = async () => {
  loading.value = true
  try {
    const res = await getTeacherDetail(id)
    teacher.value = res.data
  } catch (error) {
    console.error('获取教师详情失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchTeacherCourses = async () => {
  coursesLoading.value = true
  try {
    const res = await getTeacherCourses(id, courseQueryParams.value)
    teacherCourses.value = res.data.list
    courseTotal.value = res.data.total
  } catch (error) {
    console.error('获取教师课程失败:', error)
  } finally {
    coursesLoading.value = false
  }
}

const handleCourseSizeChange = (val) => {
  courseQueryParams.value.limit = val
  fetchTeacherCourses()
}

const handleCourseCurrentChange = (val) => {
  courseQueryParams.value.page = val
  fetchTeacherCourses()
}

const removeCourse = async (courseId) => {
  try {
    await ElMessageBox.confirm('确定要移除该课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里假设移除课程的 API 是通过分配空数组实现的
    await assignCourses(id, teacherCourses.value
      .filter(course => course.id !== courseId)
      .map(course => course.id))
    
    ElMessage.success('课程移除成功')
    fetchTeacherCourses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除课程失败:', error)
    }
  }
}

const showAssignCourseDialog = () => {
  assignCourseDialogVisible.value = true
  searchCourses()
}

const searchCourses = async () => {
  allCoursesLoading.value = true
  try {
    const res = await getCourses({
      keyword: courseSearchForm.value.keyword,
      page: 1,
      limit: 100
    })
    
    // 过滤掉已经分配的课程
    const assignedCourseIds = teacherCourses.value.map(course => course.id)
    availableCourses.value = res.data.list.filter(course => !assignedCourseIds.includes(course.id))
  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    allCoursesLoading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedCourses.value = selection
}

const confirmAssignCourses = async () => {
  if (selectedCourses.value.length === 0) {
    ElMessage.warning('请选择要分配的课程')
    return
  }
  
  assigningCourses.value = true
  try {
    // 获取当前已分配的课程ID
    const currentCourseIds = teacherCourses.value.map(course => course.id)
    // 获取新选择的课程ID
    const newCourseIds = selectedCourses.value.map(course => course.id)
    // 合并课程ID
    const allCourseIds = [...new Set([...currentCourseIds, ...newCourseIds])]
    
    await assignCourses(id, allCourseIds)
    ElMessage.success('课程分配成功')
    assignCourseDialogVisible.value = false
    fetchTeacherCourses()
  } catch (error) {
    console.error('分配课程失败:', error)
  } finally {
    assigningCourses.value = false
  }
}

onMounted(() => {
  fetchTeacherDetail()
  fetchTeacherCourses()
})
</script>

<style lang="scss" scoped>
.teacher-detail {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      margin: 0;
      font-size: 24px;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .info-card, .course-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .teacher-avatar {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .info-list {
    .info-item {
      margin-bottom: 10px;
      display: flex;
      
      .label {
        width: 100px;
        color: #606266;
      }
      
      .value {
        flex: 1;
      }
    }
  }
  
  .teacher-bio {
    margin-top: 20px;
    
    h3 {
      font-size: 16px;
      margin-bottom: 10px;
    }
    
    p {
      color: #606266;
      line-height: 1.6;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
}
</style> 