<template>
    <div id="login">
        <div class="pb5">
            <img src="@/assets/images/denglu_bg.png" width="100%" height="200" />
        </div>
        <div class="plr30 bgc-fff" id="inpForm">
            <van-cell-group>
                <van-field v-if="accountLogin" type='tel' placeholder="账号" v-model="data.mobile" clearable class="mobile right-line">
                    <van-svg-icon slot="left-icon" icon-class="svg-shoujihao"/>
                </van-field>
                 <van-field v-else type='tel' placeholder="身份证号" v-model="data.idcord" clearable class="mobile right-line">
                    <van-svg-icon slot="left-icon" icon-class="svg-shoujihao"/>
                </van-field>
                <van-field  style="opacity: 0;height: 0;width: 0;margin: 0;overflow: hidden;padding: 0;">
                </van-field>
                <template v-if="passwordLogin">
                    <van-field  class="mima right-line" v-model="data.password" :type="passwordView.type" maxlength="16" placeholder="登录密码" @click-right-icon="passwordViewSet()">
                        <van-svg-icon slot="left-icon" icon-class="svg-mima" style="margin-top:2px;"/>
                        <van-svg-icon slot="right-icon" :icon-class="passwordView.icon"/>
                    </van-field>
                </template>
                <template  v-else>
                    <van-field v-model="data.msgCode" class="codeInp right-line" clearable @click-icon="msgCode=''" maxlength="10"  placeholder="短信验证码">
                        <van-svg-icon slot="left-icon" icon-class="svg-yanzhengma" style="margin-top:2px;"/>
                        <van-button round slot="button" size="small" :disabled="countdown > 0" @click="sendMobileCode" type="primary">
                            {{ countdown ? countdown + 's' +' 后重发': '发送验证码'}}
                        </van-button>
                    </van-field>
                </template>
                <div class="imgcodeInp" v-if="isNeedPictureCode=='1'">
                    <van-field v-model="data.code" class="right-line" clearable @click-icon="data.code=''" maxlength="10"  placeholder="图形验证码">
                        <van-svg-icon slot="left-icon" icon-class="svg-yanzhengma" style="margin-top:2px;"/>
                    </van-field>
                    <div class="right-div" @click="sendMobileImgCode">
                        <van-button v-if="!imgCode" :loading="imgLoading" class="no-border" type="e1e1e1" loading-text="获取中..." >图形验证码</van-button>
                        <img v-else :src="imgCode" width="100" height="45" class="c-border-rtb-45"/>
                    </div>
                </div>
            </van-cell-group>
            <div class="mt15 c-f14 c-17B3EC clearfix">
                <!-- <div class="textLeft">
                    <span v-if="passwordLogin" @click="passwordLogin=false" style="float:left;">验证码登录</span>
                    <span v-else @click="passwordLogin=true" style="float:left;">密码登录</span>
                </div>
                <div class="textCentre">
                    <div v-if="accountLogin" @click="accountLogin=false,data.mobile='',passwordLogin=true">身份证号登录</div>
                    <div v-else @click="accountLogin=true,data.idcord='',passwordLogin=true">账号登录</div>
                </div> -->
                <div class="textRight"  @click="goPage('/fotgetPassword')">忘记密码</div>
            </div>
            <!-- <div class="tips">
                <div>注：默认密码为身份证后六位</div>
            </div>  -->
            <div class="mt32">
                <van-button v-if="!loading" block round type="primary" @click="submit" class="">
                    登　录
                </van-button>
                <van-button v-else block round type="primary" class=""><van-loading class="login-loading" color="#ffffff"/>
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getPublicKey, login, imgCaptcha, sendCaptcha ,updLatLon} from "@/api/login";
import JSEncrypt from "@/utils/jsencrypt";
import ValidatorUtils from '@/utils/validator'
import store from "@/store";
import { setTimeout } from 'timers';
import residentApi from '@/api/residentApi'
import { getSign, getOpenidByCode} from "@/api/wx"

