<template>
  <div class="mianBox" >
    <el-form class="login-form" auto-complete="on"  ref="loginForm" :model="loginForm" :rules="loginRules" v-if="login" :class="login?'opa1':'opa0'">
      <img src="../../assets/image/login/login.png" alt="" class="login">
      <el-form-item prop="username" width="460px">
        <el-input v-model="loginForm.username"
          ref="username"
          placeholder="请输入用户名"
          name="username"
          @keyup.enter.native="login_info()"
          type="text" auto-complete="off" >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password" style="position: relative;width:100%">
        <el-input
          class="inputs"
          ref="password"
          placeholder="请输入密码"
          name="password"
          @keyup.enter.native="login_info()"
          :type="passwordtxt"
          v-model="loginForm.password"
         >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          <svg-icon slot="prefix" icon-class="eye"  class="el-input__icon input-icon eye"    @click="eyeTab" v-show="passwordtxt =='password'" />
          <svg-icon slot="prefix" icon-class="eye-open"  class="el-input__icon input-icon  eye"   @click="eyeTab" v-show="passwordtxt =='text'" />
        </el-input>
      </el-form-item>
      <!-- <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item> -->
      <el-checkbox v-model="loginForm.rememberMe"  style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-button
        type="primary"
        @click.native.prevent="login_info()"
        @keyup.enter = "login_info()"
        >
        <span v-if="!loading" >登 录</span>
        <span v-else>登 录 中...</span></el-button
      >
    </el-form>
    <van-loading
      size="24px"
      v-if="loading"
      color="#fff"
      vertical
      style="z-index: 2; position: fixed; top: 40%; left: 0; right: 0"
      >登录中...</van-loading
    >
    <van-overlay :show="loading" style="z-index: 1; position: fixed;background-color: rgba(0,0,0,0.6);" />
  </div>
