<template>
  <div class="app-container" v-loading.fullscreen.lock="fullLoading">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="班级" prop="deptId">
        <el-cascader v-model="class_cas" ref="cas" style="width: 500px;" :options="cascaderData"
          :props="{ checkStrictly: false }" @change="handleChange" clearable filterable></el-cascader>
      </el-form-item>
      <el-form-item label="学年" prop="stuYearId">
        <el-select v-model="queryParams.stuYearId" placeholder="请选择学年" clearable @keyup.enter.native="handleQuery">
          <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名"></el-input>
      </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:sportTest: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:sportTest: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:sportTest: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:sportTest:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="importVClick">导入学生成绩</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="editVClick">更新一个学生的成绩</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sportTestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="stuNo" />
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="体能测试分数" align="center" prop="testScore" />
      <el-table-column label="学年" align="center" prop="stuYearName" />
      <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="updateVClick(scope.row)">修改分数</el-button>

          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sportTest:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:sportTest: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="学生id" prop="stuId">
          <el-input v-model="form.stuId" placeholder="请输入学生id" />
        </el-form-item>
        <el-form-item label="体能测试分数" prop="testScore">
          <el-input v-model="form.testScore" placeholder="请输入体能测试分数" />
        </el-form-item>
        <el-form-item label="学年id" prop="stuYearId">
          <el-input v-model="form.stuYearId" placeholder="请输入学年id" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" 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>

    <!-- 导入学生成绩 -->
    <el-dialog title="导入" :visible.sync="importV" :before-close="handleClose" center style="text-align: center;">
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-upload center class="upload-demo" drag :auto-upload="false" :limit="1" :on-exceed="handleExceed" action=""
          :file-list="fileList" :on-change="fileChoose">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件 <el-link @click="downloadMode" type="primary"
              size="mini">下载模板</el-link></div>
        </el-upload>
      </el-row>
      <el-form>
        <el-form-item label="学年">
          <el-select v-model="stu_year_import" placeholder="请选择学年">
            <el-option v-for="(v, i) in selectYearList" :key="i" :label="v.stuYearName" :value="v.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table border :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)" :stripe="true"
        :current-page.sync="currentPage" max-height="550" style="width: 100%">
        <el-table-column prop="stuNo" label="学号" width="180">
        </el-table-column>
        <el-table-column prop="test_score" label="体能测试成绩">
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 15, 20]"
          :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doImport()">导 入</el-button>
      </span>

    </el-dialog>

    <el-dialog title="修改分数" :visible.sync="updateV" width="500px" append-to-body>
      <el-form ref="form" :model="updateForm" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="updateForm.stuNo" readonly />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="updateForm.stuName" readonly />
        </el-form-item>
        <el-form-item label="学年">
          <el-input v-model="updateForm.stuYearName" readonly />
        </el-form-item>
        <el-form-item label="分数">
          <el-input v-model="updateForm.testScore" placeholder="请输入体能测试分数" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doUpdate">确 定</el-button>
        <el-button @click="updateV = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="更新成绩" :visible.sync="editV">
      <el-form label-width="120px">
        <el-form-item label="学号">
          <el-input size="mini" v-model="editForm.stuNo"></el-input>
        </el-form-item>
        <el-form-item label="学年">
          <el-select v-model="editForm.stuYearId" size="mini">
            <el-option v-for="(v, i) in stu_years" :key="i" :label="v.stuYearName" :value="v.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数">
          <el-input size="mini" v-model="editForm.testScore" placeholder="请输入体能测试分数" type="number" />
        </el-form-item>
        <el-form-item label="">
          <el-button @click="doEditScore">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import { editStuScore, getSportTest, delSportTest, addSportTest, updateSportTest, listLeftJoin, importExcel } from "@/api/stuCQS/info-fill/sportTest";
import { listAllStuYear } from "@/api/stuCQS/info-fill/score";
import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, file2Xce } from "@/api/helpFunc";
import { treeStudent, listEnableStu } from "@/api/stuCQS/basedata/student";
import { isEmpty,fullLoading } from "@/api/helpFunc";
import { listAllYear as listYear } from "@/api/stuCQS/basedata/year";

import { listEnableYear } from "@/api/stuCQS/basedata/year";

