// pages/login/phone_login/phone_login.js
let log = require('../../../utils/log.js');
let Util = require("../../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: null,
    vcode: null,
    checkCode: false,
    checkPhone: false,
    vcodeFlag: false,
    errorMsg: '',
    varificatCodeFocus:false,
    vcode_button_text: '获取验证码',
    scene: "LOGIN",
    vcodeTimeOut: 0,
    vcodeTimeOutDefault: 0,
    vcodeLen:6,
    servicetel: getApp().globalData.helpPhoneNum,
    queryip: '',
    showMsg: false,
    timeing: true,
  },
  onError(e) {
    wx.showModal({
      title: '温馨提示',
      content: '当前网络环境较差，无法连接服务器，请稍后重试。有问题请联系客服电话4009608068，接听时段08:30-17:00。',
      showCancel: false,
      confirmColor:'#00AADD',
    });
  },
  inputPhone(e) {
    this.setData({
      phone: e.detail.value,
      showMsg: false
    });
    this.checkAll();
  },

  inputVerificatrCode(e) {
    this.setData({
      vcode: e.detail.value,
      showMsg: false
    });
    if(!this.msgVcode()){
      return;
    }
    this.checkAll();
  },

  msgVcode(){
    if (!this.checkVcode()) {
      this.setData({
        // errorMsg: '验证码格式不正确'
        errorMsg: '验证码格式不正确'
      });
      this.setData({
        checkCode: false
      });
      return false;
    } else {
      this.setData({
        errorMsg: ''
      });
    }
    return true;
  },

  checkAll() {
    if (!this.checkPhoneNumber()) {
      this.setData({
        errorMsg: '手机号输入有误，请重新输入',
        checkPhone: false,
        checkCode: false,
        vcodeFlag: false
      });
      return;
    } else {
      this.setData({
        checkPhone: true,
        errorMsg: '',
        vcodeFlag: true
      });
    }

    if(!this.msgVcode()){
      return;
    }

    if (this.data.phone && this.data.vcode) {
      this.setData({
        checkCode: true
      });
    } else {
      this.setData({
        checkCode: false
      });
    }
  },

  checkPhoneNumber() {
    if (!(/^1[3456789]\d{9}$/.test(this.data.phone))) {
      return false;
    }
    return true;
  },

  checkVcode() {
    if (this.data.vcode==undefined || this.data.vcode=="") {
      return false;
    }
    if(this.data.vcode.length==this.data.vcodeLen){
      return true;
    }
    return false;
  },

  getVerificateCode(){
    let vcodeFlag = this.data.vcodeFlag;
    let checkPhone = this.data.checkPhone;
    let phone = this.data.phone;
    let that = this;

    if (!vcodeFlag) {
      return;
    }

    if (!checkPhone) {
      that.setData({
        errorMsg: '手机号输入有误，请重新输入',
        checkCode: false
      });
      return;
    } else {
      that.setData({
        errorMsg: ''
      });
    }

    this.setData({
      vcodeTimeOut:this.data.vcodeTimeOutDefault
    })

    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/sendPhoneVcodeNoUnique',
      data: {
        scene: that.data.scene,
        terminal: phone,
      },
      method: 'POST',
      success(res) {
        console.info(res.data.code);
        if (res.data.code == 2) {
          wx.showModal({
            title: '提示',
            content:res.data.msg,
            showCancel:false,
            confirmColor:'#00AADD',
          });
        }else if (res.data.code == 1) {
          if(res.data.msg!=null && res.data.msg.startsWith("503")){
            getApp().showNetworkError();
            return;
          }
          // 跳转
          wx.showModal({
            title: '提示',
            content: '手机号未绑定账户。若您已注册,请通过账号密码方式登录,登陆后根据系统提示绑定手机号或联系客服处理',
            confirmText: '密码登录',
            cancelText:"确定",
            showCancel:true,
            confirmColor:'#00AADD',
            success: function (res1) {
              if (res1.confirm) {
                let url = '/pages/login/username_login/username_login';
                wx.redirectTo({
                  url
                })
              }
            }
          });
        }else if (res.data.code == 200) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 1000 //持续的时间
          })
          let vcodeInterval = setInterval(function () {
            if (that.data.vcodeTimeOut <= 0) {
              that.setData({
                vcodeFlag: true,
                vcode_button_text: '获取验证码',
                timeing:true
              })
              clearInterval(vcodeInterval);
            }else{
              let str = '获取验证码'+'(' + that.data.vcodeTimeOut + 's)'
              that.setData({
                vcodeTimeOut:that.data.vcodeTimeOut-1,
                vcodeFlag: false,
                vcode_button_text: str,
                timeing:false
              })
            }
          }, 1000);
        }
      }
    });

  },

  loginUser(e) {
    let that = this;
    that.loginUserInner(e,that,that.data.queryip)
  },

  loginUserInner(e,that,ip) {
    let { phone, vcode } = that.data;
    that.checkAll();
    that.setData({
      showMsg:true
    })
    if(!that.data.checkCode){
      return;
    }
    log.info('[登录]', '[登录]', '[请求]', { phone, vcode });
    wx.login({
        success(loginRes) {

          wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechat/phoneLogin',
            data: {
              phonenumber: phone,
              // ip:ip,
              vcode,
              code: loginRes.code
            },
            method: 'POST',
            success(res) {
              console.log(res);
              log.info('[登录]', '[登录]', '[响应]', res.data);
              if (res.data.code == 1) {
                if(res.data.msg!=null && res.data.msg.startsWith("503")){
                  getApp().showNetworkError();
                  return;
                }
                 that.setData({
                   vcode: null,
                   passwordFocus:true//,
                   //errorMsg: res.data.msg
                 });
                wx.showModal({
                  title: '提示',
                  content:res.data.msg,
                  showCancel:false,
                  confirmColor:'#00AADD',
                });
                log.info('[登录]', '[登录]', '[失败code==1]', res.data);
              } else {
                //返回该用户
                //跳转到上一页
                wx.setStorageSync("userInfo", res.data);
                wx.setStorageSync("isLogin", true);
                //let url = `/pages/ucenter/index/index`;
                log.info('[登录]', '[登录]', '[成功返回上一个界面]', res.data);
                wx.navigateBack();
                //wx.redirectTo({
                // url
                //});
              }
            },
            fail(e){
              getApp().showNetworkError();
            }
          });



        }
      });
  },
  

  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: this.data.servicetel
    })
  },

  goToAccountLogin(e){
    let url = '/pages/login/username_login/username_login';
    wx.redirectTo({
      url
    })
  },

  goToRegister(e) {
    let url = '/pages/register/register';
    wx.redirectTo({
      url
    })
  },
  goToForget(e){
    let url = '/pages/forget/forget';
    wx.redirectTo({
      url
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let scene = this.data.scene;
    let that = this

    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/vcodeInfo',
      data: {
        scene,
      },
      method: 'POST',
      success(res) {
        that.setData({
          vcodeInfo:false,
          vcodeTimeOut:res.data.result.expire,
          vcodeTimeOutDefault:res.data.result.expire,
          vcodeLen:res.data.result.len
        })
        // wx.request({
        //   url: 'https://ipv4.icanhazip.com/',
        //   method: 'POST',
        //   success(rrr){
        //     console.info(rrr);
        //     var query = (rrr == null?'':rrr==null?'':rrr);
        //     let queryip = query.data==null? '':query.data.replace("\n","");
        //     that.setData({
        //       queryip
        //     })
        //   },
        //   fail(rrr){
        //     that.setData({
        //       queryip: ''
        //     })
        //   }
        // })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})