<style lang="less" scoped>
@import "./Teacher.less";
.loginDiv {
    background: rgba(75, 112, 136, 0.5);
    border-radius: 20px;
    overflow: hidden;
    margin-top: -100px;
}
.left-box {
    padding: 0px 55px;
    height: 400px;
    display: flex;
    align-items: center;
    box-shadow: 2px 0px 15px 0px rgba(75, 113, 136, 0.9);
}
.right-box {
    padding: 40px 150px;
    width: 600px;
    height: 400px;
    box-shadow: -2px 0px 15px 0px rgba(75, 113, 136, 0.9);
}
.teacher-login-title {
    color: white;
    font-size: 42px;
    text-align: center;
}
.teacher-login-decr {
    color: white;
    font-size: 18px;
    text-align: center;
    font-weight: 200;
}
.loginForm {
    margin: auto;
    margin-top: 30px;
    width: 300px;
}
.formItem {
    margin-bottom: 8px;
}
.form-bottom {
    color: white;
    font-size: 12px;
}
.form-bottom-link {
    float: right;
    margin-left: 10px;
}
.qrcode-login {
    cursor: pointer;
}
.other-login-box {
    display: flex;
    margin-top: 25px;
}
.other-login-item {
    width: 50%;
    color: white;
    text-align: center;
    cursor: pointer;
}
.other-login-icon {
    font-size: 50px;
    display: block;
}
</style>

<style lang="less">
.login-input-box .ivu-input {
    border-radius: 25px;
    line-height: 35px;
    height: 35px;
    padding: 0px 15px;
}
.login-input-box .ivu-input-prefix i,
.login-input-box .ivu-input-suffix i {
    line-height: 35px;
}
.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="left-box">
            <!-- 这张图片需要裁剪顶部 -->
            <img src="@/assets/login/3-2.png" class="teacher-login-img" style="margin-top:-30px">
        </div>
        <div class="right-box" v-show="!qrloginFlag">
            <p class="teacher-login-title">醍摩豆账号登录</p>
            <p class="teacher-login-decr">系统管理者、教师、学生与家长登录</p>
            <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" class="login-input-box" v-model="loginForm.id" :placeholder="$t('login.placeholder.id')" />
                </FormItem>
                <FormItem class="formItem" prop="pass">
                    <Input element-id="tmdpw" class="login-input-box" 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>
            <p class="form-bottom">
                <span class="qrcode-login" @click="chgLoginType()">
                    <Icon size="14" custom="iconfont icon-qr-code" style="vertical-align: text-bottom;" />
                    {{ $t('login.link.QRLogin') }}
                </span>
                <router-link to="/regist" class="form-bottom-link">
                    {{$t('login.link.regist')}}
                </router-link>
                <router-link to="/forgotpw" href="" class="form-bottom-link">
                    {{$t('login.link.forgetPsw')}}
                </router-link>
            </p>
            <div class="other-login-box">
                <div class="other-login-item" @click="oauthLogin('facebook')">
                    <Icon type="logo-facebook" class="other-login-icon" />
                    <p class="other-login-text">Facebook</p>
                </div>
                <div class="other-login-item" v-if="!(srvAdr == 'Global')" @click="oauthLogin('wechat')">
                    <Icon custom="iconfont icon-wechat" class="other-login-icon" />
                    <p class="other-login-text">或使用第三方平台登录</p>
                </div>
            </div>
        </div>
        <div class="right-box" v-show="qrloginFlag">
            <div style="width:fit-content;margin: auto;">
                <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 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">
                            <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="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/teacherIcon.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  class="icon" @click="oauthLogin('facebook')">
                <img v-if="!(srvAdr == 'China')" 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> -->
    </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 = ''
            }
        };
        return {
            qrloginFlag: false,
            loginForm: {
                id: '',
                pass: '',
            },
            loginRule: {
                id: [
                    { validator: validateID, trigger: 'blur' },
                ],
                pass: [
                    { validator: validatePW, trigger: 'blur' },
                ]
            },
            loginErrText: '',
            schoolErrText: '',
            userOauth: {        // 社群帳號
                code: '',
                state: ''
            },
            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
        }
    },
    created() {
        // 此頁面為老師頁面
        localStorage.setItem('identity', 'teacher')

        // 取得學校設定簡碼
        this.setDefSchool()
    },
    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
                    // 詢問帳號是否有效
                    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)
                    }
                }
            })
        },
        oauthLogin: function (provider) { // 第三方登入
            let redirect_uri = window.location.origin + '/login';
            this.$api.BuildOauthUrl(provider, redirect_uri).then(res => {
                window.location.href = res
            })
        },
        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: '/home' })
                }
            })
        },
        saveUserCodes: function (res) {
            this.$store.commit('setUserInfo', res)
        },
        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
            }
        },
        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'));
                }
            })
        },
    }
}
</script>