function GetRequest() {  
    let url = location.search; //获取url中"?"符后的字串
    let theRequest = {};
    let strs = []
    if (url.indexOf("?") != -1) {
        let str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

export default {
    name: "login",
    data() {
        return {
            openid: (this.user&&this.user.openid) || this.$route.query.openid,
            countdown: 0,
            // 验证对象
            validator: undefined,
            data: {
                password: "",
                mobile: "",
                code: "",
                msgCode: "",
                idcord:'',
            },
            rules: {
                mobile: [
                    { required: true, message: '请输入账号' },
                    // { pattern: /^[1][0-9]{10}$/, message: '请输入正确的手机号码' }
                ],
                idcord:[
                    { required: true, message: '请输入身份证号' },
                    { pattern: /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0]([0|1][0-9]|[2][0|1]))([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/, message: '请输入正确的身份证号' }
                ],
                password: [
                    { required: true, message: '请输入密码' }
                ],
                code: [{ required: true, message: "请输入验证码" },],
                msgCode: [{ required: true, message: "请输入短信验证码" },]
            },      
            passwordLogin: true, //true密码登录，false验证码登录
            accountLogin:true,  //true账号登录，false身份证登录
            isChangeUser: false,
            passwordView: {},
            passwordNotView: {
                type: "password",
                icon: "svg-biyan",
                value: false
            }, //闭眼
            password_view: { type: "text", icon: "svg-kaiyan", value: true }, //睁眼
            redirect: undefined,
            imgLoading:false,  //图形验证码加载状态
            imgCode:"",   //图形验证码
            imgKey: "",
            loading: false,
            isNeedPictureCode: false,
            lat:'',
            lng:''
        };
    },
    async created() {
        this.validator = new ValidatorUtils({
            rules: this.rules,
            data: this.data 
        })
        this.data = this.validator.Data
        this.openid = await this.fetchOpenid()
        this.initPage();
    },
    methods: {
        getPosition(vals) {
            this.lat = vals.lat
            this.lng = vals.lng
        },
      fetchOpenid() {
            let queryParam = GetRequest(),
                code = queryParam.code
            //微信授权过来的  取得到code
            if(code){
                return getOpenidByCode({
                    code: code
                }).then((res)=>{
                    if(res.status==200){
                        store.dispatch('SetLoginUser', {openid: res.obj})
                        
                        return Promise.resolve(res.obj)
                    } else {
                        vant.Toast('获取openid失败');
                        return Promise.reject()
                    }
                }).catch((err)=>{
                    vant.Toast('获取openid失败');
                    console.error(err)
                    return Promise.reject()
                })
            }
            
        },
        toRegister(){
            this.$router.push({path: "/register", query: this.$route.query})
        },
        async initPage() {
            //初始化登录页
            this.passwordView = this.passwordNotView;
            this.imgCaptcha()
        },
        passwordViewSet() {
            //设置密码显示
            var vm = this;
            if (vm.passwordView.value) {
                vm.passwordView = vm.passwordNotView;
            } else {
                vm.passwordView = vm.password_view;
            }
        },
        countdownSubtract() {
            //验证码
            if (this.countdown > 0) {
                setTimeout(() => {
                this.countdown -= 1;
                this.countdownSubtract();
                }, 1000);
            }
        },
        initData(){

        },
        goPage(url){
            this.$router.push({
                path:url
            });
        },
        //以下需对接
        sendMobileImgCode(){
            this.imgCode=""
            this.imgLoading=true
            this.imgCaptcha()
        },
        sendMobileCode() {
            this.validator.validate("mobile").then(() => {
                this.countdown = 60;
                this.countdownSubtract();
                sendCaptcha({
                    type: 1, // 1 登录
                    username: this.data.mobile?this.data.mobile:this.data.idcord,
                    client_id: this.$store.getters.clientId?this.$store.getters.clientId:process.env.VUE_APP_CLIENTID,
                    wxId: process.env.VUE_APP_WXID
                }).then((res) => {
                    if(res.status == 200) {
                        this.$toast("发送成功");
                    } else {
                        this.$toast("发送失败");
                    }
                })     
            }, (err) => {
                this.$toast(err[0].message)
            })
        },
        validate() {
            return this.validator.validate().then(() => {
                // 校验成功
            }, 
            (err) => {
                // 校验失败
                this.$toast(err[0].message)
                return Promise.reject(err)
            })
        },
        submit(){
            let rules = this.rules
            var crules
            if(this.passwordLogin) {
                crules = {
                    mobile: rules.mobile,
                    password: rules.password,
                }
            } else {
                crules = {
                    mobile: rules.mobile,
                    msgCode: rules.msgCode,
                }
            }
            if(this.accountLogin) {
               
            }else{
                crules = {
                    idcord: rules.idcord,
                    password: rules.password,
                }
            }
            if(this.isNeedPictureCode==1){
                crules.code = rules.code
            }
            this.validator.setRules(crules)
            this.validate().then(() => {
                if(this.passwordLogin) {
                    this.login(1)
                } else {
                    this.login(2)
                }
                if(this.accountLogin) {

                }else{
                    this.login(4) 
                }
            })      
        },
        redirectToLogin() {
            let appId = process.env.VUE_APP_APPID,
                protocol = window.location.protocol,
                host = window.location.host,
                redirctWxAuthUrl = encodeURIComponent(`${protocol}//${host}${process.env.VUE_APP_PRE_PATH}/login`),
                wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirctWxAuthUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
            
            location.replace(wxAuthUrl)
        },
        async login(type) {
            var that = this
            this.loading = true
            var p = {}
            if(type==1){
                var res 
                try{
                    res = await getPublicKey()
                } catch(e){
                    console.error(e)
                    this.loading=false
                    return
                }
                
                if (res && res.status == 200) {
                   
                    var encrypt = new JSEncrypt()
                    encrypt.setPublicKey(res.obj.publicKey)
                    p = {
                        client_id: this.$store.getters.clientId,
                        password: encrypt.encrypt(this.data.password),
                        username: this.data.mobile?this.data.mobile:this.data.idcord,
                        login_type: 3, // 1-平台管理员  2-医生登录  3-患者登录
                        key: this.imgKey,
                        text: this.data.code,
                        openid: this.openid,
                        clientType: "wx"
                    }

                } else {
                    this.loading = false
                    this.$toast('登录失败');
                    return
                }
            } else {
                p = {
                    client_id: this.$store.getters.clientId?this.$store.getters.clientId:process.env.VUE_APP_CLIENTID,
                    username: this.data.mobile?this.data.mobile:this.data.idcord,
                    login_type: 3, // 1-平台管理员  2-医生登录  3-患者登录
                    captcha: this.data.msgCode,
                    openid: this.openid,
                    clientType: "wx"
                }
            }
            p.wechatId = process.env.VUE_APP_WXID
            //小程序code
            p.appletCode = this.$route.query.appletCode||""

             let isApp = this.$route.query.isApp || this.isSupportHtml5Plus
             console.log(p, isApp)
            if(navigator.userAgent.toLowerCase().indexOf('micromessenger') !==-1) {
              if(!p.openid && !isApp) {
                this.redirectToLogin()
                return ;
              }
            }
            

            login(p).then(async result => {
                this.loading=false
                if (result.status == 200) {
                    result.obj.openid = result.obj.openid || this.openid
                    store.dispatch('SetLoginUser', result.obj)
                    try{
                      localStorage.removeItem("Medical-Care-Wx-Proxy-User")
                    }catch{

                    }
                    if(result.obj.archiveType==3){
                      let userAgent = {agent: result.obj.id}
                      localStorage.setItem("Medical-Care-Wx-Logined-User-Agent", JSON.stringify(userAgent))
                    }
                    let userInfo = await this.getPatientById(result.obj)
                    this.$toast.clear()
                    if(this.redirect){
                        this.$router.replace(decodeURIComponent(this.redirect))
                    } else {
                        updLatLon({
                            latLon:this.lat+","+this.lng,
                            patientId:this.user.id
                        }).then(res=>{
                            // console.log("保存定位成功")
                        })
                        if(userInfo.archiveType) {
                            this.$router.replace("/home")
                        } else {
                            this.$router.replace("/setRole")
                        }
                        
                    }
                } else {
                    this.$toast.clear()
                    this.$toast(result.status==1300? "验证码错误" : result.message);
                    if(result.status != 1300){
                        //非验证码错误时 刷新验证码
                        this.imgCaptcha()
                    }
                }
            })
            .catch(result => {
              this.$toast(result.message)
                this.loading=false
                if(result.status!=1300){
                    this.imgCaptcha()
                }
            })
        },
        imgCaptcha(){
            if(this.isNeedPictureCode!=1){
                return
            }
            imgCaptcha({}).then(data => {
                if(data.status==200){
                    this.imgCode = data.obj.image
                    this.imgKey = data.obj.key
                }
            })
        },
        async getPatientById(userInfo){
            var res = await residentApi.getPatientById({
                id: userInfo.id
            }).catch(err=>{
                console.error(err)
            })
            var userAgent = {
              id: res.obj.patient.id,
              uid: res.obj.patient.id,
              agent: res.obj.agentPatient?res.obj.agentPatient.id:''
            }
            res.obj.agentPatient?localStorage.setItem("Medical-Care-Wx-Proxy-User", JSON.stringify(res.obj.agentPatient)):''
            localStorage.setItem("Medical-Care-Wx-Logined-User-Agent", JSON.stringify(userAgent))
            userInfo = _.assignIn(userInfo, res.obj.patient)
            store.dispatch('SetLoginUser', userInfo)

            return userInfo
        }
    },
    watch: {
        $route: {
            handler: function(route) {
                this.redirect = route.query && route.query.redirect;
                this.openid = this.user.openid || (route.query && route.query.openid);

                if(route.query.loginType == 2){ // 2 验证码登录
                    this.passwordLogin = false
                    this.data.mobile = route.query.mobile
                }
                if(route.query.loginType == 4){ // 4 身份证号登录
                    this.accountLogin = false
                    this.data.idcord = route.query.idcord
                }
            },
            immediate: true
        }
    }
};
</script>

<style lang="scss">
#login .login-loading svg{
    color: #fff!important;
}
#login .van-button--normal{
    font-size: 16px;
}
#login .van-button--normal.no-border{
    border:none;
}
#login .van-button--primary{
    background: #17B3EC;
    border:none;
}
#login .van-button--normal.register-btn{
    border-color: #17B3EC;
    color: #17B3EC;
}


