// pages/register/register.js
import Toast from '../../vant/toast/toast';
import random from '../../utils/random.js' 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName: null,
    phone: null,
    email: null,
    carNum:null,
    password: null,
    rePassword: null,
    checkPass: false,
    errorMsg: '',
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    vcodeFlag: false,
    vcodeTimeOut: 0,
    vcodeTimeOutDefault: 0,
    scene: "REGIST",
    vcodeLen:6,
    vcodeInterval:null,
    vcode_button_text:'获取验证码',
    servicetel: '4009608068',
    showMsg: false,
    timeing: true,
    checked:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    let scene = this.data.scene;
    let that = this
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/vcodeInfo',
      // 场景(LOGIN:登录;LN_PHONE:绑定手机;UN_PHONE:解绑手机;FORGET_PWD:忘记密码;REGIST:注册;MDF_PWD:修改密码)
      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
        })
      }
    });


    //var that = this;
    //查看是否授权
    //wx.getSetting({
    //success(res) {
    //console.log(res);
    //if (res.authSetting['scope.userInfo']) {
    //that.setData({
    //authSet: true
    //});
    //已经授权，可以直接调用 getUserInfo 获取头像昵称
    //wx.getUserInfo({
    //success(res) {
    //console.log(res)
    //that.setData({
    //userInfo: res.userInfo
    //});
    //}
    //});
    //}
    //}
    //});
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    if(!this.data.checked){
        Toast('请先阅读并同意用户使用协议');
        return;
    }
    this.checkAll();
    this.setData({
      showMsg:true
    })
    if(!this.data.checkPass){
      return;
    }
    let that=this
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {


        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        that.bindGetUserInfo(res.userInfo);
      }
    })
  },

  bindGetUserInfo(userInfo) {
    //console.log(e.detail.userInfo)
    console.info(this.userInfo)
    let that = this;
    const randomPassword = random.generateRandomCode()
    if (userInfo) {
      let {
        nickName: userName,
        gender: sex,
        avatarUrl: avatar
      } = userInfo;
      this.setData({
        password:randomPassword
      })
      let {
        userName: loginName,
        password,
        phone,
        carNum,
        email,
        vcode
      } = this.data;
      wx.login({
        success(res) {
          console.log(res);
          if (res.code) {
            wx.request({
              url: getApp().globalData.postHeadAgreement + '/restapi/wechat/register',
              data: {
                multipleOrders:0,
                refund:1,
                userName,
                sex:"0",
                avatar:'http://cdglyy.pjnes.com/web/profile/avatar/c134f314cbbe985a8aae1787b45e6d6a.jpg',
                loginName,
                password,
                phonenumber: phone,
                email,
                vcode,
                license_number: carNum,
                code: res.code,
                
              },
              method: 'POST',
              success(res1) {
                //console.log(res1);
                //console.log(res1.data.code == 1);
                if (res1.data.code == 1 || res1.data.code == 2) {

                  if(res1.data.msg!=null && res1.data.msg.startsWith("503")){
                    getApp().showNetworkError();
                    return;
                  }

                  // that.setData({
                  //   errorMsg: res1.data.msg
                  // })
                  wx.showModal({
                    title: '提示',
                    content: res1.data.msg,
                    showCancel:false,
                    confirmColor:'#00AADD',
                  });
                } else {
                  //返回该用户
                  //跳转到上一页
                  wx.setStorageSync("userInfo", res1.data);
                  wx.setStorageSync("isLogin", true);
                  wx.navigateBack();
                  //let url = `/pages/ucenter/index/index`;
                  //wx.redirectTo({
                  //url
                  //});
                }
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg)
          }
        }
      });

    }
  },
  inputAccount(e) {
    this.setData({
      userName: e.detail.value
    });
    this.checkAll();
  },
  inputPassword(e) {
    this.setData({
      password: e.detail.value,
      showMsg: false
    });
    this.checkAll();
  },
  inputRepassword(e) {
    this.setData({
      rePassword: e.detail.value,
      showMsg: false
    });
    this.checkAll();
  },
  inputPhone(e) {
    this.setData({
      phone: e.detail.value,
      showMsg: false
    });
    this.checkAll();
  },
  inputVcode(e) {
    this.setData({
      vcode: e.detail.value,
      showMsg: false
    });
    if(!this.msgVcode()){
      return;
    }
    this.checkAll();
  },
  inputEmail(e) {
    this.setData({
      email: e.detail.value
    });
    this.checkAll();
  },
  inputCarNum(e){
    this.setData({
      carNum: e.detail.value
    });
    this.checkAll();
  },
  checkPassword() {
    if (!this.data.password || !this.data.rePassword || this.data.password != this.data.rePassword) {
      return false;
    }
    return true;
  },
  checkPhone() {
    if (!(/^1[3456789]\d{9}$/.test(this.data.phone))) {
      this.setData({
        vcodeFlag:false
      })
      return false;
    }
    if(this.data.vcodeTimeOut<=0){
      this.setData({
        vcodeFlag:true,
      })
    }
    return true;
  },
  checkMail() {
    if (!(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(this.data.email))) {
      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;
  },
  checkCarNum(){
    if (this.data.carNum){
      // if (!(/^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(this.data.carNum))) {
      if (!/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领].*$/.test(this.data.carNum)) {
        return false;
      }
    }
    return true;
  },
  sendVcode(e){
    let that  = this
    if (!that.checkPhone()) {
      that.setData({
        errorMsg: '手机号输入有误，请重新输入'
      });
      that.setData({
        checkPass: false
      });
      return;
    } else {
      that.setData({
        errorMsg: ''
      });
    }


    let phone = that.data.phone;


    that.setData({
      vcodeTimeOut:that.data.vcodeTimeOutDefault
    })
    let vcodeInterval = setInterval(that.vcodeFun,1000);
    that.setData({
      vcodeInterval 
    })


    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/sendPhoneVcodeUnique',
      // url: getApp().globalData.postHeadAgreement + '/restapi/wechat/sendPhoneVcode',
      data: {
        scene: that.data.scene,
        terminal: phone,
      },
      method: 'POST',
      success(res) {


        //console.log(res1);
        //console.log(res1.data.code == 1);
        if (res.data.code == 1) {
          if(res.data.msg!=null && res.data.msg.startsWith("503")){
            getApp().showNetworkError();
            return;
          }
            that.setData({
              vcodeTimeOut:0,
              vcodeFlag:true,
              vcode_button_text:'获取验证码'
            })
          wx.showModal({
            title: '提示',
            content:res.data.msg,
            showCancel:false,
            confirmColor:'#00AADD',
          });
        }else if (res.data.code == 2) {
          that.setData({
            vcodeTimeOut:0,
            vcodeFlag:true,
            vcode_button_text:'获取验证码'
          })
          // 跳转
          wx.showModal({
            title: '提示',
            content: '手机号已绑定账户,请检查手机号是否填写正确或联系客服',
            showCancel:true,
            confirmText: '去登录',
            cancelText:"确定",
            confirmColor:'#00AADD',
            success: function (res1) {
              if (res1.confirm) {
                let url = '/pages/login/phone_login/phone_login';
                wx.redirectTo({
                  url
                })
              }
            }
      
          });
        }else{
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 1000 //持续的时间
          })
        }
      }
    });


  },
  vcodeFun(){
    
      if(this.data.vcodeTimeOut<=0){
        this.setData({
          vcodeFlag:true,
          vcode_button_text:'获取验证码',
          timeing:true
        })
        clearInterval(this.data.vcodeInterval)
      }else{
        this.setData({
          vcodeTimeOut:this.data.vcodeTimeOut-1,
          vcodeFlag:false,
          vcode_button_text:'获取验证码(' + this.data.vcodeTimeOut+'s)',
          timeing:false
        })
      }

  },

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


  checkAll() {
    // if (!this.data.userName || !this.data.userName.replace(/(^\s*)|(\s*$)/g,"")) {
    //   this.setData({
    //     errorMsg: '账号不能为空'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // } else if (this.data.userName.length < 2 || this.data.userName.length > 20) {
    //   this.setData({
    //     errorMsg: '账号长度应为2-20'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // } else if (!(/^[a-zA-Z0-9_.\u4e00-\u9fa5]+$/.test(this.data.userName))) {
    //   this.setData({
    //     errorMsg: '账号只能包含字母、数字、中文、下划线和点'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // }else{
    //   this.setData({
    //     errorMsg: ''
    //   }); 
    // }
    if (!this.checkPhone()) {
      this.setData({
        errorMsg: '手机号输入有误，请重新输入'
      });
      this.setData({
        checkPass: false,
        vcodeFlag: false
      });

      return;
    } else {
      this.setData({
        errorMsg: '',
        vcodeFlag: true
      });

    }

    if(!this.msgVcode()){
      return;
    }
    // if (!this.checkMail()) {
    //   this.setData({
    //     errorMsg: '邮箱输入有误，请重新输入'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // } else {
    //   this.setData({
    //     errorMsg: ''
    //   });
    // }
    // if (!this.checkCarNum()) {
    //   this.setData({
    //     errorMsg: '车牌号输入有误，请重新输入'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // } else {
    //   this.setData({
    //     errorMsg: ''
    //   });
    // }
    // if (this.data.password && (this.data.password.length < 5 || this.data.password.length > 20)) {
    //   this.setData({
    //     errorMsg: '密码长度应为5-20'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // }
    // if (!this.checkPassword()) {
    //   this.setData({
    //     errorMsg: '两次密码输入不一致，请重新输入'
    //   });
    //   this.setData({
    //     checkPass: false
    //   });
    //   return;
    // } else {
    //   this.setData({
    //     errorMsg: ''
    //   });
    // }
    this.setData({
      checkPass: true
    });
  },
  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: this.data.servicetel,
    })
  },
  userAgreement(){
    let url = '/pages/agreement/userAgreement'
    wx.navigateTo({
      url
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  onCheckBoxChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
})