<style lang="less" scoped>
  @import './ImportStudent.less';
</style>
<style lang="less">
  @import './IImportStudent.less';
</style>
<template>
  <Modal v-model="show" width="70%" class="import-student" :mask-closable="false" @on-cancel="cancel">
    <div slot="header">
      <span class="model-title">{{$t('stuAccount.importTitle')}}</span>
    </div>
    <div class="content">
      <div v-if="file == null">
        <Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx" :show-upload-list="false">
          <Icon type="ios-folder" color="#606060" size="200" style="margin-top:60px;cursor:pointer;" @click="openUploadFile" />
        </Upload>
        <p class="import-tips" style="margin-top:40px;">{{$t('stuAccount.importTips1')}}</p>
        <p class="import-tips">{{$t('stuAccount.importTips2')}}</p>
        <p class="import-tips">{{$t('stuAccount.importTips3')}}</p>
      </div>
      <div class="form-body" style="background:none;" v-if="file !== null">
        <div class="ivu-upload-list-file">
          <Icon type="ios-stats"></Icon>
          {{ file.name }}
          <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove" @click.native="handleRemove()"></Icon>
        </div>
        <div class="table-info">
          <div class="table-info-item">
            <span class="table-info-label">{{$t('stuAccount.importInfo1')}}</span>
            <span class="table-info-num">{{totalNum}}</span>
          </div>
          <div class="table-info-item" v-if="repeatNum != 0">
            <span class="table-info-label">{{$t('stuAccount.importInfo2')}}</span>
            <span class="table-info-num">{{repeatNum}}</span>
          </div>
          <div class="table-info-item"  v-if="seatRepeatNum != 0">
            <span class="table-info-label">{{$t('stuAccount.importInfo3')}}</span>
            <span class="table-info-num">{{seatRepeatNum}}</span>
          </div>
          <div class="table-info-item" v-if="noClassroomNum != 0">
            <span class="table-info-label">{{$t('stuAccount.importInfo4')}}</span>
            <span class="table-info-num">{{noClassroomNum}}</span>
          </div>

          <div class="table-info-item" v-if="existNum != 0">
            <span class="table-info-label">{{$t('stuAccount.importInfo5')}}</span>
            <span class="table-info-num">{{existNum}}</span>
          </div>
          <div class="table-info-item" style="display:none;">
            <span class="table-info-label">{{$t('stuAccount.importInfo6')}}</span>
            <span class="table-info-num">{{totalNum - repeatNum - existNum}}</span>
          </div>
          <!--<div class="table-info-item">
            <Icon type="md-trash" size="18" color="white" @click="initUpload" />
          </div>-->
        </div>
        <Table :row-class-name="rowClassName" :columns="tableTitle" :data="tableData" :loading="tableLoading" height="560" style="margin-top:15px; " @on-select="getSelectInfo" @on-select-cancel="getSelectInfo" @on-select-all="getSelectInfo" @on-select-all-cancel="cancelAll">
          <template slot-scope="{ row,index }" slot="password">
            <p>{{(row.password == '' || row.password == null)? '— —' : row.password+''}}</p>
          </template>
          <template slot-scope="{ row,index }" slot="status">
            <p :class="(repeatAccounts.length == 0 || repeatAccounts.indexOf(row.account) == -1) ? 'account-success-tips':'account-error-tips'">{{(repeatAccounts.length == 0 || repeatAccounts.indexOf(row.account) == -1)?"":"错误：账号重复！" }}</p>
            <p :class="(row.classroomCode == '' || row.classroomCode == null) ? 'account-warning-tips':''">{{(row.classroomCode == '' || row.classroomCode == null)?"警告 ：未找到指定教室":"" }}</p>
            <p :class="row.seatRepeat? 'account-error-tips':''">{{row.seatRepeat ? "错误：座位号重复":"" }}</p>
          </template>
        </Table>
        <p style="margin-top:15px;">{{$t('stuAccount.passwordTips')}}</p>
        <Button class="confirm-btn" :class=" isError == 0 ?'confirm-btn-active':''  " :loading="uploadLoading" @click="saveFileData">
          {{$t('stuAccount.submitList')}}
        </Button>
      </div>
    </div>
    <div slot="footer">

    </div>
  </Modal>
