<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="schoolYear">
        <el-input
          v-model="queryParams.schoolYear"
          placeholder="请输入学年"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="gradeValue">
        <el-select
          v-model="queryParams.gradeValue"
          clearable
          placeholder="请选择年级"
          style="width: 100%;"
        >
          <el-option
            v-for="dict in dict.type.Grade"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="ml20" 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:grade: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:grade: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:grade:remove']"
        > 删 除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button class="ml20" type="warning" plain icon="el-icon-s-check" size="mini" @click="handleUpgrade"> 升 级
        </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:grade:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="gradeList" v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="届/级" align="center" min-width="100" prop="gradeYear">
        <template slot-scope="scope">
          <span>{{ scope.row.gradeYear }}</span>
        </template>
      </el-table-column>
      <el-table-column label="级部名称" align="center" min-width="150" prop="gradeName"/>
      <el-table-column label="学年" align="center" min-width="100" prop="schoolYear"/>
      <el-table-column label="年级" align="center" min-width="110" prop="gradeValue">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.Grade" :value="scope.row.gradeValue"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" min-width="300" prop="remark"/>
      <el-table-column label="操作" min-width="250" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gradeMemberList(scope.row)"
            v-hasPermi="['system:grade:edit']"
          >级部成员
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:grade:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:grade: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="100px">
        <el-form-item label="届/级：" prop="gradeYear">
          <el-date-picker
            style="width: 100%;"
            value-format="yyyy"
            v-model="form.gradeYear"
            type="year"
            placeholder="请选择届/级">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="级部名称：" prop="gradeName">
          <el-input
            disabled
            v-model="form.gradeName"
            placeholder="请选择上方的届/级"
            clearable
          />
        </el-form-item>
        <el-form-item label="学年：" prop="schoolYear">
          <el-date-picker
            style="width: 100%;"
            v-model="form.schoolYear"
            value-format="yyyy"
            type="year"
            :picker-options="pickerOptions"
            placeholder="选择学年">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="年级：" prop="gradeValue">
          <el-select
            v-model="form.gradeValue"
            disabled
            clearable
            style="width: 100%;"
            placeholder="请选择上方的学年"
          >
            <el-option
              v-for="dict in dict.type.Grade"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入备注"
            clearable
            type="textarea"
            @keyup.enter.native="handleQuery"
          />
        </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 {
  listGrade,
  getGrade,
  delGrade,
  addGrade,
  updateGrade,
  upgrade
} from "@/api/smartSchool/teachAffairAdministration/affairGradeManage";

export default {

  name: "index",
  dicts: ["Class", "Grade", "grade_type"],
  watch: {
    'form.gradeYear': function (val) {
      if (val != null) {
        this.$set(this.form, 'gradeName', val + '级部')
      }
    },
    'form.schoolYear': function (val) {
      if (val != null) {
        let gap = this.form.schoolYear - this.form.gradeYear + 1
        this.$set(this.form, 'gradeValue', gap)
      }
    }
  },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校年级级部表格数据
      gradeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gradeValue: null,
        schoolYear: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gradeYear: [{required: true, message: '届/级不能为空', trigger: 'change'}],
        gradeName: [{required: true, message: '级部名称不能为空', trigger: 'blur'}],
        schoolYear: [{required: true, message: '学年不能为空', trigger: 'change'}],
        gradeValue: [{required: true, message: '年级不能为空', trigger: 'change'}],
        // remark: [{required: true, message: '备注不能为空', trigger: 'blur'}],
      },
      pickerOptions: {
        disabledDate: (time) => {
          let startTime = this.form.gradeYear;
          if (startTime) {
            return (Date.parse(time) < Date.parse(startTime) || Date.parse(time) > Date.parse(Number(startTime) + 2))
          }
        },
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学校年级级部列表 */
    getList() {
      this.loading = true;
      listGrade(this.queryParams).then(response => {
        this.gradeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gradeYear: null,
        gradeName: null,
        schoolYear: null,
        gradeValue: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleUpgrade() {
      this.$confirm('是否将所有级部升高一级,此操作不可逆转。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          upgrade().then((res) => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '升级操作成功!'
              });
            } else {
              this.$modal.msgError("升级操作失败");
            }
          })
        }
      ).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消此次升级操作'
        });
      });
    },
    /** 重置按钮操作 */
    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
      getGrade(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) {
            updateGrade(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGrade(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选的数据项？').then(function () {
        return delGrade(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.loading = false
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/grade/export', {
        ...this.queryParams
      }, `grade_${new Date().getTime()}.xlsx`)
    },
    gradeMemberList(row) {
      this.$router.push({
        path: "/teachAffair/gradeMemberList",
        query: {
          gradeId: row.id
        }
      })
    }
  }
};
</script>
