<template>
  <div v-loading.fullscreen.lock="loading" class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="学院" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择学院" filterable clearable @change="changeDept">
          <el-option v-for="(v, i) in deptList" :key="i" :label="v.label" :value="v.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="majorId">
        <el-select v-model="queryParams.majorId" placeholder="请先选择学院再选择专业" filterable clearable @change="changeMajor">
          <el-option v-for="(v, i) in majorList" :key="i" :label="v.majorName" :value="v.majorId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请先选择专业再选择班级" filterable clearable>
          <el-option v-for="(v, i) in classList" :key="i" :label="v.className" :value="v.classId" />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <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="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-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="['comprehensive:ranking: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="['comprehensive:ranking:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button v-hasPermi="['comprehensive:ranking:remove']" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['comprehensive:ranking:export']" type="warning" plain icon="el-icon-download" size="mini"
                   @click="handleExport"
        >导出</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>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="rankingList" @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="xsxm" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="学年" align="center" prop="stuYearName" />
      <el-table-column label="所选课程总学分" align="center" prop="courseCredit" />
      <el-table-column label="所得总学分" align="center" prop="totalCredit" />
      <el-table-column label="总成绩" align="center" prop="totalScore" />
      <el-table-column label="课程数" align="center" prop="courseNum" />
      <el-table-column label="平均分" align="center" prop="avgScore" />
      <el-table-column label="平均学分绩" align="center" prop="avgCredit" />
      <el-table-column label="专业排名" align="center" prop="ranking" />
      <el-table-column label="不及格门数" align="center" prop="nopass" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['comprehensive:ranking:edit']" size="mini" type="text" icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button v-hasPermi="['comprehensive:ranking:remove']" size="mini" type="text" icon="el-icon-delete"
                     @click="handleDelete(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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="stuNo">
          <el-input v-model="form.stuNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级编号" prop="classCode">
          <el-input v-model="form.classCode" 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="courseCredit">
          <el-input v-model="form.courseCredit" placeholder="请输入所选课程总学分" />
        </el-form-item>
        <el-form-item label="所得总学分" prop="totalCredit">
          <el-input v-model="form.totalCredit" placeholder="请输入所得总学分" />
        </el-form-item>
        <el-form-item label="总成绩" prop="totalScore">
          <el-input v-model="form.totalScore" placeholder="请输入总成绩" />
        </el-form-item>
        <el-form-item label="课程数" prop="courseNum">
          <el-input v-model="form.courseNum" placeholder="请输入课程数" />
        </el-form-item>
        <el-form-item label="平均分" prop="avgScore">
          <el-input v-model="form.avgScore" placeholder="请输入平均分" />
        </el-form-item>
        <el-form-item label="平均学分绩" prop="avgCredit">
          <el-input v-model="form.avgCredit" placeholder="请输入平均学分绩点" />
        </el-form-item>
        <el-form-item label="排名" prop="ranking">
          <el-input v-model="form.ranking" placeholder="请输入排名" />
        </el-form-item>
        <el-form-item label="不及格门数" prop="nopass">
          <el-input v-model="form.nopass" 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" width="1000px" 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" :on-success="handleFileSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件 <el-link type="primary" size="mini"
                                                                         @click="downloadMode"
          >下载模板</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 stu_years" :key="i" :label="v.stuYearName" :value="v.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table border
                :data="importData.slice((importForm.currentPage - 1) * importForm.pagesize, importForm.currentPage * importForm.pagesize)"
                :stripe="true" :current-page.sync="importForm.currentPage" max-height="550" style="width: 100%"
      >
        <el-table-column prop="stuNo" label="学号" width="180" />
        <el-table-column prop="courseCredit" label="所修课程学分" />
        <el-table-column prop="totalCredit" label="所得学分" />
        <el-table-column prop="totalScore" label="总成绩" />
        <el-table-column prop="courseNum" label="课程门数" />
        <el-table-column prop="avgScore" label="平均分" />
        <el-table-column prop="avgCredit" label="平均学分绩" />
        <el-table-column prop="ranking" label="排名" />
        <el-table-column prop="nopass" label="不及格课程数门数" />
      </el-table>
      <div class="pagination">
        <el-pagination :page-sizes="[10, 15, 20]" :page-size="importForm.pagesize" layout="total, sizes, prev, pager, next, jumper"
                       :total="importTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>

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


  </div>
</template>

<script>
import { listRanking, getRanking, delRanking, addRanking, updateRanking, importScore } from '@/api/comprehensive/ranking'
import { treeStudent } from '@/api/stuCQS/basedata/student'
import * as XLSX from 'xlsx'
import { isEmpty, isNumber } from '@/api/helpFunc'
import { listAllYear as listYear } from '@/api/stuCQS/basedata/year'
import { getDeptName } from '@/api/system/dept'
import { listMajors } from '@/api/stuCQS/basedata/majors'
import { listClass } from '@/api/stuCQS/basedata/class'
import { listGrade } from '@/api/stuCQS/basedata/grade'

export default {
  name: 'Rankings',
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pagesize: 10,
      total: 0,
      stu_year_import: null,
      fileList: [],
      //学年下拉框的内容
      stu_years: [],
      cascaderData: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //导入学生成绩的弹窗控制
      importV: false,
      // 科学文化素质表格数据
      rankingList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuNo: null,
        xsxm: null,
        className: null,
        stuYearName: null,
        classId: null,
        classCode: null,
        stuYearId: null,
        courseCredit: null,
        totalCredit: null,
        totalScore: null,
        courseNum: null,
        avgScore: null,
        avgCredit: null,
        ranking: null,
        nopass: null,
        status: null,
        createDate: null,
        updateDate: null,
        deptId: null,
        majorId: null,
        classId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      importData: [],
      importTotal: 0,
      importForm: {
        pageNum: 1,
        pageSize: 10,
        currentPage: 1,
        pagesize: 10,
        total: 0,
      },
      
      deptList: [],//学院列表
      majorList: [],//专业列表
      classList: [],//班级列表
      gradeList: [],//年级列表
    }
  },
  created() {
    this.listAllStuYear()
    this.getList()
    this.listDept()
    this.listGrade()
    this.getCascaderData()
    this.listAllStuYear()
  },

  methods: {
    async listGrade() {
      let res = await listGrade()
      this.gradeList = [...res.rows]
    },

    async listDept() {
      let res = await getDeptName()
      this.deptList = [...res.data]
    },
    
    async changeMajor() {
      if(this.queryParams.majorId) {
        let sdata = {
          pageNum: 1,
          pageSize: 100,
          majorId: this.queryParams.majorId
        }
        let res = await listClass(sdata)
        this.classList = [...res.rows]
      } else {
        this.queryParams.classId = null
        this.classList = []
      }
    },
    async changeDept() {
      if(this.queryParams.deptId) {
        let sdata = {
          collegeId: this.queryParams.deptId,
          pageNum: 1,
          pageSize: 100
        }
        let res = await listMajors(sdata)
        this.majorList = [...res.rows]
      } else {
        this.queryParams.majorId = null
        this.majorList = []
      }
    },
    // 级联选择的项
    /*handleChange(value) {
      this.queryParams = {
        ...this.queryParams,
        classId: value[2],
      }
    },*/
    //列出所有学年
    async listAllStuYear() {
      let res = await listYear()
      this.stu_years = [...res.data]
    },
    //列出学年信息
    async getStuYear() {
      let res = await listYear()
      this.stu_year_list = [...res.data]
    },
    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
          })
        })
      })
      //console.log(this.cascaderData);
    },
    //导入学生成绩
    async doImport() {
      if (isEmpty(this.stu_year_import)) {
        this.$message.info('请选择学年')
        return
      }
      this.loading = true
      let sdata = []
      let temp = [...this.importData]
      temp.map(v => {
        if (isNumber(v.avgCredit)) {
          let temp1 = {
            stuNo: v.stuNo,
            courseCredit: v.courseCredit,
            totalCredit: v.totalCredit,
            totalScore: v.totalScore,
            courseNum: v.courseNum,
            avgScore: v.avgScore,
            avgCredit: v.avgCredit,
            ranking: v.ranking,
            nopass: v.nopass,
            stuYearId: this.stu_year_import
          }
          sdata.push(temp1)
        }
      })
      console.log(sdata)
      let res = await importScore(sdata)
      this.loading = false
      this.$message(res.msg)
      this.getList()
      this.importV = false
      this.fileList = []
    },
    /** 查询科学文化素质列表 */
    getList() {
      this.loading = true
      listRanking(this.queryParams).then(response => {
        this.rankingList = response.rows
        // console.log(this.rankingList)
        this.total = response.total
        // console.log(response);
        this.loading = false
      })
    },
    downloadMode() {
      this.download('/comprehensive/ranking/exportmodel', {}, '科学文化素质导入模板.xlsx')
    },
    //点击导入弹窗按钮
    importVClick() {
      this.importV = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        this.excelData = []
        this.fileList = []
        this.tableData = []
        done()
      }).catch(_ => { })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    async fileChoose(file, fileList) {
      this.loading = true
      let data = await this.handleData(file)
      let daterank = data.map(item => ({
        stuNo: item.学号,
        courseCredit: item.所修课程学分,
        totalCredit: item.所得学分,
        totalScore: item.总成绩,
        courseNum: item.课程门数,
        avgScore: item.平均分,
        avgCredit: item.平均学分绩,
        ranking: item.排名,
        nopass: item.不及格课程数门数
      }))
      this.importData = daterank
      this.importTotal = data.length
      this.loading = false
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log('文件上传成功处理')
      console.log(response)
      this.tableData = []
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    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)
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuNo: null,
        className: null,
        stuYearName: null,
        classId: null,
        classCode: null,
        stuYearId: null,
        xsxm: null,
        courseCredit: null,
        totalCredit: null,
        totalScore: null,
        courseNum: null,
        avgScore: null,
        avgCredit: null,
        ranking: null,
        nopass: null,
        status: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null
      }
      this.resetForm('form')
    },
    handleSizeChange(val) {
      this.importForm.pagesize = val
    },
    handleCurrentChange(val) {
      this.importForm.currentPage = val
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.deptId = null
      this.queryParams.majorId = null
      this.queryParams.classId = null
      this.majorList = []
      this.classList = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(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
      getRanking(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) {
            updateRanking(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRanking(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 delRanking(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download('comprehensive/ranking/export', {
      //   ...this.queryParams
      // }, `ranking_${new Date().getTime()}.xlsx`)
      this.download('comprehensive/ranking/export', {

        ...this.queryParams
      }, '科学文化素质.xlsx')
      // console.log(this.queryParams);
    }
  }
}
</script>
