<template>
  <div class="page_login">
    <div class="loginTop">
      <img src="../../assets/images/loginLogo.png" alt />
    </div>
    <div class="loginBottom">
      <div class="ipts">
        <el-form ref="LoginForm" :model="LoginForm" :rules="rules" :show-message="showMessage">
          <el-form-item required prop="tel">
            <el-input
              placeholder="请填写手机号码"
              prefix-icon="el-icon-mobile"
              v-model.trim="LoginForm.tel"
              clearable
              maxlength="11"
              @input="change(LoginForm.tel)"
              v-on:blur="watchNum"
              v-on:input="watchNum"
            ></el-input>
          </el-form-item>
          <el-form-item  v-if="LoginForm.tel!='14795166168'&&LoginForm.tel!='19175053813'&&LoginForm.tel!='13635052020'&&LoginForm.tel!='13471923068'&&LoginForm.tel!='17376348819'&&LoginForm.tel!='15278270837'&&LoginForm.tel!='17376306487'&&LoginForm.tel!='15994500627'&&LoginForm.tel!='13100456939'&&LoginForm.tel!='18934874266'">
            <el-input
             class="noRight"
              placeholder="请填写密码"
              prefix-icon="el-icon-lock"
              v-model.trim="LoginForm.psd"
              show-password
              clearable
              v-on:blur="watchNum"
              v-on:input="watchNum"
            ></el-input>
          </el-form-item>

          <el-form-item  v-else>
            <el-input
             class="noRight"
              placeholder="请填写密码"
              prefix-icon="el-icon-lock"
              v-model.trim="LoginForm.psd"
              clearable
              type="password"
              v-on:blur="watchNum"
              v-on:input="watchNum"
            ></el-input>
          </el-form-item>
          
        </el-form>
      </div>
      <div class="rememberBox">
        <div class="remember">
          <van-checkbox class="checked" v-model="remember" shape="square">记住密码</van-checkbox>
        </div>
        <p class="forget" @click="toForgetPassword()" v-if="LoginForm.tel!='14795166168'&&LoginForm.tel!='19175053813'&&LoginForm.tel!='13635052020'&&LoginForm.tel!='13471923068'&&LoginForm.tel!='17376348819'&&LoginForm.tel!='15278270837'&&LoginForm.tel!='17376306487'&&LoginForm.tel!='15994500627'&&LoginForm.tel!='13100456939'&&LoginForm.tel!='18934874266'">忘记密码?</p>
      </div>
      <div class="login" @click="submitForm()" v-show="loginshow">登录</div>
      <div class="login3" v-show="loginshowtwo">登录</div>
      <div class="login2">
        <p @click="noPassword()" v-if="LoginForm.tel!='14795166168'&&LoginForm.tel!='19175053813'&&LoginForm.tel!='13635052020'&&LoginForm.tel!='13471923068'&&LoginForm.tel!='17376348819'&&LoginForm.tel!='15278270837'&&LoginForm.tel!='17376306487'&&LoginForm.tel!='15994500627'&&LoginForm.tel!='13100456939'&&LoginForm.tel!='18934874266'">免密码登录</p>
        <p class="register" @click="ToRegister()">快速注册</p>
      </div>
    </div>
    <div class="agreeBox">
      <van-checkbox
        class="checked"
        v-model="checked"
        v-on:input="watchNum"
        shape="square"
        >我已阅读并同意</van-checkbox
      >
      <span class="newColor" @click="agree()">《隐私服务协议》</span>
      <span class="newColor" @click="agree1()">《用户协议》</span>
    </div>
    <van-overlay :show="show" type="spinner" size="30px">
      <div class="wrapper">
        <van-loading size="24px" vertical>正在登录...</van-loading>
      </div>
    </van-overlay>

    <Popup ref="showscret"></Popup>
  </div>
</template>

