<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable>
          <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1"/>
          <el-option label="禁用" :value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['courses:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['courses:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['courses:student:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="学号" align="center" prop="studentNo" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="姓名" align="center" prop="name" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="年级" align="center" prop="grade" width="80">
        <template slot-scope="scope">
          <el-tag size="small">{{ formatGrade(scope.row.grade) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center" prop="classId" width="120">
        <template slot-scope="scope">
          {{ getClassName(scope.row.classId) }}
        </template>
      </el-table-column>
      <el-table-column label="已选选修课" align="center" min-width="250">
        <template slot-scope="scope">
      <span v-if="scope.row.selectedElectiveIds" class="text-gray">
        {{ formatCourseNames(scope.row.selectedElectiveIds) }}
      </span>
          <span v-else class="text-gray">无选修课</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:student:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%" @change="handleGradeChange">
                <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select
                v-model="form.classId"
                placeholder="请选择班级"
                style="width: 100%"
                :disabled="!form.grade"
                :loading="classLoading"
              >
                <el-option
                  v-for="cls in filteredClasses"
                  :key="cls.id"
                  :label="cls.className"
                  :value="cls.id"
                />
                <div v-if="!filteredClasses.length && form.grade && !classLoading" class="empty-classes">
                  <el-empty description="暂无该年级的班级数据" :image-size="60"/>
                </div>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="选修课" prop="selectedElectiveIds">
          <el-select
            v-model="form.selectedElectiveIds"
            placeholder="请选择3-4门选修课"
            style="width: 100%"
            multiple
            clearable
            :multiple-limit="4"
            :disabled="!electiveCourses.length || !form.grade"
            :loading="courseLoading"
          >
            <el-option
              v-for="course in filteredElectiveCourses"
              :key="course.id"
              :label="course.courseName"
              :value="course.id"
            >
              <span style="float: left">{{ course.courseName }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">
        {{ course.subject }} | {{ course.gradeLevel }}
      </span>
            </el-option>
            <div v-if="!filteredElectiveCourses.length && form.grade && !courseLoading" class="empty-courses">
              <el-empty description="暂无选修课数据" :image-size="60"/>
            </div>
          </el-select>
          <div class="select-tips">
            已选择 {{ form.selectedElectiveIds ? form.selectedElectiveIds.length : 0 }} 门课程（建议选择3-4门）
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent, exportStudent } from "@/api/course/student"
import { listClazz } from "@/api/course/clazz"
import { listCourse } from "@/api/course/courses"

export default {
  name: "Student",
  data() {
    // 验证选修课数量的自定义规则
    const validateElectiveCourses = (rule, value, callback) => {
      if (!value || value.length === 0) {
        // 允许不选选修课
        callback()
        return
      }

      if (value.length < 3) {
        callback(new Error('至少选择3门选修课'))
      } else if (value.length > 4) {
        callback(new Error('最多选择4门选修课'))
      } else {
        callback()
      }
    }

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 年级选项
      gradeOptions: ['高一', '高二', '高三'],
      // 班级列表
      classList: [],
      classLoading: false,
      // 选修课列表
      electiveCourses: [],
      courseLoading: false,
      // 所有课程列表（用于显示课程名称）
      allCourses: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentNo: null,
        name: null,
        grade: null,
        status: null
      },
      // 表单参数
      form: {
        selectedElectiveIds: []
      },
      // 表单校验
      rules: {
        studentNo: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "change" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "change" }
        ],
        selectedElectiveIds: [
          { validator: validateElectiveCourses, trigger: "change" }
        ]
      }
    }
  },
  computed: {
    // 计算属性：根据年级过滤班级
    filteredClasses() {
      if (!this.form.grade || !Array.isArray(this.classList)) return []
      return this.classList.filter(cls => cls.grade === this.form.grade)
    },
    // 计算属性：根据年级过滤选修课
    filteredElectiveCourses() {
      if (!Array.isArray(this.electiveCourses)) return []
      if (!this.form.grade) return this.electiveCourses

      // 返回当前年级的选修课和"全部"年级的选修课
      return this.electiveCourses.filter(course =>
        course.gradeLevel === this.form.grade || course.gradeLevel === '全部'
      )
    }
  },
  created() {
    this.getList()
    this.getClassList()
    this.getCourseList()
  },
  methods: {

    /** 格式化年级显示 */
    formatGrade(grade) {
      const gradeMap = {
        'FRESHMAN': '高一',
        'SOPHOMORE': '高二',
        'JUNIOR': '高三'
      }
      return gradeMap[grade] || grade
    },

    /** 根据班级ID获取班级名称 */
    getClassName(classId) {
      if (!this.classList.length) return `班级${classId}`
      const cls = this.classList.find(c => c.id === classId)
      return cls ? cls.className : `班级${classId}`
    },

    /** 格式化选修课名称显示 */
    formatCourseNames(ids) {
      if (!ids || !this.allCourses.length) return '无选修课'

      // 如果 ids 是字符串，尝试解析
      let idArray = []
      try {
        if (typeof ids === 'string') {
          idArray = JSON.parse(ids)
        } else if (Array.isArray(ids)) {
          idArray = ids
        }
      } catch (e) {
        console.error('解析选修课ID失败:', e)
        return '选修课数据异常'
      }

      if (!idArray.length) return '无选修课'

      const names = idArray.map(id => {
        const course = this.allCourses.find(c => c.id === id)
        return course ? course.courseName : `课程${id}`
      })

      return names.join('、')
    },
    /** 查询学生列表 */
    getList() {
      this.loading = true
      console.log('发送查询请求，参数:', this.queryParams)

      listStudent(this.queryParams).then(response => {
        console.log('学生列表API返回:', response)  // 查看完整响应

        if (response.code === 200 || response.success) {
          // 根据实际响应结构调整
          // 数据在 response.data 中（这是一个数组）
          this.studentList = response.rows

          // 注意：响应中没有 total 字段，需要处理分页
          // 如果没有分页信息，可以设置为数组长度
          this.total = this.studentList.length

          console.log('设置的学生数据:', this.studentList)
          console.log('总数:', this.total)
        } else {
          this.$modal.msgError(response.msg || "获取学生列表失败")
          this.studentList = []
          this.total = 0
        }
        this.loading = false
      }).catch(error => {
        console.error('获取学生列表失败:', error)
        this.$modal.msgError("获取学生列表失败")
        this.loading = false
        this.studentList = []
        this.total = 0
      })
    },

    /** 获取班级列表 */
    getClassList() {
      this.classLoading = true
      listClazz().then(response => {
        if (response.code === 200) {
          // 根据实际API返回结构调整
          // 可能是 response.data 或 response.rows
          this.classList = response.data || response.rows || []
        } else {
          this.$modal.msgError(response.msg || "获取班级列表失败")
          this.classList = []
        }
        this.classLoading = false

        if (this.classList.length === 0) {
          this.$modal.msgWarning("暂无班级数据，请先在班级管理中配置班级")
        }
      }).catch(error => {
        console.error('获取班级列表失败:', error)
        this.classList = []
        this.classLoading = false
        this.$modal.msgWarning("获取班级列表失败，请联系管理员配置班级数据")
      })
    },

    /** 获取课程列表 */
    getCourseList() {
      this.courseLoading = true
      listCourse().then(response => {
        if (response.code === 200) {
          // 根据实际API返回结构调整
          // 可能是 response.data 或 response.rows
          this.allCourses = response.data || response.rows || []
          // 过滤出选修课
          this.electiveCourses = this.allCourses.filter(course =>
            course.courseType === '选修'
          ) || []
        } else {
          this.$modal.msgError(response.msg || "获取课程列表失败")
          this.allCourses = []
          this.electiveCourses = []
        }
        this.courseLoading = false

        if (this.electiveCourses.length === 0) {
          this.$modal.msgWarning("暂无选修课数据，请先在课程管理中配置选修课")
        }
      }).catch(error => {
        console.error('获取课程列表失败:', error)
        this.allCourses = []
        this.electiveCourses = []
        this.courseLoading = false
        this.$modal.msgWarning("获取课程列表失败，请联系管理员配置课程数据")
      })
    },

    // 年级变化时重置班级选择
    handleGradeChange() {
      this.form.classId = null
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentNo: null,
        name: null,
        grade: null,
        classId: null,
        selectedElectiveIds: [],
        status: 1,
        remark: null
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields()
      }
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加学生"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getStudent(id).then(response => {
        if (response.code === 200) {
          const data = response.data || {}

          // 解析选修课ID数组
          let electiveIds = []
          try {
            if (data.selectedElectiveIds) {
              if (typeof data.selectedElectiveIds === 'string') {
                electiveIds = JSON.parse(data.selectedElectiveIds)
              } else if (Array.isArray(data.selectedElectiveIds)) {
                electiveIds = data.selectedElectiveIds
              }
            }
          } catch (e) {
            console.error('解析选修课ID失败:', e)
          }

          this.form = {
            ...data,
            selectedElectiveIds: electiveIds
          }

          this.open = true
          this.title = "修改学生"
        } else {
          this.$modal.msgError(response.msg || "获取学生信息失败")
        }
      }).catch(error => {
        console.error('获取学生信息失败:', error)
        this.$modal.msgError("获取学生信息失败")
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 准备提交的数据
          const submitData = {
            ...this.form,
            selectedElectiveIds: JSON.stringify(this.form.selectedElectiveIds || [])
          }

          if (this.form.id != null) {
            // 修改学生
            updateStudent(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError(response.msg || "修改失败")
              }
            }).catch(error => {
              console.error('修改失败:', error)
              this.$modal.msgError("修改失败")
            })
          } else {
            // 新增学生
            addStudent(submitData).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError(response.msg || "新增失败")
              }
            }).catch(error => {
              console.error('新增失败:', error)
              this.$modal.msgError("新增失败")
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除学生名称为"' + (row.name || ids) + '"的数据项？').then(() => {
        return delStudent(ids)
      }).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$modal.msgSuccess("删除成功")
          this.ids = []
        } else {
          this.$modal.msgError(response.msg || "删除失败")
        }
      }).catch(error => {
        console.error('删除失败:', error)
        this.$modal.msgError("删除失败")
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有学生数据项？').then(() => {
        this.exportLoading = true
        return exportStudent(this.queryParams)
      }).then(response => {
        // 假设后端返回文件流，使用Blob下载
        if (response instanceof Blob) {
          const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob)
          downloadElement.href = href
          downloadElement.download = "学生数据.xlsx"
          document.body.appendChild(downloadElement)
          downloadElement.click()
          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
          this.$modal.msgSuccess("导出成功")
        } else {
          this.$modal.msgError("导出失败，返回格式不正确")
        }
        this.exportLoading = false
      }).catch(error => {
        console.error('导出失败:', error)
        this.$modal.msgError("导出失败")
        this.exportLoading = false
      })
    },



    /** 格式化时间 */
    parseTime(time) {
      if (!time) return ''

      // 如果已经是字符串，直接返回
      if (typeof time === 'string') {
        return time
      }

      // 如果是时间戳，转换为字符串
      const date = new Date(time)
      if (isNaN(date.getTime())) {
        return time
      }

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      const second = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }
  }
}
</script>

<style scoped>
.text-gray {
  color: #999;
}

.select-tips {
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

.empty-classes,
.empty-courses {
  padding: 20px;
  text-align: center;
}

</style>
