<template>
  <div class="joylink-card">
    <div style="margin-top: 20px;">
      <el-row>
        <el-col :span="20">
          <el-form ref="form" :model="form" label-width="80px" size="mini" style="width: 100%;margin-top: 10px;">
            <el-row>
              <el-col :span="6">
                <el-form-item label="班级:">
                  <el-select v-model="form.classId" placeholder="请选择" @change="getLessonByClassId">
                    <el-option
                      v-for="item in calssList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="考勤天数:">
                  <el-input-number v-model="form.attendanceDays" :min="1" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="开始日期:">
                  <el-date-picker
                    v-model="form.termBeginDate"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="结束日期:">
                  <el-date-picker
                    v-model="form.termEndDate"
                    type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="产品类型:">
                  <el-select v-model="form.prdType" placeholder="请选择">
                    <el-option
                      v-for="item in calssList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="课程:">
                  <el-select v-model="form.lessonId" placeholder="请选择">
                    <el-option
                      v-for="item in calssList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="考试:">
                  <el-select v-model="form.examPaperId" placeholder="请选择">
                    <el-option
                      v-for="item in calssList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="query">查询</el-button>
          <el-button type="primary" class="uploadDemo" size="mini" style="margin-top: 10px;">
            <input
              id="importResults"
              ref="files"
              type="file"
              class="file_box"
              accept=".json, application/json, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              @change="importResults"
            >
            成绩导入
          </el-button>
          <el-button type="primary" size="mini" style="margin-top: 10px;" @click="exportResults">成绩导出</el-button></el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getLessonDrftList } from '@/api/jmap/lessondraft';
import XLSX from 'xlsx';
import { convertSheetToList } from '@/utils/runPlan';
import { importnStudentResults } from '@/api/management/user';
import { getSessionStorage } from '@/utils/auth';
import { ProjectCode } from '@/scripts/ProjectConfig';
import { getProjectClassList } from '@/api/management/user';
import { getLessonByClassId } from '@/api/jmap/lesson';

export default {
    name: 'StudentManage',
    components: {
    },
    data() {
        return {
            loading: false,
            calssList: [],
            form: {
                attendanceDays: 1,
                classId: '',
                termBeginDate: '',
                termEndDate: '',
                prdType: '',
                lessonId: '',
                examPaperId: ''
            },
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            queryForm: {
                show: false
            },
            queryList: {
                query: this.queryFunction,
                selectCheckShow: false,
                indexShow: true,
                columns: [

                ]
            }

        };
    },
    computed: {
        mapId() {
            return this.$route.params.mapId;
        },
        hasRelease() {
            return this.$store.state.user.roles.includes('04') ||
					this.$store.state.user.roles.includes('05');
        }
    },
    watch: {
        $route() {
            this.refresh();
        }
    },
    mounted() {
        const project = getSessionStorage('project');
        getProjectClassList(ProjectCode[project]).then(resp => {
            this.calssList = resp.data;
        }).catch(() =>{
            this.$message.error('获取班级数据失败！');
        });
    },
    methods: {
        queryFunction(params) {
            return getLessonDrftList(this.$route.params.mapId, params);
        },
        importResults(e) {
            const obj = this.$refs.files;
            if (obj.files) {
                const file = obj.files[0];
                this.handleImportResults(file);
                obj.value = '';
            }
        },
        query() {

        },
        getLessonByClassId(classId) {
            getLessonByClassId(classId).then(resp => {

            }).catch(()=> {

            });
        },
        handleImportResults(file) {
            const studentData = { className: '', students:[] };
            const project = getSessionStorage('project');
            if (file) {
                setTimeout(() => {
                    const that = this;
                    const reader = new FileReader();
                    if (reader) {
                        reader.onload = function (e) {
                            let wb;
                            const data = e.target.result;
                            if (that.rABS) {
                                wb = XLSX.read(btoa(that.fixdata(data)), { // 手动转化
                                    type: 'base64'
                                });
                            } else {
                                wb = XLSX.read(data, {
                                    type: 'binary'
                                });
                            }
                            if (wb) {
                                try {
                                    const students = [];
                                    for (const index in wb.Sheets) {
                                        const dataList = convertSheetToList(wb.Sheets[index], true);
                                        const className = dataList[0][2].split(' ')[0].replace(/\s*/g, '').split('：')[1];
                                        studentData.className = className;
                                        for ( let i = 5; i <= dataList[0].length; i++) {
                                            if (dataList[0][i] && dataList[1][i]) {
                                                students.push({studentID:dataList[0][i], name: dataList[1][i]});
                                            }
                                        }
                                        studentData.students = students;
                                    }
                                    importnStudentResults(ProjectCode[project], studentData).then(resp => {
                                        that.$message.success('学生成绩导入成功！');
                                    }).catch(error => {
                                        that.$message.error('学生成绩导入失败！');
                                    });
                                } catch (error) {
                                    that.$message.warning(`解析成绩单失败:${error}`);
                                }
                            }
                        };
                        if (that.rABS) {
                            reader.readAsArrayBuffer(file);
                        } else {
                            reader.readAsBinaryString(file);
                        }
                    }
                }, 200);
            }
        },
        handelData() {

        },
        exportResults() {

        },
        refresh() {
            this.$refs.queryListPage.refresh(true);
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	@import "src/styles/mixin.scss";
	.joylink-card{
		height: 100%;
		overflow: auto;
	}
	.file_box {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		opacity: 0;
		cursor: pointer;
		z-index: 100;
	}
	.uploadDemo {
		position: relative;
		overflow: hidden;
		margin-right: 3px;
		cursor: pointer;
		padding: 0 15px;
		height: 28px;
	}
</style>
