<style lang="less" scoped>
  @import './Student.less';
</style>

<style lang="less">
.loginBox{
  .loginForm{
    .formItem{
      input, select{
        border-radius: 0;
        font-size: 12px;
      }
      .ivu-select-selection{
        border-radius: 0;
      }
    }
    .schoolAutoComplete{
      height: 170px;
      .schoolsBox{
        border-bottom: 1px solid #e9e9e9;
        padding: 5px 5px 5px 15px;
        .area{
          font-size: 12px;
          padding: 5px;
        }
      }
    }
    .ivu-select-dropdown{
      border-radius: 0;
    }
  }
}
.identityModal{
  .ivu-modal{
    .ivu-modal-content{
      background-color: #2a292e;
      padding: 12px;
      border: 1px solid #ccc;
      .ivu-modal-header, .ivu-modal-footer{
        border: 0;
      }
      .ivu-modal-footer{
        padding: 0;
      }
      .ivu-modal-header{
        padding: 5px 16px;
        p{
          color: whitesmoke;
        }
      }
      .identity-body{
        display: flex;
        justify-content: space-around;
        align-items: center;
        .ivu-btn{
          background-color: #1cc0f2;
          color: white;
          font-weight: bold;
          border: 0;
          padding: 0 22px;
        }
      }
    }        
  }
}
.demo-spin-col .ivu-spin-main{
	background-color: transparent;
	padding: 0;
}
</style>