</template>
<script>
import { Toast } from "vant";
import axios from "axios";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '../../utils/jsencrypt';
export default {
  data() {
    return {
      login:false,
      loading:false,
      passwordtxt:"password",
      codeUrl: "",
      cookiePassword: "",
      show_num:[],
      // 验证码开关
        // captchaOnOff: true,
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      appid:"wxd64360a4b8c50006",
      secret:"b758e45c89162542610509dafd9db7c3",
      code:undefined,
    };
  },
  mounted() {

    document.title = '中国东信智慧园区'
    Cookies.set("openid57",'o5P6I5tLj-TjrK7leWUT8EFmTCa4') //本地测试
    if(Cookies.get('rememberMe57')){
      this.loginForm.rememberMe = Boolean(Cookies.get('rememberMe57'))
    }
    if(Cookies.get("username57")){
      this.loginForm.username = Cookies.get("username57")
    }
    if(Cookies.get("password57")){
      this.loginForm.password = decrypt(Cookies.get("password57"))
    }
    if(Cookies.get("openid57")){
      if(Cookies.get("username57") && Cookies.get("password57")){
        this.login_info()
        this.login = false
      }else{
        this.login = true
      }
    }else{
      this.login = true
      let url = window.location.href
      if(url.indexOf("?code")>0){
        let code = this.getRequest("code")
        this.wx_openid(code)
      }else{
        this.wx_login()
      }
    }
    
  },
  methods: {
    //获取url指定参数
    getRequest(parName){
       var str=parName.toLowerCase()+"=";
       var gvalue="";
       var HREF=location.href;
       var upperHREF=location.href.toLowerCase();
       if(upperHREF.indexOf(str)>0) {
         gvalue=HREF.substring(upperHREF.indexOf(str)+str.length,upperHREF.length);
         if(gvalue.indexOf('&')>0)gvalue=gvalue.substring(0,gvalue.indexOf('&'));
         if(gvalue.indexOf("#")>0)gvalue=gvalue.split("#")[0];
         gvalue  =  decodeURIComponent(gvalue)
       }
       return gvalue;
     },
    wx_login(){//微信拉起授权获取code
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd64360a4b8c50006&redirect_uri=https://smartpark.caih.com/vuepay&response_type=code&scope=snsapi_base&state=123`
      //获取openid
      //https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd64360a4b8c50006&secret=b758e45c89162542610509dafd9db7c3&code=021Ye8Ha1jvNXC0ckiJa1JtKPF2Ye8Hp&grant_type=authorization_code
    },
    wx_openid(code){//获取openid
      axios.get('/offOpenId' + '?code=' + code, {
        code:code
      }).then(res => {
        if(res.data.data){
          Cookies.set("openid57",res.data.data, { expires: 300 })
        }
      })
    },
    eyeTab(){//密码显示开关
      if(this.passwordtxt == "password"){
        this.passwordtxt = "text"
      }else{
        this.passwordtxt = "password"
      }
    },
    // getCode() {//获取验证码
    //   getCodeImg().then(res => {
    //     this.codeUrl = "data:image/gif;base64," + res.data.img;
    //     this.loginForm.uuid = res.data.uuid;
    //   });
    // },
    getCookie() {//缓存数据
      const username = Cookies.get("username57");
      const password = Cookies.get("password57");
      const rememberMe = Cookies.get('rememberMe57')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    login_info() {
      if(Cookies.get("openid57") && Cookies.get("username57") && Cookies.get("password57")){
        //window.location.href = "https://smartpark.caih.com/vuepay/#/home"
        this.$router.push({ path: `/home`}) 
      }else{
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            axios.get(`https://smartpark.caih.com/zkxt/api/thirdparty/v1/user/appLogin?name=${this.loginForm.username}&pass=${this.loginForm.password}`).then(res => {
              if (res?.data?.data?.data?.cipher) {
                let data = res.data.data.data
                //人员种类(00-正式人员、01-外协单位、02-租户)
                if(data.user.dmUser.type == "00"){
                  //Toast('请使用"中国东信APP查看功能"')
                  if(data.user.dmUser.status == false){
                    Toast("离职人员,暂无权限")
                    return
                  }else{
                    localStorage.setItem("cipher57",data.cipher)
                    localStorage.setItem("classify","2")
                    Cookies.set("username57", this.loginForm.username, { expires: 300 });
                    Cookies.set("rememberMe57", this.loginForm.rememberMe, { expires: 300 });
                    Cookies.set("password57", encrypt(this.loginForm.password), { expires: 300 });
                    Cookies.set("portrait57", data.user.dmUser.faceid, { expires: 300 });
                    Cookies.set("userId57", data.userId, { expires: 300 });
                    Cookies.set("token57", data.token, { expires: 300 });
                    Cookies.set("nonce57", data.nonce, { expires: 300 });
                    Cookies.set("timestamp57", data.timestamp, { expires: 300 });
                    Cookies.set("nickName57", data.user.nickName, { expires: 300 });
                    Cookies.set("dept57", data.user.dept.name, { expires: 300 });
                    Cookies.set("phone57", data.user.dmUser.contacts, { expires: 300 });
                    Cookies.set("people57", 0, { expires: 300 });
                    axios.put('/dxtop/staff', {
                      id:data.userId,
                      openId:Cookies.get("openid57")
                    })
                    setTimeout(()=>{
                      this.$router.push({ path: `/home`}) 
                      //window.location.href = "https://smartpark.caih.com/vuepay/#/home"
                    },200)
                  }

                }else if(data.user.dmUser.type == "01"){
                  if(data.user.dmUser.status == false){
                    Toast("离职人员,暂无权限")
                    return
                  }else{
                    
                    localStorage.setItem("cipher57",data.cipher)
                    localStorage.setItem("classify","1")
                    Cookies.set("username57", this.loginForm.username, { expires: 300 });
                    Cookies.set("rememberMe57", this.loginForm.rememberMe, { expires: 300 });
                    Cookies.set("password57", encrypt(this.loginForm.password), { expires: 300 });
                    Cookies.set("portrait57", data.user.dmUser.faceid, { expires: 300 });
                    Cookies.set("userId57", data.userId, { expires: 300 });
                    Cookies.set("token57", data.token, { expires: 300 });
                    Cookies.set("nonce57", data.nonce, { expires: 300 });
                    Cookies.set("timestamp57", data.timestamp, { expires: 300 });
                    Cookies.set("nickName57", data.user.nickName, { expires: 300 });
                    Cookies.set("dept57", data.user.dept.name, { expires: 300 });
                    Cookies.set("phone57", data.user.dmUser.contacts, { expires: 300 });
                    Cookies.set("people57", 1, { expires: 300 });
                    
                    axios.put('/dxtop/staff', {
                      id:data.userId,
                      openId:Cookies.get("openid57")
                    })
                    setTimeout(()=>{
                      this.$router.push({ path: `/home`}) 
                      //window.location.href = "https://smartpark.caih.com/vuepay/#/home"
                    },200)
                    
                  }
                }else if(data.user.dmUser.type == "02"){
                  Toast("暂无权限")
                }else{

                }
              } 
            }).catch(err =>{
              Toast(err.response.data.message)
            })
            setTimeout(()=>{
              this.loading = false
            },2000)
          }
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.mianBox{
    color: #000;
    position: fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
}
.opa1{
  opacity: 1;
}
.opa0{
  opacity: 0;
}
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 90%;
  position: absolute;
  top:8%;
  left:5%;
  .login{
    width:60%;
    margin:10% 20%;
  }
  .el-form-item__content{
    height:40px;
  }
  .login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
  }
  .login-code {
    width: 33%;
    height: 38px;
    float: right;
    margin-top:-2px;
    text-align: right;
    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
  .login-code-img {
    height: 38px;
  }

  .el-button--primary{
    width:100%;
    margin-top:10px;
    color: #fff;
    background-color: rgba(242, 46, 60, 1);;
    border-color: rgba(242, 46, 60, 1);;
    border-radius: 4px;
  }

  .eye{
    position: absolute;
    top:12px;
    
  }
  @media screen and (min-width: 300px) and (max-width: 330px){
    .eye{
      left:250px;
    }
  }
  @media screen and (min-width: 340px) and (max-width: 365px){
    .eye{
      left:290px;
    }
  }
  @media screen and (min-width: 365px) and (max-width: 380px){
    .eye{
      left:300px;
    }
  }
  @media screen and (min-width: 381px) and (max-width: 400px){
    .eye{
      left:320px;
    }
  }
  @media screen and (min-width: 401px) and (max-width: 420px){
    .eye{
      left:330px;
    }
  }
  @media screen and (min-width: 421px) and (max-width: 440px){
    .eye{
      left:350px;
    }
  }
  .el-input__inner{
    padding-left:30px
  }
  .el-input__prefix{
    left:8px !important;
  }
    
}
</style>