<template>
  <div class="app-container" v-loading.fullscreen.lock="fullscreenLoading">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="学生姓名" prop="XSXM">
        <el-input v-model="queryParams.XSXM" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="考生号" prop="KSH">
        <el-input v-model="queryParams.KSH" placeholder="请输入考生号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="SFZH">
        <el-input v-model="queryParams.SFZH" placeholder="请输入身份证号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="SJH">
        <el-input v-model="queryParams.SJH" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 学院 -->
      <el-form-item label="学院" prop="XY">
        <el-input v-model="queryParams.XY" placeholder="请输入学院" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 专业 -->
      <el-form-item label="专业" prop="ZY">
        <el-input v-model="queryParams.ZY" placeholder="请输入专业" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 班级代码 -->
      <el-form-item label="班级代码" prop="BJDM">
        <el-input v-model="queryParams.BJDM" placeholder="请输入班级代码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- 班级 -->
      <el-form-item label="班级" prop="BJ">
        <el-input v-model="queryParams.BJ" placeholder="请输入班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="校编学号" prop="XH">
        <el-input v-model="queryParams.XH" placeholder="请输入校编学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="注册状态" prop="regStatus">
        <el-select v-model="queryParams.regStatus" placeholder="请选择注册状态" clearable>
          <el-option v-for="dict in dict.type.srs_stu_reg_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否申请助学贷款" prop="isLoan">
        <el-select v-model="queryParams.isLoan" placeholder="是否申请助学贷款" clearable>
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否是定向生" prop="isDirection">
        <el-select v-model="queryParams.isDirection" placeholder="是否是定向生" clearable>
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </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="['system:reg: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:reg: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:reg: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:reg:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="importVClick">导入学生信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-check" size="mini" @click="checkAllDorm">
          将所有已报到新生安排入住
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div>
      <span v-for="(v, i) in regStatusCompare" :key="i">{{ v.label }}人数:{{ v.value }}
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    </div>
    <el-table v-loading="loading" :data="regList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="查看任务" align="center" class-name="small-padding fixed-width" fixed="left">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="lookTask(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="学号" align="center" prop="xh" width="80" />
      <el-table-column label="学生姓名" align="center" prop="xsxm" width="100" />
      <el-table-column label="注册状态" align="center" prop="regStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.srs_stu_reg_status" :value="scope.row.regStatus" />
        </template>
      </el-table-column>
      <el-table-column label="分配的宿舍" align="center" prop="dorm" width="100" />
      <el-table-column label="考生号" align="center" prop="ksh" width="130" />
      <el-table-column label="学院" align="center" prop="xy" width="90" />
      <el-table-column label="专业" align="center" prop="zy" width="90" />
      <el-table-column label="班级代码" align="center" prop="bjdm" width="90" />
      <el-table-column label="班级" align="center" prop="bj" width="90" />
      <el-table-column label="性别" align="center" prop="xb" width="70" />
      <el-table-column label="政治面貌" align="center" prop="zzmm" width="80" />
      <el-table-column label="民族" align="center" prop="mz" width="70" />
      <el-table-column label="毕业学校" align="center" prop="lastSchool" width="150" />
      <el-table-column label="毕业学校所在地" align="center" prop="lastSchoolAddr" width="150" />
      <el-table-column label="家庭联系人姓名" align="center" prop="famName" width="120" />
      <el-table-column label="与本人关系" align="center" prop="famRelation" width="100" />
      <el-table-column label="家庭联系人电话" align="center" prop="famPhone" width="120" />
      <el-table-column label="家庭现居地址" align="center" prop="famNowAddr" width="180" />
      <el-table-column label="户籍所在地" align="center" prop="sfzAddr" width="180" />
      <el-table-column label="助学贷款" align="center" prop="isLoan" width="80">
        <template slot-scope="scope">
          <div>{{ scope.row.isLoan == '1' ? '是' : '否' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="贷款编号" align="center" prop="loanNo" />
      <el-table-column label="定向生" align="center" prop="isDirection">
        <template slot-scope="scope">
          <div>{{ scope.row.isDirection == '1' ? '是' : '否' }}</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reg:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:reg:remove']">删除</el-button>

          <el-button size="mini" v-if="scope.row.regStatus == '3'" type="text" icon="el-icon-check"
            @click="checkDorm(scope.row)">安排该生入住</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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="校编学号" prop="XH">
          <el-input v-model="form.xh" placeholder="请输入校编学号" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="XSXM">
          <el-input v-model="form.xsxm" placeholder="请输入学生姓名" />
        </el-form-item>
        <!-- <el-form-item label="班级" prop="XH">
          <el-input v-model="form.bj" placeholder="请输入校编学号" />
        </el-form-item> -->
        <el-form-item label="考生号" prop="KSH">
          <el-input v-model="form.ksh" placeholder="请输入考生号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="SFZH">
          <el-input v-model="form.sfzh" placeholder="请输入身份证号" />
        </el-form-item>
        <!-- <el-form-item label="班级代码" prop="bjdm">
          <el-input v-model="form.bjdm" placeholder="请输入班级代码" />
        </el-form-item> -->
        <el-form-item label="班级" prop="bjdm">
          <el-cascader placeholder="请选择班级" v-model="classVlue2" :show-all-levels="false" :options="ClassNameList"
            @change="handleChange2" clearable filterable>
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="手机号" prop="SJH">
          <el-input v-model="form.sjh" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="XB">
          <el-input v-model="form.xb" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="政治面貌" prop="ZZMM">
          <el-input v-model="form.zzmm" placeholder="请输入政治面貌" />
        </el-form-item>
        <el-form-item label="民族" prop="MZ">
          <el-input v-model="form.mz" placeholder="请输入民族" />
        </el-form-item>

        <el-form-item label="毕业学校" prop="lastSchool">
          <el-input v-model="form.lastSchool" placeholder="请输入毕业学校" />
        </el-form-item>
        <el-form-item label="毕业学校所在地" prop="lastSchoolAddr">
          <el-input v-model="form.lastSchoolAddr" placeholder="请输入毕业学校所在地" />
        </el-form-item>
        <el-form-item label="家庭联系人姓名" prop="famName">
          <el-input v-model="form.famName" placeholder="请输入家庭联系人姓名" />
        </el-form-item>
        <el-form-item label="与本人关系" prop="famRelation">
          <el-input v-model="form.famRelation" placeholder="请输入与本人关系" />
        </el-form-item>
        <el-form-item label="家庭联系人电话" prop="famPhone">
          <el-input v-model="form.famPhone" placeholder="请输入家庭联系人电话" />
        </el-form-item>
        <el-form-item label="家庭现居地址" prop="famNowAddr">
          <el-input v-model="form.famNowAddr" placeholder="请输入家庭现居地址" />
        </el-form-item>
        <el-form-item label="户籍所在地" prop="sfzAddr">
          <el-input v-model="form.sfzAddr" placeholder="请输入户籍所在地" />
        </el-form-item>
        <el-form-item label="是否申请助学贷款" prop="isLoan">
          <el-select v-model="form.isLoan" placeholder="是否申请助学贷款">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否是定向生" prop="isDirection">
          <el-select v-model="form.isDirection" placeholder="是否是定向生">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册状态" prop="regStatus">
          <el-radio-group v-model="form.regStatus">
            <el-radio v-for="dict in dict.type.srs_stu_reg_status" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </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" 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/dbf文件 <el-link @click="downloadMode" type="primary"
              size="mini">下载模板</el-link></div> -->
    <!-- </el-upload>
      </el-row>
    </el-dialog> -->

    <!--导入学生信息 -->
    <el-dialog :title="'导入Excel'" :visible.sync="dialogVisible" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" action="" :auto-upload="false" :on-change="handleFileChange" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件.</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitData">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看学生任务" :visible.sync="taskV">
      <el-table :data="task_list">
        <el-table-column label="学生姓名" align="center" prop="stuName" width="120" />
        <el-table-column label="任务序号" align="center" prop="rowRank" />
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="是否完成" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.srs_remain_status" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>




  </div>
</template>

<script>
import { listReg, getReg, delReg, addReg, updateReg, importInfo, countStatus, importDbf, checkDorm, checkAllDorm, importData } from "@/api/stureg/reg";
import { listStuTodo } from "@/api/stureg/stu_todo";
import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog, dbfToJson, isEmpty, fullLoading } from "@/api/helpFunc";
import { getClassName } from "@/api/stuCQS/basedata/student";

export default {
  name: "Reg",
  dicts: ['srs_stu_reg_status', 'srs_remain_status'],
  data() {
    return {
      dialogVisible: false, // 控制弹窗显示
      selectedFile: null,      // 存储解析后的数据(不显示)
      fullscreenLoading: false,
      fileList: [],
      tableData: [],
      currentPage: 1,
      pagesize: 10,
      total: 0,
      importV: false,
      regStatusCompare: [],
      ClassNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新生报到学生注册信息表格数据
      regList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        XSXM: null,
        KSH: null,
        SFZH: null,
        SJH: null,
        XB: null,
        ZZMM: null,
        MZ: null,
        XH: null,
        lastSchool: null,
        lastSchoolAddr: null,
        famName: null,
        famRelation: null,
        famPhone: null,
        famNowAddr: null,
        sfzAddr: null,
        regStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      classVlue2: [],
      taskV: false,
      task_list: []
    };
  },
  created() {
    this.getList();
    this.countRegStatus();
    this.getClassNameList();
  },
  methods: {
    // 文件选择变化时触发
    handleFileChange(file) {
      //const { raw } = file;

      // 文件类型校验
      // const isValidType = [
      //   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      //   'application/vnd.ms-excel'
      // ].includes(raw.type);

      // if (!isValidType) {
      //   this.$message.error('只能上传xlsx/xls文件');
      //   return;
      // }
      // 自动读取并解析文件
      //this.readFile(raw);
      this.selectedFile = file.raw;
    },

    // 读取并解析 Excel 文件
    readFile(file) {
      const reader = new FileReader();

      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });

          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 转换为 JSON(默认第一行为表头)
          const jsonData = XLSX.utils.sheet_to_json(worksheet);

          // 保存解析数据(不展示)
          this.parsedData = jsonData;

          // 显示弹窗
          this.dialogVisible = true;

        } catch (err) {
          this.$message.error('文件解析失败,请检查格式是否正确');
        }
      };

      reader.onerror = () => {
        this.$message.error('文件读取失败');
      };

      reader.readAsArrayBuffer(file);
    },

    // 点击"确定"按钮提交数据
    submitData() {
      if (!this.selectedFile) {
        console.log('Selected File:', this.selectedFile);
        this.$message.error("请选择一个Excel文件");
        return;
      }
      const formData = new FormData();
      formData.append("file", this.selectedFile); // 注意字段名 "file" 要和后端一致

      // 这里可以发送数据到后端
      //console.log('准备提交的数据:', this.parsedData);

      //this.$message.success('数据已确认导入');
      //this.dialogVisible = false;


      this.$message.success('正在导入数据...');
      importData(formData).then(res => {
        if (res.code == 200) {
          this.$message.success("导入成功");
          this.dialogVisible = false;
          this.$refs.upload.clearFiles();
          this.getList();
        }
       });//.catch(res => {
      //   this.$message.error('导入失败');
      // });
    },

    checkAllDorm() {
      this.$confirm('此操作将把所有已报到学生安排入住,如已入住将修改宿舍信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let loading = fullLoading(this);
        let res = await checkAllDorm();
        loading.close();
        if (res.code == 200) {
          this.$message.success(res.msg);

          let data = [...res.data];
          let fileName = "";
          let fileHeader = [];
          let fileHeaderZh = {};
          let fileCol = [];

          fileHeader = ['stuName', 'ksh', 'status', 'remark'];
          fileHeaderZh = {
            'stuName': "学生姓名",
            "ksh": "考生号",
            "status": "状态",
            "remark": "备注"
          };
          fileCol = [
            { wch: 20 },
            { wch: 17 },
            { wch: 20 },
            { wch: 60 }
          ];
          fileName = "入住情况";

          const arrayWithHeader = [fileHeaderZh, ...data];

          var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
            {
              header: fileHeader,
              skipHeader: true
            });
          sheet1["!cols"] = fileCol;

          // 创建一个新的空的workbook
          var wb = XLSX.utils.book_new();
          // 为每一个工作簿设置名称并添加到workbook(excel表)中
          XLSX.utils.book_append_sheet(wb, sheet1, fileName);
          const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
          // 下载文档并添加文件名称
          openDownloadDialog(workbookBlob, fileName + ".xlsx");  // 辅助函数openDownloadDialog



        }
      }).catch(() => {

      });
    },
    getClassNameList() {
      getClassName().then(res => {
        this.ClassNameList = res.data
      })
    },
    checkDorm(row) {
      this.$confirm('此操作将把学生安排入住,如已入住将修改宿舍信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let loading = fullLoading(this);
        let res = await checkDorm(row.ksh);
        loading.close();
        if (res.code == 200) {
          this.$message.success(res.msg);
        }
      }).catch(() => {

      });
    },

    async lookTask(val) {
      let loading = fullLoading(this);
      let res = await listStuTodo(val.ksh);
      loading.close();
      if (res.code == 200) {
        this.task_list = [...res.data];
        console.log(this.task_list)
        this.taskV = true;
      }
    },

    async countRegStatus() {
      let res = await countStatus();
      let data = { ...res.data };
      let arr = Array.from(Object.values(data), x => x);
      let temp = [];
      arr.map((v, i) => {
        temp.push({
          label: this.dict.type.srs_stu_reg_status[i].label,
          value: v
        });
      });
      this.regStatusCompare = [...temp];
    },

    // 下载申请信息模板
    downloadMode() {
      // 第一个sheet工作簿,如果需要创建多个,对应let多个sheetXdata即可
      let sheet1data = [
        {
          XH: "20200318211",
          XSXM: "张三",
          KSH: "21451234567890",
          SFZH: "32022222222222222",
          SJH: "17877777777",
          XB: "男",
          ZZMM: "群众",
          MZ: "汉族",
          XY: "电信",
          XYDM: "03",
          ZY: "软件",
          ZYDM: "18",
          BJ: "23软件3",
          BJDM: "01",
          "操作提示": "第一条为样板数据,XH表示学号,XSXM表示学生姓名,KSH表示考生号,SFZH表示身份证号,SJH表示手机号,XB表示性别,ZZMM表示政治面貌,MZ表示民族,XY表示学院,XYDM表示学院代码,ZY表示,ZYDM表示专业代码,BJ表示班级,BJDM表示班级代码"
        },
      ];
      // 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
    },

    //班级选择添加修改
    handleChange2(value) {
      //console.log(value);
      this.form.classId = value[2];
      this.form.deptId = value[0];
      this.form.majorId = value[1];
    },

    //导入学生成绩
    async doImport() {
      this.fullscreenLoading = true;
      this.loading = true;
      // let temp = [...this.tableData];
      // let jsonStr = JSON.stringify(temp);
      console.log(this.fileList)
      let res = await importInfo(jsonStr);
      this.loading = false;
      this.$message(res.msg);
      this.getList();
      this.fullscreenLoading = false;
      this.importV = false;
      this.fileList = [];
    },
    //点击导入弹窗按钮
    importVClick() {
      this.importV = true;
      this.dialogVisible = true;
    },
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    async fileChoose(file, fileList) {
      this.loading = true;
      let [name, format] = file.name.split('.');

      if ('.dbf'.includes(format)) {
        let formData = new FormData();
        formData.set("file", file.raw);
        let res = await importDbf(formData);
        //console.log(res);

      } else {
        let data = await this.handleData(file);
        this.tableData = data;
        this.total = data.length;
      }

      this.loading = false;
    },

    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(_ => { });
    },


    /** 查询新生报到学生注册信息列表 */
    getList() {
      this.loading = true;
      listReg(this.queryParams).then(response => {
        this.regList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        XSXM: null,
        KSH: null,
        SFZH: null,
        SJH: null,
        XB: null,
        ZZMM: null,
        MZ: null,
        XH: null,
        lastSchool: null,
        lastSchoolAddr: null,
        famName: null,
        famRelation: null,
        famPhone: null,
        famNowAddr: null,
        sfzAddr: null,
        regStatus: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        isLoan: null,
        isDirection: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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;

      getReg(id).then(response => {
        this.classVlue2 = [response.data.deptId, response.data.majorId, response.data.classId]
        console.log(response);
        this.form = response.data;
        this.open = true;
        this.title = "修改新生报到学生注册信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReg(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReg(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = [row.id];
      if (isEmpty(row.id)) {
        ids = [...this.ids];
      }

      this.$modal.confirm('是否确认删除新生报到学生注册信息编号为"' + ids + '"的数据项?').then(function () {
        return delReg(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/reg/export', {
        ...this.queryParams
      }, `reg_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