<script>
import "../../styles/newStyle.scss";
import { loginByPwd } from "@/api/login";
import {checkMobileIp} from "@/api/newlogin"
import { hex_md5 } from "@/utils/md5";
import { Toast } from "vant";
import { checkMobile } from "@/utils/tools";
import { setRem } from "@/libs/functionRem";
import { Dialog } from "vant";
import Popup from "./Popup/index"
import axios from 'axios'
const https = require('https');
const agent = new https.Agent({
  rejectUnauthorized: false  // 忽略证书验证
});
const instance = axios.create({
  httpsAgent: agent,
  baseURL: 'http://192.168.0.38:8080', // API 的基础 URL
  timeout: 30000 // 请求超时时间
});
export default {
  name: "Home",
  components:{
    Popup
  },
  data() {
    var checkMobileRule = (rule, value, callback) => {
      if (!checkMobile(value)) {
        callback(new Error("请填写正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      showscret:false,
      remember:true,
      showMessage:false,
      show: false,
      checked: false,
      tel: "",
      psd: "",
      LoginForm: {
        tel: "",
        psd: ""
      },
      errorNum: 0,
      loginshow: false,
      loginshowtwo: true,
      rules: {
        tel: [
          { required: true, message: "手机号码不能为空" },
          { validator: checkMobileRule }
        ]
      },
      form: {
        mobile: "",
        pwd: ""
      },
      agreement: true,
      showPassword:true,
    };
  },

  created() {
    setRem();
    // this.form.mobile = loginInfo.mobile;
    // this.form.pwd = loginInfo.password;
    // window.onresize = function() {
    //   setRem();
    // };
    window.callJsFunction = this.callJsFunction;
  },
  mounted(){
    this.getCookie();
  },

  methods: {
    ToRegister() {
      this.$router.push("/register");
    },
    toForgetPassword() {
      this.$router.push("/forget");
    },
    noPassword() {
      this.$router.push("/nopassword");
    },
    change(val) {
      this.LoginForm.tel = val.replace(/[^0-9]+/g, "");
    },
    watchNum() {
     
      
      if(this.LoginForm.psd.length >= 6 && this.LoginForm.tel.length == 11 && this.checked == true){

        this.loginshow = true;
        this.loginshowtwo = false;
      }else{
          this.loginshow = false;
        this.loginshowtwo = true;
      }
    },

    submitForm() {
      this.show = true;
      // const self = this;
      //判断复选框是否被勾选 勾选则调用配置cookie方法
      if (this.remember == true) {
        // console.log("checked == true");
        //传入账号名，密码，和保存天数3个参数
        this.setCookie(this.LoginForm.tel, this.LoginForm.psd, 7);
      } else {
        // console.log("清空Cookie");
        //清空Cookie
        this.clearCookie();
      }

      loginByPwd(this.LoginForm.tel, hex_md5(this.LoginForm.psd)).then(rs => {
          var resp = rs.data;
          if (this.checked != true) {
            this.show = false
            Toast("请同意隐私服务协议");
            return;
          }

          if (resp.state == 1 && this.checked == true) {

            this.show = false;
            var user = resp.data.user;
            var admin = resp.data.admin;
            var org = resp.data.org;
            var subscibe = resp.data.subscibe;
            var config_list = resp.data.config_list;
            var dict_config_list = resp.data.dict_config_list;

            var template_info = resp.data.template_info;
            var filed_list = resp.data.filed_list;
            var token = resp.data.token;


            // console.log('orgorg:',org)
            sessionStorage.setItem("org_id",org.id);
            sessionStorage.setItem("admin_user_id",org.creator);
            localStorage.setItem("token",token);

            this.$store.dispatch("InitUserInfo", {
              admin: admin,
              user: user,
              org: org,
              subscibe: subscibe,
              template_info: template_info,
              filed_list: filed_list
            });
            this.$store.dispatch("SetConfigList", config_list);
            this.$store.dispatch("SetDictConfigList", dict_config_list);

            // if(org.id == 4){
            //   console.log('上面')
            //   location.replace("http://mobile.sgjyun.com/index22.html#/homeIndex")
            // }else{
            //   console.log('下面')
            //   location.replace("http://mobile.sgjyun.com/#/homeIndex")
            // }
            // if(org.id == 9504 || org.id == 3907 || org.id == 3877 || org.id == 10121 || org.id == 9914 || org.id == 9566 || org.id == 10138 || org.id == 10088 || org.id == 9538 || org.id ==9747 ){
              // this.$router.push({path: '/homeIndex'})
              // location.replace("http://mobile.kuyicloud.com/index22.html#/homeIndex")
            // }else{
            //   location.replace("http://mobile.kuyicloud.com/#/homeIndex")
            // }
            //博白
            console.log("机构ID------------------",resp.data.org.id)
            if(resp.data.org.id == 9671){
              this.checkMobileIp()
            }else{
              this.$router.replace({ path: "/" });
            }


          } else {
            this.show = false;
            if (this.errorNum >= 2) {
              this.showForgetPwdDialog();
            } else {
              this.errorNum = this.errorNum + 1;
              if(resp.code == 7003 && this.LoginForm.tel.length != 11){
                this.$toast({
                  message: "请输入正确的手机号"
                });
              }else if(resp.code == 7003 && this.LoginForm.psd.length < 6){
                this.$toast({
                  message: "密码错误"
                });
              }else{
                this.$toast({
                  message: resp.msg
                });
              }

            }
          }
        })
    },
   checkMobileIp() {
      console.log("000000000000000000000000000000000000");

      var that = this;

      instance.get('/test').then(function(response) {
          console.log("response", response);
          console.log("response.data.data.flag", response.data.data.flag);

          if (response.data.state == 0) {
            that.$message.error(response.data.data.msg);
            return false;
          }

          if (response.data.state == 1) {
            console.log("hahahahh");
            that.$router.replace({ path: "/" });

          }
        }).catch(function(error) {
          console.error("Error:", error);
        });
    },
    showForgetPwdDialog() {
      Dialog.confirm({
        title: "账号或密码不正确",
        confirmButtonText: "找回密码",
        cancelButtonText: "确认"
      })
        .then(() => {
          // on confirm
          this.$router.push({ path: "/forgetPassword" });
        })
        .catch(() => {
          // on cancel
        });
    },
    agree() {
      this.$router.push({ path: "/privacy" });
    },
    agree1() {
      this.$router.push({ path: "/userAgreement" });
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
        // console.log(window.document.cookie,'点击登录后设置cookie')
    },

    // 获取cookie
    getCookie: function() {
      this.$nextTick(() => {
        if (this.LoginForm.psd != "") {
          this.remember = true;
        }
      });
      if (document.cookie.length > 0) {

        // console.log(document.cookie,'document.cookie')
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == "userName") {
            this.LoginForm.tel = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "userPwd") {
            this.LoginForm.psd = arr2[1];
          }
        }
      }else{
        this.$nextTick(() => {
          this.$refs.showscret.show = true;
        })

      }
    },
    //清除cookie
    clearCookie: function() {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
    a(event){
      // console.log(123)
      // console.log(event)
    }
  },
  watch:{
    LoginForm:{
      handler: function(obj) {
        //do something
        if(obj.tel.length == 11  && obj.psd.length >= 6){
          this.loginshow = true
          this.loginshowtwo = false
        }
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.page_login {
  overflow: hidden;
  height: 100%;
  overflow-y: auto;
  .loginTop {
    width: 100%;
    img {
      width: 10rem;
      height: 5rem;
      border: none;
      margin: 4.25rem auto 1.75rem;
      display: block;
    }
  }
  .loginBottom {
    width: 23.4375rem;
    padding-top: 1rem;
    box-sizing: border-box;
    margin: 0 auto;
  }
  .forget {
    font-size: 0.8125rem;
    color: #1a8cff;
  }
  .agreeBox {
    // width: 84%;
    width: 20.25rem;
    display: flex;
    align-items: center;
    font-size: 0.8125rem;
    margin: 1.75rem auto 0;

    .newColor {
      color: #338afb;
    }
  }
  .login {
    width: 19.25rem;
    height: 2.875rem;
    background: #338afb;
    border-radius: 1.4375rem;
    margin: 0 auto;
    line-height: 2.875rem;
    color: #fff;
    text-align: center;
    font-size: 1rem;
  }
  .login2 {
    margin-top: 1.75rem;
    font-size: 0.8125rem;
    color: #1a8cff;

    > p:first-child {
      float: left;
      margin-left: 3rem;
    }
    .register {
      margin-left: 17.4375rem;
      color: #1a8cff;
    }
  }
  .login3 {
    width: 19.25rem;
    height: 2.875rem;
    background: #e5e5e5;
    border-radius: 1.4375rem;
    margin: 0 auto;
    line-height: 2.875rem;
    color: #fff;
    text-align: center;
    font-size: 1rem;
  }
  .wrapper {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .remember{
    font-size: .875rem;
    .van-checkbox__label{
      color: #1a8cff;
    }
  }
  .rememberBox{
    width: 19.25rem;
    height: 3.125rem;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.el-form-item__error {
  margin-left: 2.5rem;
}
.el-button--medium {
  padding: 0;
}

.el-message {
  min-width: 20rem;
}
</style>
<style lang="scss">
.loginBottom {
  .el-form-item {
    margin-bottom: 0;
  }
  .ipts {
    // .el-icon-circle-close {
    //   margin-right: 0.625rem;
    // }
    .noRight{
      .el-icon-circle-close {
        margin-right: 0.625rem;
        @media only screen and (min-width: 768px) {
           margin-right: 1rem;
        }
      }
    }
    .el-input {
      display: block;
      margin: 0 auto;
      width: 19.0625rem;
      border-bottom: 1px solid #e6e6e6;
      color: rgba(155, 155, 155, 1);
      // padding-left: 0.75rem;
      box-sizing: border-box;
      height: 3.375rem;
      line-height: 3.375rem;
      font-size: 1rem;
    }
    .el-input__inner {
      border: none;
      font-size: 1rem;
      color: #000 !important;
      @media only screen and (min-width: 768px) {
        padding-left: 1.75rem !important;
      }
    }
    .el-input__prefix {
      font-size: 1.5rem;
      left: 0;
    }
    .el-input__icon {
      font-size: 1.5rem;
      line-height: 3.375rem;
    }
    .el-input__suffix{
      right: 0;
    }
  }
}
.page_login{
  .van-loading__text{
    color: #fff;
  }
}
.van-picker__cancel, .van-picker__confirm{
  font-size: 1rem;
}
.remember{
  .van-checkbox{
    width: 5.625rem;
  }
  .van-checkbox__label{
    color: #1a8cff;
  }
}
.checked{
  font-size: .875rem;
}
</style>
