<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="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="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="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="bjdm" width="90" />
      <el-table-column label="手机号" align="center" prop="SJH" width="120" />
      <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" prop="isRetired" width="180" />
      <el-table-column label="建档立卡户" align="center" prop="isFiling" width="180" />
      <el-table-column label="是否残疾" align="center" prop="isDisability" width="180" />
      <el-table-column label="残疾说明" align="center" prop="disableDescript" width="180" /> 
      <!-- <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope"> 
          <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="查看学生任务" :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 } 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 {
      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: {
    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;
    },
    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>
