<template>
  <div>
    <div class="back_box">
      <el-button :loading="loadingStudentInfo" type="text" class="uploadDemo" 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="text" @click="goBack">返回</el-button>
    </div>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="部门管理" name="first">
        <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" />
      </el-tab-pane>
      <el-tab-pane label="成员管理" name="second">
        <el-form :inline="true" size="small" :model="formInline">
          <el-row>
            <el-col :span="21" :offset="1">
              <el-form-item label="班级">
                <el-select v-model="formInline.classId" placeholder="班级">
                  <el-option
                    v-for="item in classList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="studentId" label="学号" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="classId" label="班级" />
        </el-table>
        <div style="text-align: center;">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getCompanyDeptInfo, importCompanyMember, queryDeptInfoPaging } from '@/api/company';
import { convertSheetToList } from '@/utils/runPlan';
import XLSX from 'xlsx';

export default {
    name: 'Organization',
    data() {
        return {
            activeName: 'first',
            defaultProps: '',
            currentPage: 1,
            totalNum: 0,
            pageSize: 10,
            data: [],
            tableData: [],
            loadingStudentInfo: false,
            formInline: {
                classId: ''
            },
            classList: [],
            queryList: {
                query: queryDeptInfoPaging,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: '学号',
                        prop: 'studentID'
                    },
                    {
                        title: '姓名',
                        prop: 'name'
                    },
                    {
                        title: '班级',
                        prop: 'classId'
                    }
                ]
            }
        };
    },
    computed: {
        companyId() {
            return this.$store.state.user.companyId;
        }
    },
    mounted() {
        getCompanyDeptInfo(this.companyId).then(resp => {
        	console.log(resp);
        }).catch(error => {
            console.error(error);
        });
    },
    methods: {
        onSubmit() {
            console.log('submit!');
        },
        handleSizeChange(val) {
        	console.log(val);
        },
        handleCurrentChange(val) {
        	console.log(val);
        },
        importResults(e) {
            const obj = this.$refs.files;
            if (obj.files) {
                const file = obj.files[0];
                this.handleImportResults(file);
                obj.value = '';
            }
        },
        handleImportResults(file) {
            const studentData = { depart: '', parentDepart: '', companyUsers:[] };
            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);
                                        if (dataList.length) {
                                            const depart = dataList[2][0].trim();
                                            const parentDepart = dataList[1][0].trim();
                                            studentData.depart = depart;
                                            studentData.parentDepart = parentDepart;
                                            for ( let i = 2; i <= dataList[0].length; i++) {
                                                if (dataList[2][i] && dataList[1][i]) {
                                                    students.push({account:dataList[1][i], name: dataList[2][i]});
                                                }
                                            }
                                        }
                                        studentData.companyUsers = students;
                                    }
                                    that.loadingStudentInfo = true;
                                    importCompanyMember(that.companyId, studentData).then(resp => {
                                    }).catch((error) => {
                                        that.$message.error('学生信息导入失败:' + error.message);
                                        that.loadingStudentInfo = false;
                                    });
                                } catch (error) {
                                    that.$message.warning(`解析成绩单失败:${error}`);
                                }
                            }
                        };
                        if (that.rABS) {
                            reader.readAsArrayBuffer(file);
                        } else {
                            reader.readAsBinaryString(file);
                        }
                    }
                }, 200);
            }
        },
        handleClick() {
            this.dialogVisible = false;
        },
        goBack() {
            this.$router.go(-1);
        },
        queryFunction() {

        },
        handleNodeClick(e) {
        }
    }
};
</script>

<style scoped>
	.back_box {
		float: right;
		padding-right: 20px;
		height: 40px;
		z-index: 36;
		width: 200px;
		text-align: center;
		position: absolute;
		right: 0;
	}
	.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>