#login{
    // height: calc(100vh - 0px);
    // text-align: center;
    background: #ffffff;
    height: 100vh;
}
#login{
  .mima.van-cell{
      padding: 7px 15px;
  }

  svg{
    color:#999999;
    font-size:24px;
    margin-left: 10px;
    margin-right: 25px;
    margin-top: 2px;
  }
  .van-field__right-icon svg{
    color:#999999;
    font-size:20px;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 5px;
  }
  .van-loading__circular{
    margin-left: 0px;
  }
  #inpForm{
      [class*=van-hairline] {
        position:inherit;
      }
  }
.footer{
    width: 100%;
    // bottom: 20px;
    // position: absolute;
    text-align: center;
    font-size: 14px;
    color: #999999;
    padding-top: 30px;
}


.van-actionsheet{
    background-color: transparent;
}
/* 输入框 */
.van-cell{
    border-radius: 45px;
    border: 1px solid #e1e1e1;
    margin-top: 15px;
    padding: 7px 15px;
}
.van-field__control{
    font-size: 16px;
}
.van-field__icon .van-icon-password-view{
    font-size: 16px;
}
.van-field__icon .van-icon-clear{
    color:#e1e1e1;
    font-size: 16px;
}
.van-cell__left-icon {
    margin-left: 15px;
    margin-right: 30px;
    color:#999999;
    padding-top: 3px;
}
.van-cell input::-webkit-input-placeholder {
    /* placeholder颜色  */
    color: #999999;
    /* placeholder字体大小  */
    font-size: 16px;
}
.imgcodeInp{
  position:relative;
  .right-div{
    position:absolute;
    right: 0;
    top: 1px;
    .van-button{
      border-top-right-radius : 45px;
      border-bottom-right-radius : 45px;
      background:#e1e1e1;
      color:#999999;
      font-size:14px;      
    }
  }
}

