<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属学校" prop="schoolId">
        <el-select v-model="queryParams.schoolId" placeholder="请选择学校" style="width: 100%;">
            <el-option v-for="dict in dictTables.schoolDict" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
      </el-form-item>
      <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="classCount">
        <el-input
          v-model="queryParams.classCount"
          placeholder="请输入班级人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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="['system:clazz:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:clazz:edit']"
        >修改</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="['system: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="['system: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="序号" type="index" align="center"/>
       <!-- todo 显示 学校名称 -->
       <el-table-column label="所属学校" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dictTables.schoolDict" :value="scope.row.schoolId" />
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班主任" align="center" prop="teacherName" />
      <el-table-column label="班级人数" align="center" prop="classCount" />
      <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="['system:clazz:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:clazz:remove']"
          >删除</el-button>
          <!-- 要弹出对话框 让其进行选择 -->
          <el-button 
            v-if="scope.row.teacherMain === 'N' || scope.row.teacherMain === null" 
            size="mini" type="text"
            @click="handleTeacherClassBind(scope.row)"
          >
            <i class="el-icon-bind"></i>
            绑定班主任
          </el-button>
          <el-button 
            v-if="scope.row.teacherMain === 'Y'" 
            size="mini" type="text"
            @click="unbindTeacherMain(scope.row)"
          >
            <i class="el-icon-bind"></i>
            解绑班主任
          </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"
    />

    <!-- 新增 修改 班级信息 组件-->
    <clazz-form
      ref="clazzForm"
      @submit="submitForm"
      @cancel="cancel"
    ></clazz-form>
    <!-- 绑定班主任对话框 -->
    <bind-teacher-class ref="bindTeacherClass" @resetTable="getList"/>
  </div>
</template>

<script>
import { listClazz, getClazz, delClazz, addClazz, updateClazz } from "@/api/system/clazz";
import {updateTeacherClassRelation} from '@/api/system/teacher_class_relation'
import ClazzForm from "./module/ClazzForm";
import BindTeacherClass from "./module/BindTeacherClass";
import Textyixia from "@/mixin/Textyixia"

import { Loading } from 'element-ui';

export default {
  name: "Clazz",
  mixins: [Textyixia],
  dicts: ['sys_yes_no'],
  components: {
    ClazzForm,
    BindTeacherClass,
  },
  data() {
    return {
      dictTables: {
        schoolDict: []
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级管理表格数据
      clazzList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolId: null,
        className: null,
        classCount: null,
        phone: null,
      },
      // 表单参数
      form: {},
     
    };
  },
  created() {
    this.getList();
    this.dictTableData("tb_school,school_name,id").then(data => {
      this.dictTables.schoolDict = data
    })
  },
  methods: {
    /** 查询班级管理列表 */
    getList() {
      this.loading = true;
      listClazz(this.queryParams).then(response => {
        this.clazzList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.$refs.clazzForm.open = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.$refs.clazzForm.reset()
    },
    /** 搜索按钮操作 */
    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.$refs.clazzForm.open = true
      this.$refs.clazzForm.title = "添加班级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClazz(id).then(response => {
        this.$refs.clazzForm.form = response.data;
        this.$refs.clazzForm.open = true
        this.$refs.clazzForm.title = "修改班级信息";
        this.$refs.clazzForm.searchTeacherOption(true);
        this.$refs.clazzForm.schoolOptions = this.dictTables.schoolDict
      });
    },
    /** 提交按钮 */
    submitForm(data) {
      if (data.id != null) {
          updateClazz(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$refs.clazzForm.open = false
            this.getList();
          });
        } else {
          addClazz(data).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$refs.clazzForm.open = false
            this.getList();
          });
        }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除班级管理编号为"' + ids + '"的数据项？').then(function() {
        return delClazz(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/clazz/export', {
        ...this.queryParams
      }, `clazz_${new Date().getTime()}.xlsx`)
    },
    /** 绑定班主任 */
    handleTeacherClassBind(row) {
      // 弹出对话框，并让用户设置对应的教师
      this.$refs.bindTeacherClass.form.schoolId = row.schoolId;
      this.$refs.bindTeacherClass.form.classId = row.id;
      this.$refs.bindTeacherClass.openDialog();

    },
    /** 解绑班主任 */
    unbindTeacherMain(row) {
        this.form = {
            schoolId: row.schoolId,
            classId: row.id,
            teacherMain: 'N',
        }
        // 解绑班主任关系
        this.$confirm('确定解绑班主任？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loadingInstance =  Loading.service({fullscreen: true, text: '正在解绑班主任...', background: 'rgba(0, 0, 0, 0.8)'})
          updateTeacherClassRelation(this.form).then(res => {
            console.log(res);
            this.$message({
              type:'success',
              message: '解绑成功!'
            });
           
          }).finally(() => {
            setTimeout(() => {
              this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
                loadingInstance.close();
              });
            }, 500)
            this.getList();
          })
        })
    }
  }
};
</script>
