<template>
    <div>
        <div class="header">
            <div class="w-main ui-grid ui-grid-middle">
                <div class="ui-col-1"><img src="../assets/images/logo_img.png"></div>
                <!-- <div class="ui-col-0 c-t-center mr30 c-position-r">
                    <img src="../assets/images/doctor_wx.jpg" class="qrcode qrcode1" :class="{ 'active': clickImgId==1 }" @click="clickImg(1)">
                    <p class="mt5 c-f12">医生微信智能助手</p>
                </div>
                <div class="ui-col-0 c-t-center c-position-r">
                    <img src="../assets/images/iHealth_app.png" class="qrcode qrcode2" :class="{ 'active': clickImgId==2 }" @click="clickImg(2)">
                    <p class="mt5 c-f12">厦门i健康APP</p>
                </div> -->
            </div>
        </div>
        <div id="head_wrap" class="c-f14">
            <div class="w-main c-position-r" style="height: 500px;">
                <div class="form-panel">
                    <div class="c-f20 c-t-center mt10 pb20">平台登录</div>
                    <!-- <div>
                        <ul class="c-lab-mor c-f14">
                            <li v-bind:class="{ 'curr': loginMode==2 }" v-on:click="changeMode(2, $event)">
                                <a href="javascript:void(0)">验证码登录</a>
                            </li>
                            <li v-bind:class="{ 'curr': loginMode==1 }">
                                <a href="javascript:void(0)" v-on:click="changeMode(1, $event)">密码登录</a>
                            </li>
                        </ul>
                    </div> -->
                    <form class="pl45 pr45" v-show="loginMode==1" data-vv-scope="form-1">
                        <div class="input-group width-100 mt14">
                            <label>
                                <input type="text" class="form-control width-100 c-f14" maxlength="11" placeholder="请输入手机号" :class="{'input': true, 'is-danger': judgeOnblur }" name="phone1" data-vv-as="手机号" v-model="phone" @blur="validPhone()">
                            </label>
                            <div class="error-warp" @click="focusInput($event)">
                                <i v-show="judgeOnblur" class="fa fa-warning"></i>
                                <span v-show="judgeOnblur" class="help is-danger">手机号无效</span>
                            </div>
                        </div>
                        <div class="input-group width-100 mt14">
                            <label>
                                <input type="password" class="form-control width-100 c-f14" placeholder="请输入密码" :class="{'input': true, 'is-danger': errors.has('form-1.password') }" name="password" data-vv-as="密码" v-model="password" v-validate="'required'">
                            </label>
                            <div class="error-warp" @click="focusInput($event)">
                                <i v-show="errors.has('form-1.password')" class="fa fa-warning"></i>
                                <span v-show="errors.has('form-1.password')" class="help is-danger">{{ errors.first('form-1.password') }}</span>
                            </div>
                        </div>
                    </form>

                    <form class="pl45 pr45" v-show="loginMode==2" data-vv-scope="form-2">
                        <div class="input-group width-100 mt14">
                            <label>
                                <input type="text" class="form-control width-100 c-f14" maxlength="11" placeholder="请输入手机号" :class="{'input': true, 'is-danger': judgeOnblur }" name="phone" data-vv-as="手机号" v-model="phone" @input="validPhone()">
                            </label>
                            
                            <div class="error-warp" @click="focusInput($event)">
                                <i v-show="judgeOnblur" class="fa fa-warning"></i>
                                <span v-show="judgeOnblur" class="help is-danger">手机号无效</span>
                            </div>
                        </div>
                        <div class="input-group width-100 mt14 yzmbox">
                            <label class="c-display-ib c-vam">
                                <input type="text" class="form-control width-100 c-f14  c-width-190" placeholder="请输入验证码" :class="{'input': true, 'is-danger': errors.has('form-2.captcha') }" name="captcha" data-vv-as="验证码" v-model="captcha" v-validate="'required'">
                            </label>
                            <a id="sendCaptchaBtn" href="javascript:;" class="fsyzm c-vam" :class="{'c-btn-disable': disableSendCaptcha}" @click="sendCaptcha()">{{sendTip}}</a>
                            <!-- <a id="sendCaptchaBtn" href="javascript:;" class="c-btn c-vam c-width-90 c-f14" :class="{'c-btn-disable': disableSendCaptcha}" @click="sendCaptcha()">{{sendTip}}</a> -->
                            <div class="error-warp" @click="focusInput($event)">
                                <i v-show="errors.has('form-2.captcha')" class="fa fa-warning fa-yzm"></i>
                                <span v-show="errors.has('form-2.captcha')" class="help is-danger">{{ errors.first('form-2.captcha') }}</span>
                            </div>
                        </div>
                    </form>
                    <!-- <div class="c-f14 pl70 pr70 mt10" v-show="loginMode==1">
                        <label class="input-group-checkbox c-333">
                            <div class="input-group-pack">
                                <input type="checkbox" v-model="remPsd">
                                <span class="tick"></span>
                            </div>
                            记住密码
                        </label>
                        <label class="input-group-checkbox c-333">
                            <div class="input-group-pack">
                                <input type="checkbox" v-model="autoLogin">
                                <span class="tick"></span>
                            </div>
                            自动登录
                        </label>
                    </div> -->
                    <div class="pl45 pr45 mt16 mb18" v-show="loginMode==1">
                        <a id="submitBtn" href="javascript:;" class="c-btn-12b7f5 c-btn-full" @click="login()">登录</a>
                    </div>
                    <div class="pl45 pr45 mt24 mb30" v-show="loginMode==2">
                        <a id="submitBtn" href="javascript:;" class="c-btn-12b7f5 c-btn-full" @click="login()">登录</a>
                    </div>
                </div>
        
            </div>
         </div>   

        
        <div class="w-main c-t-center c-666" style="margin-top: 100px;">
            <div>版权所有：厦门市卫生和计划生育委员会</div>
            <div>技术支持：健康之路无边界(厦门)医疗科技有限公司</div>
        </div>
        <!--<div class="error-message mt6" v-show="loginMode==1">-->
            <!-- <div v-show="errorTx==1">
                <i v-show="judgeOnblur" class="fa fa-warning"></i>
                <span class="help is-danger">手机号无效</span>
            </div> -->
        <!--</div> -->
        
    </div>
