<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable/>
        </el-form-item>
        <el-form-item label="考试类型" prop="examType">
          <el-select v-model="queryParams.examType" placeholder="请选择考试类型" clearable>
            <el-option v-for="(item,index) in dict.type.exam_type" :key="index"
                       :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-select v-model="queryParams.classId" placeholder="请选择学生班级" clearable>
            <el-option v-for="(item,index) in classList" :key="index"
                       :label="item.className" :value="item.classId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="success" icon="el-icon-download" size="mini" @click="upload.open = true">导入</el-button>
          <el-button type="warning" icon="el-icon-upload2" size="mini" @click="exportRecord">导出</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="handleOption(0)">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete"
                     size="mini" :disabled="!isMultiple" @click="handleDelete(1)">批量删除</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="achievementData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column fixed="left" label="序号" type="index" width="55" align="center"/>
        <el-table-column fixed="left" label="学生姓名" align="center" prop="studentName"/>
        <el-table-column fixed="left" label="学号" align="center" prop="studentNumber"/>
        <el-table-column fixed="left" label="身份证号" align="center" prop="idCard"/>
        <el-table-column fixed="left" label="班级" align="center" prop="className"/>
        <el-table-column fixed="left" label="考试类型" align="center" prop="examType">
          <template slot-scope="{ row }">
            <div>{{ selectDictLabel(dict.type.exam_type,row.examType) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="总成绩" align="center" prop="totalScore"/>
        <el-table-column label="学校排名" align="center" prop="ranking"/>
        <el-table-column label="语文" align="center" prop="language"/>
        <el-table-column label="学校排名" align="center" prop="ywRanking"/>
        <el-table-column label="数学" align="center" prop="math"/>
        <el-table-column label="学校排名" align="center" prop="sxRanking"/>
        <el-table-column label="英语" align="center" prop="english"/>
        <el-table-column label="学校排名" align="center" prop="yyRanking"/>
        <el-table-column label="政治" align="center" prop="politics"/>
        <el-table-column label="学校排名" align="center" prop="zzRanking"/>
        <el-table-column label="地理" align="center" prop="geography"/>
        <el-table-column label="学校排名" align="center" prop="dlRanking"/>
        <el-table-column label="历史" align="center" prop="history"/>
        <el-table-column label="学校排名" align="center" prop="lsRanking"/>
        <el-table-column label="物理" align="center" prop="physics"/>
        <el-table-column label="学校排名" align="center" prop="wlRanking"/>
        <el-table-column label="化学" align="center" prop="chemistry"/>
        <el-table-column label="学校排名" align="center" prop="hxRanking"/>
        <el-table-column label="生物" align="center" prop="biology"/>
        <el-table-column label="学校排名" align="center" prop="swRanking"/>
        <el-table-column fixed="right" label="操作" align="center" prop="orgname" width="150">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="handleDelete(0,row.id)">删除</el-button>
            <el-button type="text" size="small" @click="handleOption(1,row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination ref="pageBlock" v-show="total > 0" :total="total"
                  :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

      <!-- 导入弹出框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                   :data="{ 'curriculaId':queryParams.curriculaId }"
                   :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                   :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                   :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                     @click="downloadTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 导入弹出框 -->

      <!--  新增编辑弹出框 -->
      <el-dialog title="详细信息" :visible.sync="dialogVisible" width="50%">
        <el-form :model="achievementForm" :rules="achievementRules" ref="achievementForm"
                 label-width="80px" label-position="left">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="achievementForm.idCard" placeholder="请输入身份证号"
                          @change="searchStudentInfo" :disabled="nowType==1?true:false"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学生姓名" prop="studentName">
                <el-input v-model="achievementForm.studentName" placeholder="请输入学生姓名"
                          :disabled="nowType==1?true:false"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="班级" prop="className">
                <el-input v-model="achievementForm.className" placeholder="请输入班级"
                          :disabled="nowType==1?true:false"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学号" prop="studentNumber">
                <el-input v-model="achievementForm.studentNumber" placeholder="请输入学号"
                          :disabled="nowType==1?true:false"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="考试类型" prop="examType">
                <el-select v-model="achievementForm.examType" filterable placeholder="请选择考试类型"
                           class="selectWidth" :disabled="nowType==1?true:false">
                  <el-option v-for="(item,index) in dict.type.exam_type" :key="index"
                             :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="语文" prop="language">
                <el-input v-model="achievementForm.language" placeholder="请输入语文"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数学" prop="math">
                <el-input v-model="achievementForm.math" placeholder="请输入数学"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="英语" prop="english">
                <el-input v-model="achievementForm.english" placeholder="请输入英语"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="历史" prop="history">
                <el-input v-model="achievementForm.history" placeholder="请输入历史"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="地理" prop="geography">
                <el-input v-model="achievementForm.geography" placeholder="请输入地理"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治" prop="politics">
                <el-input v-model="achievementForm.politics" placeholder="请输入政治"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="生物" prop="biology">
                <el-input v-model="achievementForm.biology" placeholder="请输入生物"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物理" prop="physics">
                <el-input v-model="achievementForm.physics" placeholder="请输入物理"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="化学" prop="chemistry">
                <el-input v-model="achievementForm.chemistry" placeholder="请输入化学"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
      <!--  新增编辑弹出框 -->
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  addPerformance, deletePerformance, editPerformance,
  getInfoByIdCard,
  performanceList
} from "../../../../../api/smartSchool/gradeWork/courseSelection/performance";
import { classList } from "../../../../../api/smartSchool/gradeWork/courseSelection/taskPublishing";

export default {
  dicts: ['exam_type'],
  data(){
    return {
      queryParams:{
        curriculaId:'',
        studentName:'',
        examType:'',
        classId:'',
        pageNum: 1,
        pageSize: 10,
      },
      loading:false,
      total:0,
      isMultiple:false, // table是否有选择
      achievementData:[], // table数据
      dialogVisible:false, // 新增编辑弹出框
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/curricula/studentScore/importData",
      },
      achievementForm:{ // 新增、编辑成绩数据
        id:'',
        studentId:'',
        classId:'',
        studentName:'',
        studentNumber:'',
        idCard:'',
        className:'',
        examType:'',
        language:'',
        math:'',
        english:'',
        politics:'',
        geography:'',
        history:'',
        physics:'',
        chemistry:'',
        biology:'',
      },
      achievementRules:{
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ],
        studentName: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' }
        ],
        className: [
          { required: true, message: '请输入学生班级', trigger: 'blur' }
        ],
        studentNumber: [
          { required: true, message: '请输入学生学号', trigger: 'blur' }
        ],
        examType: [
          { required: true, message: '请选择考试类型', trigger: 'change' }
        ],
        language: [
          { required: true, message: '请输入语文成绩', trigger: 'blur' }
        ],
        math: [
          { required: true, message: '请输入数学成绩', trigger: 'blur' }
        ],
        english: [
          { required: true, message: '请输入英语成绩', trigger: 'blur' }
        ],
        politics: [
          { required: true, message: '请输入政治成绩', trigger: 'blur' }
        ],
        geography: [
          { required: true, message: '请输入地理成绩', trigger: 'blur' }
        ],
        history: [
          { required: true, message: '请输入历史成绩', trigger: 'blur' }
        ],
        physics: [
          { required: true, message: '请输入物理成绩', trigger: 'blur' }
        ],
        chemistry: [
          { required: true, message: '请输入化学成绩', trigger: 'blur' }
        ],
        biology: [
          { required: true, message: '请输入生物成绩', trigger: 'blur' }
        ],
      },
      classList:[], // 班级list
      nowType:0, //当前弹框类型 1编辑 0新增
      deleteArr:[] //删除数据ID数组
    }
  },
  mounted() {
    this.getClassList()
    this.getList()
  },
  methods:{
    //获取班级下拉框数据
    getClassList(){
      let grade = this.$route.query.grade
      classList(grade).then(res=>{
        if(res.code == 200){
          this.classList = res.data
        }
      })
    },

    //获取数据信息
    getList(){
      this.loading = true
      this.queryParams.curriculaId = this.$route.query.id
      performanceList({...this.queryParams}).then(res=>{
        if(res.code == 200){
          this.achievementData = res.rows
          this.total = res.total
          this.loading = false
        }
      })
    },

    //重置
    resetQuery(){
      this.queryParams = {
        curriculaId:'',
        studentName:'',
        examType:'',
        classId:'',
        pageNum: 1,
        pageSize: 10,
      }
      this.getList()
    },

    //新增、编辑成绩
    handleOption(type,item){
      this.nowType = type
      if(type == 0){
        //新增
        this.achievementForm = {
          studentId:'',
          classId:'',
          studentName:'',
          studentNumber:'',
          idCard:'',
          className:'',
          examType:'',
          language:'',
          math:'',
          english:'',
          politics:'',
          geography:'',
          history:'',
          physics:'',
          chemistry:'',
          biology:'',
        }
      }else {
        //编辑
        Object.keys(this.achievementForm).forEach(key => {
          item[key] && (this.achievementForm[key] = item[key])
        })
      }
      this.dialogVisible = true
    },

    //表单提交数据
    submitForm(){
      let data = {}
      this.$refs['achievementForm'].validate((valid) => {
        if (valid) {
          if(this.nowType == 0) {
            data = {
              studentId:this.achievementForm.studentId,
              curriculaId:this.$route.query.id,
              classId:this.achievementForm.classId,
              examType:this.achievementForm.examType,
              language:this.achievementForm.language,
              math:this.achievementForm.math,
              english:this.achievementForm.english,
              politics:this.achievementForm.politics,
              geography:this.achievementForm.geography,
              history:this.achievementForm.history,
              physics:this.achievementForm.physics,
              chemistry:this.achievementForm.chemistry,
              biology:this.achievementForm.biology,
            }
            //新增
            addPerformance(data).then(res=>{
              if(res.code == 200){
                this.$message.success("成绩添加成功！");
                setTimeout(()=>{
                  this.dialogVisible = false;
                  this.getList();
                },2000)
              }
            })
          }else {
            //编辑
            data = {
              id:this.achievementForm.id,
              studentId:this.achievementForm.studentId,
              curriculaId:this.$route.query.id,
              classId:this.achievementForm.classId,
              examType:this.achievementForm.examType,
              language:this.achievementForm.language,
              math:this.achievementForm.math,
              english:this.achievementForm.english,
              politics:this.achievementForm.politics,
              geography:this.achievementForm.geography,
              history:this.achievementForm.history,
              physics:this.achievementForm.physics,
              chemistry:this.achievementForm.chemistry,
              biology:this.achievementForm.biology,
            }
            editPerformance(data).then(res=>{
              if(res.code == 200){
                this.$message.success("成绩编辑成功！");
                setTimeout(()=>{
                  this.dialogVisible = false;
                  this.getList();
                },2000)
              }
            })
          }
        }
      })
    },

    //根据身份证号获取学生信息
    searchStudentInfo(){
      const idCard = this.achievementForm.idCard
      getInfoByIdCard(idCard).then(res=>{
        if(res.code == 200){
          Object.keys(this.achievementForm).forEach(key => {
            res.data[key] && (this.achievementForm[key] = res.data[key])
          })
        }
      })
    },

    //批量删除、删除
    handleDelete(type,id){
      let infoMessaage = type == 1?'此操作将永久删除选中数据, 是否继续?':'此操作将永久删除该数据, 是否继续?'
      this.$confirm(infoMessaage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(id){
          this.deleteArr.push(id)
        }
        let deleteStr = this.deleteArr.toString()
        deletePerformance(deleteStr).then(res=>{
          if(res.code == 200){
            this.$message.success('删除成功!');
            this.getList()
          }else {
            this.$message.error("删除失败！")
            this.getList()
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除!')
      });
    },

    //table点击事件
    handleSelectionChange(val) {
      this.isMultiple = val.length == 0?false:true
      this.deleteArr = val.map(item=>{
        return item.id
      })
    },

    //导出列表数据
    exportRecord(){
      let data = {
        curriculaId:this.queryParams.curriculaId,
        studentName:this.queryParams.studentName,
        examType:this.queryParams.examType,
        classId:this.queryParams.classId,
      }
      this.download(
        "curricula/studentScore/export",
        {
          ...data,
        },
        `学生成绩管理_${new Date().getTime()}.xlsx`
      );
    },

    //下载模板
    downloadTemplate() {
      this.download(
        "/curricula/studentScore/importTemplate",{},
        `成绩管理数据导入_template_${new Date().getTime()}.xlsx`
      );
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
}
</script>

<style lang="scss" scoped></style>
