<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          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 label="高一" value="高一"/>
          <el-option label="高二" value="高二"/>
          <el-option label="高三" value="高三"/>
        </el-select>
      </el-form-item>
      <el-form-item label="班级类型" prop="classType">
        <el-select
          v-model="queryParams.classType"
          placeholder="请选择班级类型"
          clearable
        >
          <el-option label="普通班" value="普通班"/>
          <el-option label="特长班" value="特长班"/>
          <el-option label="实验班" value="实验班"/>
        </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:clazz: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:clazz: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:clazz:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clazzList" @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="className" :show-overflow-tooltip="true" />
      <el-table-column label="年级" align="center" prop="grade" width="100">
        <template slot-scope="scope">
          <el-tag :type="getGradeTagType(scope.row.grade)">{{ scope.row.grade }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="班级类型" align="center" prop="classType" width="100">
        <template slot-scope="scope">
          <el-tag :type="getClassTypeTagType(scope.row.classType)">{{ scope.row.classType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="学生人数" align="center" prop="studentCount" width="100">
        <template slot-scope="scope">
          <span :class="{ 'warning-text': scope.row.studentCount > 50 }">
            {{ scope.row.studentCount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="班主任" align="center" prop="headTeacherName" width="120" :show-overflow-tooltip="true" />
      <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="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</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="['courses:clazz:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['courses:clazz: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-select v-model="form.grade" placeholder="请选择年级" style="width: 100%">
                <el-option label="高一" value="高一"/>
                <el-option label="高二" value="高二"/>
                <el-option label="高三" value="高三"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级类型" prop="classType">
              <el-select v-model="form.classType" placeholder="请选择班级类型" style="width: 100%">
                <el-option label="普通班" value="普通班"/>
                <el-option label="特长班" value="特长班"/>
                <el-option label="实验班" value="实验班"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="学生人数" prop="studentCount">
              <el-input-number
                v-model="form.studentCount"
                :min="0"
                :max="100"
                controls-position="right"
                style="width: 100%"
                placeholder="请输入学生人数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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-col>
        </el-row>
        <el-form-item label="班主任" prop="headTeacherId">
          <el-select
            v-model="form.headTeacherId"
            placeholder="请选择班主任"
            style="width: 100%"
            clearable
            filterable
            :loading="teacherLoading"
          >
            <el-option
              v-for="teacher in teacherOptions"
              :key="teacher.id"
              :label="teacher.label"
              :value="teacher.id"
            >
              <span style="float: left">{{ teacher.teacherName }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">
                {{ teacher.teacherNo || teacher.id }}
              </span>
            </el-option>
            <div v-if="!teacherOptions.length && !teacherLoading" class="empty-teachers">
              <el-empty description="暂无教师数据" :image-size="60"/>
            </div>
          </el-select>
        </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 { listClazz, getClazz, delClazz, addClazz, updateClazz, exportClazz } from "@/api/course/clazz"
import { listTeacher } from "@/api/course/teacher"

export default {
  name: "Clazz",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级表格数据
      clazzList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 教师选项
      teacherOptions: [],
      teacherLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: null,
        grade: null,
        classType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "change" }
        ],
        classType: [
          { required: true, message: "班级类型不能为空", trigger: "change" }
        ],
        studentCount: [
          { required: true, message: "学生人数不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTeacherList()
  },
  methods: {
    /** 查询班级列表 */
    getList() {
      this.loading = true
      listClazz(this.queryParams).then(response => {
        this.clazzList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取教师列表 */
    getTeacherList() {
      this.teacherLoading = true
      listTeacher().then(response => {
        this.teacherOptions = response.map(teacher => ({
          id: teacher.id,
          teacherName: teacher.teacherName,
          teacherNo: teacher.teacherNo,
          label: `${teacher.teacherName} (${teacher.teacherNo || teacher.id})`
        }))
        this.teacherLoading = false

        if (this.teacherOptions.length === 0) {
          this.$modal.msgWarning("暂无教师数据，请先在教师管理中配置教师")
        }
      }).catch(() => {
        this.teacherOptions = []
        this.teacherLoading = false
        this.$modal.msgWarning("获取教师列表失败，请联系管理员配置教师数据")
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        className: null,
        grade: null,
        classType: null,
        studentCount: 0,
        headTeacherId: null,
        status: 1,
        remark: null
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      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
      getClazz(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改班级"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClazz(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClazz(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除班级名称为"' + row.className + '"的数据项？').then(() => {
        return delClazz(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        this.ids = []
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有班级数据项？').then(() => {
        this.exportLoading = true
        return exportClazz(this.queryParams)
      }).then(response => {
        this.$download.name(response, "班级数据.xlsx")
        this.exportLoading = false
      }).catch(() => {})
    },
    /** 年级标签类型 */
    getGradeTagType(grade) {
      const types = {
        '高一': 'success',
        '高二': 'warning',
        '高三': 'danger'
      }
      return types[grade] || ''
    },
    /** 班级类型标签类型 */
    getClassTypeTagType(classType) {
      const types = {
        '普通班': '',
        '特长班': 'success',
        '实验班': 'warning'
      }
      return types[classType] || ''
    }
  }
}
</script>

<style scoped>
.warning-text {
  color: #e6a23c;
  font-weight: bold;
}

.empty-teachers {
  padding: 20px;
  text-align: center;
}
</style>