</template>

<script>
import Vue from 'vue'
import Validate from '../assets/js/input-validate'
import RSAUtils from '../assets/js/vendor/RSAUtils'
import LoginService from '../assets/js/apis/api-login'
import getSessionsService from '../assets/js/apis/api-im'
import storage from '../assets/js/storage'
import $ from 'jquery'

Vue.use(Validate, {
    locale: 'zh_CN'
})

let timerCaptcha = null

export default {
    props: [],
    components: {},
    data() {
        return {
            loginMode: 1,               // 登录模式：1、密码登录 2、验证码登录
            autoLogin: false,           // 是否自动登录
            autoLaunch: false,          // 是否开机自启动
            remPsd: false,              // 是否记住密码
            phone: '',                   // 手机号
            password: '',                // 登录密码
            captcha: '',                 // 手机验证码
            sendTip: '发送验证码',       // 控制“发送验证码”按钮上的显示文本
            seconds: 120,                // 控制“发送验证码”按钮再次可用间隔时间60s
            disableSendCaptcha: true,    // 控制“发送验证码”按钮是否可用
            judgeOnblur: false,
            clickImgId: 0 // 标记点击二维码的index
        }
    },
    computed: {
    },
    mounted() {
    },
    methods: {
        // 如果登录方式变更，则清空密码及验证码，但保留手机号
        changeMode(loginMode) {
            if (this.loginMode === loginMode) {
                return
            }
            this.loginMode = loginMode
            this.password = ''
            this.captcha = ''
            // this.errors.clear(`form-${loginMode}`);
        },
        // 获取验证码
        async getCaptcha() {
            let result
            try {
                result = await LoginService.getCaptchaAjax(this.phone)
            } catch (error) {
                this.$toast('连接超时请检查网络')
            }
            if (result.status === 200) {
                this.sendTip = (this.seconds--) + 's'
                timerCaptcha = setInterval(() => {
                    this.sendTip = (this.seconds--) + 's'
                    // 计时器完成120s计时
                    if (this.seconds < 1 || result.data.status === -1) {
                        if (result.data.status) {
                            this.$toast(result.data.msg)
                        }
                        clearInterval(timerCaptcha)
                        timerCaptcha = null
                        this.sendTip = '发送验证码'
                        this.disableSendCaptcha = false
                        this.seconds = 120
                    }
                }, 1000)
            } else {
                this.$toast(result.msg || '获取失败')
                // 还原'发送验证码'按钮的可用状态
                this.sendTip = '发送验证码'
                this.disableSendCaptcha = false
            }
        },
        sendCaptcha() {
            // 防止多次暴力点击
            if (this.disableSendCaptcha) {
                return
            }
            this.disableSendCaptcha = true
            this.getCaptcha()
        },
        async validPhone() {
            // ES7 async/await 语法，等待验证完成返回结果，再往后执行该函数内的后续逻辑
            // let isValid = await this.$validator.validate('phone', this.phone, 'form-2')
            let isValid = this.phone.length === 11 && /^((13|14|15|17|18|19)[0-9]{1}\d{8})$/.test(this.phone)
            this.judgeOnblur = !isValid
            // this.errorTx = 1
            // 如果手机号验证通过，计时器处于初始状态，则'发送验证码'按钮可用，反之亦反
            if (isValid && this.seconds === 120) {
                this.disableSendCaptcha = false
            } else {
                this.disableSendCaptcha = true
            }
        },
        closeWindow() {
            // 关闭登录窗口
            // this.$electron.ipcRenderer.send('login:close')
        },
        async submitForPassword() {
            let pubKeyRes,
                result,
                data,
                publicKey = '',
                encryedPwd = '',
                loginRes
            try {
                pubKeyRes = await LoginService.getPublicKey()
                result = pubKeyRes.data
                data = result.data
            } catch (error) {
                this.$loading.close()
                this.$toast('连接超时请检查网络')
            }
            if (pubKeyRes.status === 200) {
                publicKey = RSAUtils.getKeyPair(data.exponent, '', data.modulus)
                if (publicKey) {
                    encryedPwd = RSAUtils.encryStr(publicKey, this.password)
                    loginRes = await LoginService.login(this.phone, '', encryedPwd, 4)
                    this.handleLoginRes(loginRes)
                } else {
                }
            } else {
                this.$loading.close()
                this.$toast(publicKey.msg || '公钥获取失败请重试')
            }
        },
        async submitForCaptcha() {
            let loginRes
            loginRes = await LoginService.login(this.phone, this.captcha, '', 4)
            this.handleLoginRes(loginRes)
        },
        async getBaseInfo() {
            let baseInfo = await LoginService.getBaseInfo()
            if (baseInfo.data.status === 200) {
                return baseInfo
            } else {
                this.$loading.close()
                this.$toast('登录失效，请重新登录')
            }
        },
        async getAdminTeams(code) {
            let adminTeams = await LoginService.getAdminTeams(code)
            if (adminTeams.status === 200) {
                return adminTeams
            } else {
                this.$loading.close()
                this.$toast('登录失效，请重新登录')
            }
        },
        async loginIm(userId) {
            let res = await getSessionsService.Users.login(userId, 'pcimbana', 'pcbanimb', 4)
            if (res.status === 200) {
                // 关闭登录提示框
                this.$loading.close()
                // this.$electron.ipcRenderer.send('login:loginSubmit:success')
            } else {
                this.$loading.close()
                this.$toast('im登录失败')
            }
        },
        async handleLoginRes(res, storeData) {
            console.log(storeData)
            let result,
                data
            if (res) {
                result = res.data
                data = result.data
            } else {
                result = {
                    status: 200
                }
                data = {
                    id: storeData.id,
                    uid: storeData.uid,
                    token: storeData.token,
                    currentUserRole: storeData.currentUserRole,
                    level: storeData.level,
                    photo: storeData.photo
                }
            }

            let baseInfoResponse = null,
                baseInfoResult = null,
                baseInfo = null,
                doctorInfo = null

            let adminTeamResponse = null,
                adminTeamResult = null,
                adminTeams = null

            if (result.status === 200) {
                storage.setItem(storage.API_LOGIN_DOCTOR, data)

                baseInfoResponse = await this.getBaseInfo()
                baseInfoResult = baseInfoResponse.data
                baseInfo = baseInfoResult.data
                adminTeamResponse = await this.getAdminTeams(baseInfo.uid ? baseInfo.uid : baseInfo.code)
                adminTeamResult = adminTeamResponse.data
                adminTeams = adminTeamResult.data
                doctorInfo = Object.assign({}, data, baseInfo, {
                    adminTeams: adminTeams
                })
                storage.setItem(storage.API_LOGIN_DOCTOR, doctorInfo)
                this.loginIm(doctorInfo.uid)

                if ((this.remPsd || this.autoLogin) && this.password !== '') { // 储存信息下次自动登录
                    if (this.autoLogin) {
                        // this.$electron.ipcRenderer.send('app:tokenLogin', {
                        //     id: data.id,
                        //     uid: data.uid,
                        //     token: data.token,
                        //     remtoken: 'remtoken',
                        //     currentUserRole: data.currentUserRole,
                        //     level: data.level,
                        //     photo: data.photo
                        // })
                    } else {
                        // this.$electron.ipcRenderer.send('app:clearToken')
                    }
                    if (this.remPsd) {
                        // this.$electron.ipcRenderer.send('app:autoLoginData', {
                        //     phone: this.phone,
                        //     password: this.password,
                        //     rempsd: 'rempsd'
                        // })
                    } else {
                        // this.$electron.ipcRenderer.send('app:clearPsd')
                    }
                } else { // 清除自动登录信息
                    // this.$electron.ipcRenderer.send('app:clearLoginData')
                    this.$loading.close()
                    if(res.data.data.doctorType == "1") {
                        this.$router.replace("/specialist-message")
                    } else{
                        this.$router.replace("/message")
                    }
                }
            } else {
                // 登录失败错误提醒
                this.$loading.close()
                this.$toast(result.msg || '登录失败')
            }
        },
        login() {
            // 根据选择的登录方式进行输入校验
            // let scope = `form-${this.loginMode}`
            // this.$validator.validateAll(scope).then(result => {
            //     if (result) {
            //         this.$loading('登录中...')
            //          // this.$electron.ipcRenderer.send('login:loginSubmit:success'
            //         switch (this.loginMode) {
            //             case 1:
            //                 this.submitForPassword()
            //                 break
            //             case 2:
            //                 this.submitForCaptcha()
            //                 break
            //         }
            //     }
            // })
            let scope = `form-${this.loginMode}`
            this.$validator.validateAll(scope).then(result =>{
                if(result){
                    this.$loading('登录中...')
                    if(this.password != this.phone.substr(-6)){
                        this.$loading.close()
                        this.$toast('请输入正确的密码')
                        return false;
                    }
                    let data = {
                        id: '',
                        uid:  this.phone, //'rll201703150333', //
                        token: '',
                        level: '1',
                        photo: ''
                    }
                    storage.setItem(storage.API_LOGIN_DOCTOR, data)
                    // this.loginIm(this.phone)
                    this.$loading.close()
                    this.$router.replace("/")
                }
            })
        },
        focusInput(event) {
            $(event.target).closest('.input-group').find('input').focus()
        },
        changeAutoLaunch() {
            this.$electron.ipcRenderer.send('app:autoLaunch', this.autoLaunch)
        },
        clickImg(index){
            if(this.clickImgId == index){
                this.clickImgId = 0;
            }else{
                this.clickImgId = index;
            }
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import '../assets/sass/tabs';

a,
label,
input,
button {
    -webkit-user-select: none;
    -webkit-app-region: no-drag;
}
.w-main{
    width: 1000px;
    margin: 0 auto;
    height: 120px;
}
.qrcode{
    width: 56px;
    height: 56px;
    margin-top: 10px;
}
.qrcode.active{
    position: absolute;
    height: 190px;
    width: 190px;
    top: -44px;
    z-index: 2;
}
.qrcode1.active{
    right: 0;
}
.qrcode2.active{
    left: 0;
}
.form-panel{
    width: 380px;
    height: 320px;
    background-color: #ffffff;
    border-radius: 10px;
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
}
.c-display-ib {
    display: inline-block;
}

.c-vam {
    vertical-align: middle
}

.c-width-190 {
    width: 190px;
}

.c-width-90 {
    width: 90px;
}

.c-btn-12b7f5 {
    background-color: #12b7f5;
}

.c-lab-mor>li:first-of-type::after {
    content: '';
    display: block;
    // width: 2px;
    // height: 30px;
    background: #d7dce6;
    position: absolute;
    right: 0;
    top: 15px;
}

.c-lab-mor { 
 width: 90%;
 margin-left: 5%;
 margin-right: 5%;
 height: 46px;
}
.c-lab-mor li {
    -webkit-box-flex: 1;
    height: 46px;
    line-height: 50px;
}

.input.is-danger,
.textarea.is-danger {
    border-color: #ff3860;
}

.input-group {
    position: relative;
    height: 30px;
}

.input-group .form-control,
.input-group label .form-control,
.input-group label .form-select,
.input-group label .form-textarea {
    border-radius: 2px;
}
.input-group .form-control{height: 1.5rem}
.input-group-checkbox .input-group-pack .tick {
    background: #12b7f5;
    margin: .15rem 0 0 .16rem;
}

.input-group-checkbox .input-group-pack .tick:after {
    background: #12b7f5;
}
.input-group-checkbox .input-group-pack{
    width: .7rem;
    height: .7rem;
    border-radius: 0;
}

#submitBtn,
#sendCaptchaBtn {
    border-radius: 2px;
    -webkit-user-select: none;
}

#sendCaptchaBtn {
    border: .05rem solid #e1e1e1;
    color: #12b7f5;
    background: #fff;
    border-left: none;
}

.c-btn-disable {
    pointer-events: none;
}

#sendCaptchaBtn.c-btn-disable {
    background: #f8f8f8;
    color: #323232;
}