.codeInp .van-button--small{
    padding: 0;
    background-color: #ffffff;
    color:#17B3EC;
    font-size: 14px;
    border: 1px solid #ffffff;
    height: 28px;
}
.codeInp .van-button--disabled {
    // background-color: #e1e1e1;
    // border: 1px solid #e1e1e1;
    color: #999999;
}
.mobile .van-cell__value,.imgcodeInp .van-cell__value{
  padding-top:3px;
}
// .van-checkbox__icon--checked .van-icon{
//     color: #fff;
//     border-color: #17B3EC;
//     background-color: #17B3EC;
//     line-height: 18px;
//     font-size: 14px;
// }
.right-line::before{
	position: absolute;
  top: 7px;
  left: 62px;
  width: 1px;
  height: 30px;
  content: "";
  background: #e1e1e1;
}
[class*=van-hairline]::after {
   border-top: 1px solid #e1e1e1;
}

  .van-cell:not(:last-child)::after {    
    -webkit-transform: initial;
    transform: initial;
    border-bottom: 0px solid #e1e1e1;
}
}
.sign{
    color: red;
    font-size: 13px;
    padding-top: 10px;
}
.clearfix{
    display: flex;
    justify-content: space-between;
}
.textLeft{
    width: 33.33%;
}
.textCentre{
    width: 33.33%;
    text-align: center;

}
.textRight{
    width: 100%;
    margin-right: 0px;
    text-align: right;

}
</style>
<style lang="scss">
#login{
    .tips{
        text-align: left;
        margin-top:10px;
        font-size: 14px;
        color: #ff0000;
        line-height: 20px;
    }
    .van-checkbox{
        display: inline-flex;
    }
}
</style>