export default {
  name: "SportTest",
  data() {
    return {
      fullLoading: false,

      stu_list: [],
      editV: false,

      editForm: {
        stuNo: null,
        stuYearId: null,
        testScore: null
      },

      updateForm: {
        id: null,
        testScore: 0.00,
        stuName: "",
        stuNo: ""
      },
      updateV: false,

      class_cas: [],

      stu_year_import: null,
      fileList: [],
      tableData: [],
      currentPage: 1,
      pagesize: 10,
      total: 0,
      cascaderData: null,

      //学年下拉框的内容
      stu_years: [],
      //导入学生成绩的弹窗控制
      importV: false,

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 体能测试表格数据
      sportTestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuId: null,
        testScore: null,
        stuYearId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      selectYearList: []
    };
  },
  created() {
    this.listEnableYear();

    //this.getList();
    this.listAllStuYear();
    this.getCascaderData();

  },
  methods: {
    async listEnableYear() {
      let res = await listEnableYear();
      if (res.code == 200) {
        this.selectYearList = [...res.rows];
      }
    },
    async doEditScore() {
      let sdata = { ...this.editForm };
      if (isEmpty(sdata.stuNo)) {
        this.$message.info("请输入学号");
        return;
      }
      if (isEmpty(sdata.stuYearId)) {
        this.$message.info("请选择学年");
        return;
      }
      if (isEmpty(sdata.testScore)) {
        this.$message.info("请输入成绩");
        return;
      }
      this.fullLoading = true;
      let res = await editStuScore(sdata);
      this.fullLoading = false;

      if (res.code == 200) {
        this.$message.success(res.msg);
        this.getList();
        this.editV = false;
      }

    },
    editVClick() {
      this.editV = true;
    },
    async doUpdate() {
      let temp = { ...this.updateForm };
      let sdata = {
        id: temp.id,
        testScore: temp.testScore
      };
      if (isEmpty(sdata.testScore)) {
        this.$message.info("请填写分数");
        return;
      }
      this.fullLoading = true;
      let res = await updateSportTest(sdata);
      this.fullLoading = false;

      if (res.code == 200) {
        this.$message.success(res.msg);
        this.getList();
        this.updateV = false;
      }
    },

    updateVClick(v) {
      let temp = { ...v };
      this.updateForm.id = temp.id;
      this.updateForm.testScore = temp.testScore;
      this.updateForm.stuName = temp.name;
      this.updateForm.stuNo = temp.stuNo;
      this.updateForm.stuYearName = temp.stuYearName;
      this.updateV = true;
    },

    // 级联选择数据
    async getCascaderData() {
      const res = await treeStudent()
      this.cascaderData = res.data
      this.cascaderData.forEach(dept => {
        dept.children.forEach(major => {
          major.children.forEach(c => {
            delete c.children
          })
        })
      });
    },
    // 级联选择的项
    handleChange(value) {
      this.queryParams = {
        ...this.queryParams,
        classId: value[2],
      }
    },

    // 下载申请信息模板
    downloadMode() {
      // 第一个sheet工作簿，如果需要创建多个，对应let多个sheetXdata即可
      let sheet1data = [
        {
          stuNo: "20210001",
          test_score: 95,
          "操作提示": "第一条为样板数据，stuNo表示学号，test_score表示学生的体能测试成绩"
        },
      ];
      // let sheet2data = []; // 第二个sheet工作簿
      // 转换sheet格式
      var sheet1 = XLSX.utils.json_to_sheet(sheet1data);
      // 创建一个新的空的workbook      
      var wb = XLSX.utils.book_new();
      // 为每一个工作簿设置名称并添加到workbook（excel表）中
      XLSX.utils.book_append_sheet(wb, sheet1, "体能测试分导入模板");
      const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
      // 下载文档并添加文件名称
      openDownloadDialog(workbookBlob, "体能测试分导入模板.xlsx");  // 辅助函数openDownloadDialog
    },

    //导入学生成绩
    async doImport() {
      if (this.stu_year_import == null) {
        this.$message.info("请选择学年");
        return;
      }

      this.loading = true;

      let sdata = [];
      let temp = [...this.tableData];
      temp.map(v => {
        if (!isEmpty(v.stuNo)) {
          let temp1 = {
            testScore: v.test_score,
            stuNo: v.stuNo,
            stuYearId: this.stu_year_import
          };
          sdata.push(temp1);
        }
      });
      let jsonStr = JSON.stringify(sdata);

      let loading = fullLoading(this);
      let res = await importExcel(jsonStr);
      loading.close();
      this.loading = false;
      this.$message(res.msg);
      this.getList();
      this.importV = false;
      this.fileList = [];
    },
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    async fileChoose(file, fileList) {
      let data = await this.handleData(file);
      this.tableData = data;
      this.total = data.length;
    },
    handleData(file) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(file.raw);
      return new Promise((resolve, reject) => {
        reader.onload = (e) => {
          let data = e.target.result;
          let workbook = XLSX.read(data, { //手动转化
            type: 'binary'
          });
          //获取json格式的Excel数据
          let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook
            .SheetNames[0]], {
            defval: 'null' //单元格为空时的默认值
          });
          resolve(jsonData);
        };
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        this.excelData = [];
        this.fileList = [];
        done();
      }).catch(_ => { });
    },

    //点击导入弹窗按钮
    importVClick() {
      this.importV = true;
    },
    //列出所有学年
    async listAllStuYear() {
      let res = await listYear();
      this.stu_years = [...res.data];
    },

    /** 查询体能测试列表 */
    getList() {
      this.loading = true;
      listLeftJoin(this.queryParams).then(response => {
        this.sportTestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        testScore: null,
        stuYearId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      let cas = this.$refs.cas;
      cas.inputValue = "";
      this.class_cas = [];
      this.queryParams.classId = null;
      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
      getSportTest(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) {
            updateSportTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSportTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除体能测试编号为"' + ids + '"的数据项？').then(function () {
        return delSportTest(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sportTest/export', {
        ...this.queryParams
      }, `sportTest_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>