.input-group-checkbox {
    color: #333;
    margin-right: 1.3rem;
}

.error-warp {
    // position: absolute;
    left: 0;
    bottom: .3rem;
    color: #ff3860;
    width: 100%;
    // text-align: right;
    padding-right: 15px;
    height: 21px;
}

#forgetPassword {
    color: #999999;
}

#sendCaptchaBtn {
    padding-left: 12px;
    padding-right: 12px;
}
.error-message{
    width: 100%;
    height: 34px;
    overflow: hidden;
    background-color: #fafaeb;
    color: #666666;
    font-size: 12px;
    line-height: 34px;
}

.c-lab-mor li.curr:before{ content:''; display:block; width:56%; height:.15rem; background:#12b7f5; position:absolute; left:23%; bottom:-1px;}
.c-lab-mor li a{color: #323232}
.c-lab-mor li.curr a{color: #12b7f5;}
.pl70{padding-left: 3.5rem}
.pr70{padding-right: 3.5rem}
.c-f14{font-size: .7rem}
.mt14{margin-top: .7rem}
.mt16{margin-top: .8rem}
.mb18{margin-bottom: .9rem;}
.f10{font-size: .5rem;}
.mt6{margin-top:.3rem}
.mt24{margin-top:1.2rem;}
.mb30{margin-bottom: 1.5rem;}
.f10{color: #909090;width: 300px;margin: 0 auto;text-align: center;}
.fsyzm{
    padding-top: 5px;
    padding-bottom: 5px;
    display: inline-block;
    font-size: .7rem;
    width: 98px;
    height: 1.5rem;
    text-align: center;
}
#head_wrap {
    width: 100%;
    height: 500px;
    background-image: url(../assets/images/bg_img.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}
#head_wrap img{
    height: 68px;
    margin: 34px 105px;
}
</style>