<template>
  <div class="loginDiv">
    <div class="schoolName">
        <div style="width: 100px;height: 100px;background-color: #69b0d0;border-radius: 4px;cursor: pointer;">
          <img style="display: block;width: 100%;height: 100%;" src="@/assets/icon/studentIcon.png">
        </div>
    </div>
    <div class="formDiv">
      <div class="loginBox">
        <div class="title">
          <div class="logo">
            <img  width="15" height="15" src="@/assets/icon/tmd_account.svg">
          </div>
          <h4 class="text">
            {{ qrloginFlag ? $t('login.title.QRLogin'): $t('login.title.IDLogin') }}
          </h4>
          <Tooltip class="tooltip" placement="right-end" :transfer="true" max-width="200">
            <img src="@/assets/icon/icon_info.svg" width="15" height="15">
            <div slot="content">
              <p style="font-size: 12px;">{{ $t('login.tooltip.text1') }}</p>
            </div>
          </Tooltip>
        </div>
        <h4 class="subTitle">
          {{ qrloginFlag ? $t('login.subTitle.QRLogin') : $t('login.subTitle.IDLogin')}}
        </h4>

        <div v-show="!qrloginFlag">
          <Form class="loginForm" ref="loginForm" :model="loginForm" :rules="loginRule" :show-message="false" @keydown.enter.native="loginSubmit('loginForm')">
            <FormItem class="formItem" prop="id" >
              <Input element-id = "tmdID" v-model="loginForm.id" :placeholder="$t('login.placeholder.id')"/>
            </FormItem>
            <FormItem class="formItem"  prop="pass">
              <Input element-id = "tmdpw" type="password" v-model="loginForm.pass" :placeholder="$t('login.placeholder.psw')" >
                <Icon size="24" v-show="!loading && loginFormEnter" @click="loginSubmit('loginForm')" type="md-arrow-forward" slot="suffix" class="iconFrame" />
                <div v-show="loading" class="demo-spin-col" slot="suffix">
                  <Spin>
                    <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
                  </Spin>
                </div>
              </Input>
            </FormItem>
            <div class="errlable">{{ loginErrText }}</div>
          </Form>

          <div class="extra">
            <div class="qrlogin">
              <div class="logo">
                <img  width="15" height="15" src="@/assets/icon/icon_qrcode.svg">
              </div>
              <a @click="chgLoginType()">{{ $t('login.link.QRLogin') }}</a>
            </div>
            <div class="link">
              <router-link to="/regist">{{ $t('login.link.regist') }}</router-link> | <router-link to="/forgotpw">{{ $t('login.link.forgetPsw') }}</router-link>
            </div>
          </div>

          <div class="communyLoging">
            <div class="description">{{ $t('login.communy.title')}}</div>
            <div class="links">
              <div v-if="!(srvAdr == 'China')" class="icon" @click="oauthLogin('facebook')">
                <img  src="@/assets/icon/icon_fb.svg">
                <span>{{ $t('login.communy.fb')}}</span>
              </div>
              <div v-if="!(srvAdr == 'China')" class="icon" @click="oauthLogin('google')">
                <img  src="@/assets/icon/icon_google.svg">
                <span>{{ $t('login.communy.google')}}</span>
              </div>
              <div v-if="!(srvAdr == 'Global')" class="icon" @click="oauthLogin('wechat')">
                <img  src="@/assets/icon/icon_wechat.svg">
                <span>{{ $t('login.communy.wechat')}}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-show="qrloginFlag">
          <div class="qrloginMode">
            <div class="qrcodeBox">
              <div id="qrcode" :class="{'qrcode': joinQRcode != undefined}" ref="qrcode"></div>
              <div class="expired" v-if="joinQRcode != undefined && !sseSurvive">
                <Icon size="40" type="md-refresh-circle" @click="SEELink()" />
              </div>
            </div>              
            <div class="links">
              <div class="icon-a">
                <img src="@/assets/icon/icon_account.svg">
                <a @click="chgLoginType()">{{ $t('login.link.IDLogin') }}</a>
              </div>
              <router-link to="/regist">{{ $t('login.link.regist') }}</router-link>
            </div>
          </div>
        </div>
      </div>

      <div class="loginBox">
      <div class="title">
        <div class="logo">
          <img  width="15" height="15" src="@/assets/icon/tmd_account.svg">
        </div>
        <h4 class="text">{{ $t('login.title.schoolLogin') }}</h4>
        <Tooltip class="tooltip" placement="right-end" :transfer="true" max-width="200">
            <img src="@/assets/icon/icon_info.svg" width="15" height="15">
            <div slot="content">
              <p style="font-size: 12px;">{{ $t('login.tooltip.text2') }}</p>
            </div>
        </Tooltip>
      </div>
      <h4 class="subTitle">{{ $t('login.subTitle.schoolLogin') }}</h4>
      <Form class="loginForm" ref="studForm" :model="studForm" :rules="studRule" :show-message="false" @keydown.enter.native="loginSubmit('studForm')">
        <FormItem class="formItem" style="margin-bottom: 15px;" prop="schoolCode">
          <Select v-show="!defaultSchool.code" v-model="studForm.schoolCode" :placeholder="$t('login.placeholder.schoolMenu')" filterable clearable >
            <template v-for="(item, index) in schoolList" >
              <OptionGroup :label="item.province" :key="index">
                <Option v-for="school in item.schools" :key="school.id" :value="school.id">{{ school.name }}</Option>
              </OptionGroup>
            </template>
          </Select>
        </FormItem>
        <FormItem class="formItem" prop="id" >
          <Input element-id = "studId" v-model="studForm.id" :placeholder="$t('login.placeholder.schoolID')"/>
          <input type="text" style="position:fixed;z-index:-10000;width:0;border:none"/>
        </FormItem>
        <FormItem class="formItem"  prop="pass">
          <input type="password" style="position:fixed;z-index:-10000;width:0;border:none"/>
          <Input element-id="studpw"  type="password" v-model="studForm.pass" :placeholder="$t('login.placeholder.schoolPsw')" >
            <!-- <Icon v-show="studFormEnter" @click="loginSubmit('studForm')" type="md-arrow-forward" slot="suffix" /> -->
            <Icon size="24" v-show="!loading && studFormEnter" @click="loginSubmit('studForm')" type="md-arrow-forward" slot="suffix" class="iconFrame" />
            <div v-show="loading" class="demo-spin-col" slot="suffix">
              <Spin>
                <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
              </Spin>
            </div>
          </Input>
        </FormItem>
        <div class="errlable">{{ schoolErrText }}</div>
      </Form>
      </div>
    </div>
  </div>
</template>
<script>
import { EventSourcePolyfill } from 'event-source-polyfill';
import QRCode from 'qrcodejs2'
import { User } from '@/service/User'
import { mapState, mapGetters } from 'vuex'