</template>
<script>
  import excel from '../../../utils/excel'
  export default {
    props: {
      isShow: {
        type: Boolean,
        default: false
      },
      schoolCode: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        totalNum: 0,
        seatRepeatNum:0,
        repeatNum: 0,
        existNum: 0,
        repeatAccounts:[],
        noClassroomNum:0,
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        selectionData:[],
        file: null,
        tableData: [],
        tableTitle: [],
        tableLoading: false,
        systemColumn: [
          'account',
          'password',
          'name',
          'classroomName',
          'classroomCode',
          'seatNo'
        ]
      }
    },
    components: {
    },
    computed: {
      isError() {
        return this.seatRepeatNum + this.repeatNum + this.existNum + this.noClassroomNum;
      },
      show: {
        get() {
          return this.isShow;
        },
        set(value) {
        }
      },

    },
    watch: {
    },
    methods: {
      getSelectInfo() {

      },
      cancelAll() {

      },
      rowClassName(row, index) {
        let className = ''
        if (!(this.repeatAccounts.length == 0 || this.repeatAccounts.indexOf(row.account) == -1) || row.seatRepeat) {
          className = className + 'account-error-row-bg ';
        }
        if (row.classroomCode == '' || row.classroomCode == null) {
          className = className + 'account-warning-row-bg';
        }
        return className;
      },
      cancelUploadFile() {
        this.file = null;
      },
      initUpload() {
        this.file = null;
        this.showProgress = false;
        this.loadingProgress = 0;
        this.tableData = [];
      },
      openUploadFile() {
        this.initUpload()
      },
      handleRemove() {
        this.initUpload()
        this.$Message.info(this.$t('stuAccount.importTips4'));
      },
      handleBeforeUpload(file) {
        const fileExt = file.name.split('.').pop().toLocaleLowerCase()
        if (fileExt === 'xlsx' || fileExt === 'xls') {
          this.readFile(file)
          this.file = file
        } else {
          this.$Notice.warning({
            title: this.$t('stuAccount.importTips5'),
            desc: this.$t('stuAccount.importTips6') + file.name + this.$t('stuAccount.importTips7')
          })
        }
        return false
      },
      // 读取文件
      readFile(file) {
        this.tableLoading = true
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onloadstart = e => {
          this.showProgress = true
        }
        reader.onprogress = e => {
          this.progressPercent = Math.round(e.loaded / e.total * 100)
        }
        reader.onerror = e => {
          this.$Message.error(this.$t('stuAccount.importTips8'));
        }
        reader.onload = e => {
          const data = e.target.result;
          const { header, results } = excel.read(data, 'array');
          const tableColumn = header.map(item => { return { title: item, key: item } });
          const columns = tableColumn.map(item => {
            return item.key
          });
          const columnStr = columns.join("");
          console.log(columnStr);
          let flag = true;
          let column = '';
          for (let item of this.systemColumn) {
            let f = 0;
            for (let i of columns) {
              if (i == item) {
                f = 1;
                break;
              }
            }
            if (f == 0) {
              column = item;
              flag = false;
              break;
            }
          }
          if (flag) {
            //处理表格导入数据类型
            this.tableData = results.filter(item => {
              let arr = item.account.split("#");
              if (arr.length == 2) {
                for (let i of this.systemColumn) {
                  if (i != 'seatNo') {
                    if (typeof item[i] == "number") {
                      item[i] = item[i] + "";
                    }
                    if (item.password == undefined) {
                      item.password = arr[1]
                    }
                  }
                }
                
              } else {
                item._disabled = true;
              }
              return item;
            });
            //计算重复账号数量和重复账号,过滤重复账号
            this.totalNum = this.tableData.length;
            let accounts = this.tableData.map(item => { return item.account });
            this.repeatAccounts = accounts.filter((item, index, self) => self.indexOf(item) != index);
            this.repeatAccounts = this.repeatAccounts.filter((item, index, self) => self.indexOf(item) === index);
            //直接过滤重复账号
            //this.tableData = this.tableData.filter((item, index, self) => {
            //  if (accounts.indexOf(item.account) === index) {
            //    return 1;
            //  } else {
            //    return 0;
            //  }
            //});
            accounts = accounts.filter((item, index, self) => self.indexOf(item) === index);
            this.repeatNum = this.totalNum - accounts.length + this.repeatAccounts.length;
            //根据教室Code GroupBy,判断班级座位号是否重复
            console.log("++++++++++");
            let classStu = this.groupBy(this.tableData, 'classroomCode');
            for (let item of classStu) {
              let seatNoArr = item.map(item => { return item.seatNo });
              for (let index in item) {
                let flag = seatNoArr.indexOf(item[index]['seatNo'])
                if (flag != index) {
                  let tableIndex = this.getIndex(this.tableData, item[flag]);
                  if (this.tableData[tableIndex].seatRepeat != true) {
                    this.seatRepeatNum++;
                    this.tableData[tableIndex].seatRepeat = true;
                  }
                  tableIndex = this.getIndex(this.tableData, item[index]);
                  this.tableData[tableIndex].seatRepeat = true;
                  this.seatRepeatNum++;
                }
              }
            }
            //筛选没有教室账号
            let noRoom = this.tableData.filter(item => { return (item.classroomCode == '' || item.classroomCode == null) });
            this.noClassroomNum = noRoom.length;
            this.$Message.info(this.$t('stuAccount.importTips11'));
            this.tableLoading = false;
          } else {
            this.$Message.error({
              content: this.$t('stuAccount.importTips9') + column + this.$t('stuAccount.importTips10'),
              duration:4
            });
            this.tableLoading = false;
          }
          this.showRemoveFile = true;
        }
      },
      groupBy(array, key) {
        const groups = {}
        array.forEach(function (item) {
          const group = JSON.stringify(item[key])
          groups[group] = groups[group] || []
          groups[group].push(item)
        })
        return Object.keys(groups).map(function (group) {
          return groups[group]
        })
      },
      /*
      *获取对象在对象数组的中index
      */
      getIndex(_arr, _obj) {
        var len = _arr.length;
        for (let i = 0; i < len; i++) {
          if (this.isObjEqual(_arr[i],_obj)) {
            return parseInt(i);
          }
        }
        return -1;
      },

      /*
      * 判断两个json对象是否相同
      */
      isObjEqual(o1, o2) {
        var props1 = Object.keys(o1);
        var props2 = Object.keys(o2);
        console.log(props1);
        if (props1.length != props2.length) {
          return false;
        }
        for (var i = 0, max = props1.length; i < max; i++) {
          var propName = props1[i];
          if (o1[propName] !== o2[propName]) {
            return false;
          }
        }
        return true;
      },
      saveFileData() {
        if (this.isError == 0) {
          this.uploadLoading = true;
          //if (this.repeatNum != 0) {
          //  let accounts = this.tableData.map(item => { return item.account });
          //  let repeat = accounts.filter((item, index, self) => self.indexOf(item) != index);
          //  this.tableData = this.tableData.filter((item, index, self) => repeat.indexOf(item.account) === -1)
          //}
          this.$emit("importStudentInfo", {
            data: this.tableData
          });
          this.initData();
          this.uploadLoading = false;
        } else {
          this.$Message.error(this.$t('stuAccount.importTips12'));
        }
        
      },
      cancel() {
        this.initData();
        this.$emit("importStudentInfo", {
          data:[]
        });
      },
      initData() {
        this.totalNum = 0;
        this.repeatNum = 0;
        this.existNum = 0;
        this.seatRepeatNum = 0;
        this.repeatAccounts = [];
        this.noClassroomNum = 0;
        this.uploadLoading =  false;
        this.progressPercent = 0;
        this.showProgress = false;
        this.showRemoveFile =  false;
        this.file = null;
        this.tableData = [];
        this.tableTitle = [
          {
            type: 'selection',
            width: 80,
            align: 'center'
          },
          {
            title: this.$t('stuAccount.seatNo'),
            key: 'seatNo',
            width: 80,
          },
          {
            title: this.$t('stuAccount.account'),
            key:'account'
          },
          {
            title: this.$t('stuAccount.password'),
            slot:'password'
          },
          {
            title: this.$t('stuAccount.stuName'),
            key:'name'
          },
          {
            title: this.$t('stuAccount.classroomName'),
            key:'classroomName'
          },
          {
            title: this.$t('stuAccount.classroomCode'),
            key:'classroomCode'
          },
          {
            title: this.$t('stuAccount.abnormalStatus'),
            slot:'status'
          }
        ]
      }
    },
    created() {
      this.initData();
    },
    mounted() {

    },
    watch: {

    }
  }
</script>