export default {
  data() {
    const validateID = (rule, value, callback) => {
      if (value === '') {
          callback(new Error());
          this.loginErrText = this.$t('error.required')
      } else if (value.search(/^\+/) == 0) {
          callback(new Error());
          this.loginErrText = this.$t('error.format.default')
      } else {
        if(value.indexOf('@') >=0){ //是否為Email
          var emailRule = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/;
          if(value.search(emailRule)!= -1){
              callback();
              this.loginErrText = ''
          } else {
              callback(new Error());
              this.loginErrText = this.$t('error.format.email')
          }
        } else {
          callback();
          this.loginErrText = ''
        }
      }
    };
    const validatePW = (rule, value, callback) => {
      if (value === '') {
          callback(new Error());
          this.loginErrText = this.$t('error.required')
      }
      else {
          callback();
          this.loginErrText = ''
      }
    };
    const validateStudID = (rule, value, callback) => {
      if (value === '') {
          callback(new Error());
          this.schoolErrText = this.$t('error.required')
      } else if (value.search(/^\+/) == 0) {
          callback(new Error());
          this.schoolErrText = this.$t('error.format.default')
      } else {
        if(value.indexOf('@') >=0){ //是否為Email
          var emailRule = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/;
          if(value.search(emailRule)!= -1){
              callback();
              this.schoolErrText = ''
          } else {
              callback(new Error());
              this.schoolErrText = this.$t('error.format.email')
          }
        } else {
          callback();
          this.schoolErrText = ''
        }
      }
    };
    const validateStudPW = (rule, value, callback) => {
      if (value === '') {
          callback(new Error());
          this.schoolErrText = this.$t('error.required')
      }
      else {
          callback();
          this.schoolErrText = ''
      }
    };
    const validateStudSchoolCode = (rule, value, callback) => {
      if (value === '') {
          callback(new Error());
          this.schoolErrText = this.$t('error.required')
      }
      else {
          callback();
          this.schoolErrText = ''
      }
    };
    return {
      qrloginFlag: false,
      loginForm: {
          id: '',
          pass: '',
      },
      loginRule: {
          id: [
              { validator: validateID, trigger: 'blur' },
          ],
          pass: [
              { validator: validatePW, trigger: 'blur' },
          ]
      },
      studForm: {
        schoolCode: '',
        id: '',
        pass: ''
      },
      studRule: {
          schoolCode: [
            { validator: validateStudSchoolCode, trigger: 'blur' },
          ],
          id: [
            { validator: validateStudID, trigger: 'blur' },
          ],
          pass: [
            { validator: validateStudPW, trigger: 'blur' },
          ]
      },
      loginErrText: '',
      schoolErrText: '',
      userOauth: {        // 社群帳號
          code: '',
          state: ''
      },
      schoolList: [],
      loading: false,
      sseSurvive: false,
      joinQRcode: undefined,
      defaultSchool: {
        name: '',
        code: ''
      },
      identityFlag: false
    }
  },
  computed: {
    ...mapState({
      config: state => state.config
    }),
    ...mapGetters({
        srvAdr: 'config/getSrvAdr'
    }),
    loginFormEnter: function(){
      let flag = false
      if(this.loginForm.id && this.loginForm.pass) flag = true
      return flag
    },
    studFormEnter: function(){
      let flag = false
      if(this.studForm.schoolCode && this.studForm.id && this.studForm.pass) flag = true
      return flag
    }
  },
  created() {
    // 此頁面為學生頁面
    localStorage.setItem('identity', 'student')

    // 建立學校LIST清單
    this.getSchools()

    // 取得學校設定簡碼
    this.setLoginSchoolCode()
  },
  methods: {
    chgLoginType: function(){ // 變更登入類型
      this.qrloginFlag = !this.qrloginFlag
      if(this.qrloginFlag && !this.sseSurvive) {
        // SSE 連線
        this.SEELink()
      }
    },
    loginSubmit: function(name){  // 登入
      this.$refs[name].validate( async(valid) => {        
        if (valid) {
          this.loading = true // 登入中動畫
          let result; // 輸出暫存
          let isFail = false // 失敗flag

          switch (name) {
            case 'loginForm':
              
              // 詢問帳號是否有效
              await this.$api.login.verification({id: this.loginForm.id, pass: this.loginForm.pass}).then(res => {
                result = res
              }).catch(err=>{
                isFail = true
              })
              console.log('res***',result)
              if(isFail){
                this.loginErrText = this.$t('login.apiError.text1')
                this.loading = false
              } else {
                this.loginProcess(result, this.defaultSchool.code)
              }              
              break;
            case 'studForm':

              // 學生登入大雲
              await this.$api.login.studLogin({schoolCode: this.studForm.schoolCode, id: this.studForm.id, pw: this.studForm.pass}).then( res => {
                  result = res
              }).catch(err=>{
                isFail = true
              })


              if(isFail){
                this.schoolErrText = this.$t('login.apiError.text1')
                this.loading = false
              } else {
                //設定權限並登入
                User.login(result).then(res => {
                  if(res) {
                    localStorage.setItem('identity', 'student')
                    this.$router.push({ path: '/studentWeb' })
                  }
                })
              }              
              break;
          }          
          return false;
        }
      })
    },
    oauthLogin: function(provider){ // 第三方登入
      let redirect_uri = window.location.origin + '/login';
      this.$api.BuildOauthUrl(provider, redirect_uri).then(res=>{
          window.location.href  = res
      })
    },
    SSOLogin: function(code){ // 快速登入
      this.$Spin.show(); //開啟加載畫面
      this.$api.SSOLogin(code).then( async res=>{
        this.$Spin.hide(); // 關閉加載畫面
          if(!res.error){
            // 登入大雲開始
            this.loginProcess(res, this.defaultSchool.code)
          } else {
            this.$Message.warning(this.$t('login.sse.error.text1'));
          }
      })
    },
    SEELink: function() { // 開啟SSE連結
      if(!this.sseSurvive){
        let url = this.config[this.srvAdr].coreAPIUrl

        let es = new EventSourcePolyfill(url+'/service/sse',{headers: {'X-Auth-Name': 'IES5'}});
        let _this = this;

        var closeSSE = function(){
          if(_this.sseSurvive) {
            es.close();
            _this.sseSurvive = false
          }
        }

        es.addEventListener('open', function (e) {
          _this.sseSurvive = true
        }, false);

        //取得登入網址
        es.addEventListener('message', function (e) {
          if (e.data) {
            let data = JSON.parse(e.data)
            
            if(data.sid) {
              let qrcodeURL = url + '/qrcode/login?sid=' + encodeURIComponent(data.sid, "utf-8") + '&info=' + encodeURIComponent(_this.$t('login.sse.text1'),"utf-8")
              _this.crtQrcode(qrcodeURL)
            } else if(data.code){
              closeSSE()
              _this.SSOLogin(data.code)
            }

          }
        }, false);

        // 錯誤
        es.addEventListener('error', function (e) {
          closeSSE()
        }, false);

        // 設定五分鐘後關閉連接
        setTimeout(() => {
          closeSSE()
        }, 300000);
      }
    },
    crtQrcode: function(url) { // 開啟QRCODE
      this.$nextTick(() => {
        if(this.joinQRcode == undefined){
          let qrcode = new QRCode('qrcode', {
            width: 200, // 设置宽度，单位像素
            height: 200, // 设置高度，单位像素
            text: url, // 设置二维码内容或跳转地址
          })
          this.joinQRcode = qrcode
        } else {
          this.joinQRcode.clear()
          this.joinQRcode.makeCode(url)
        }
      })
    },
    loginProcess: async function(item, schoolCode){ // 登入用function
      let result;

      await this.$api.login.loginIES(item, schoolCode).then( res => {
        result = res
      })
      console.log('////',result)
      //設定權限並登入
      User.login(result).then(res => {
        if(res) {
          this.saveUserCodes({
            TEAMModelId: result.id,
            name:result.name,
            schoolCode: result.defaultschool
          })
          this.$router.push({ path: '/studentWeb' })
        }
      })
    },
    saveUserCodes: function (res) {
		  this.$store.commit('setUserInfo',res)
	  },
    getSchools: function(){ // 取得學校清單
      let _this = this
      this.$api.getSchoolList().then( res =>{
        if(Array.isArray(res.schools) && res.schools.length > 0){
          res.schools.forEach(function(item){

            let isProvinceSame = _this.schoolList.find(function( val ){
              return val.province == item.province
            })

            if(isProvinceSame){

              let index = _this.schoolList.indexOf(isProvinceSame)
              _this.schoolList[index].schools.push({
                id: item.id,
                name: item.name,
              })
            } else {
              let data = {
                province: item.province,
                schools: [
                  {
                    id: item.id,
                    name: item.name,
                  }
                ]
              }

              _this.schoolList.push(data)

            }
          })
        }
      })
    },
    setLoginSchoolCode: function(){ // 設定預設的學校簡碼
      let schoolCode = this.$route.query.schoolcode == undefined ? '' : this.$route.query.schoolcode;
      if(schoolCode){
          this.$api.login.getSchoolName({schoolCode: schoolCode}).then( res => {
          this.defaultSchool.code = res.code
          this.defaultSchool.name = res.name
          this.studForm.schoolCode = this.defaultSchool.code
        })
      }
    },
    setDefSchool: function(){
      let defschool = sessionStorage.defaultSchool
      if(defschool){
        defschool = JSON.parse(decodeURIComponent(defschool), "utf-8")
        this.defaultSchool.code = defSchool.code
        this.defaultSchool.name = defSchool.name
      }      
    }
  }
}
</script>