// pages/bindphone/bindPhone.js
let log = require('../../utils/log.js');
Page({
  /**
   * 组件的初始数据
   */
  data: {
      userInfo: {},
      isLogin: false,
      phone: null,
      errorMsg: '',
      vcodeFlag: true,
      vcodeTimeOut: 0,
      vcodeTimeOutDefault: 0,
      scene: "LN_PHONE",
      vcodeLen:2,
      vcodeInterval:null,
      vcode_button_text:'获取验证码',
      servicetel: '4009608068'
  },

  onError(e) {
    wx.showModal({
      title: '温馨提示',
      content: '当前网络环境较差,无法连接服务器,请稍后重试。有问题请联系客服电话4009608068,接听时段08:30-17:00。',
      showCancel: false
    });
  },

  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    });
    this.checkAll();
  },

  inputVerificatrCode(e) {
    this.setData({
      vcode: e.detail.value
    });
    this.checkAll();
  },

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

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

    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/sendPhoneVcodeUnique',
      data: {
        scene: that.data.scene,
        terminal: phone,
      },
      method: 'POST',
      success(res) {
        if (res.data.code == 1) {
          wx.showModal({
            title: '提示',
            content:res.msg,
            showCancel:false,
            confirmColor:'#4359b5'
          });
        }else if (res.data.code == 2) {
          // 跳转
          wx.showModal({
            title: '提示',
            content: '手机已绑定账户,请检查手机号是否填写正确或联系客服',
            showCancel:false,
          });
        }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: '获取验证码'
              })
              clearInterval(vcodeInterval);
            }else{
              let str = '获取验证码'+'(' + that.data.vcodeTimeOut + 's)'
              that.setData({
                vcodeTimeOut:that.data.vcodeTimeOut-1,
                vcodeFlag: false,
                vcode_button_text: str
              })
            }
          }, 1000);
        }
      }
    });

  },

  bindPhone(e) {
    let that = this;
    let loginName = this.data.userInfo.loginName;
    let { phone, vcode } = this.data;
    log.info('[绑定手机]', '[绑定手机]', '[请求]', { phone, vcode });
    wx.request({
      url: getApp().globalData.postHeadAgreement +'/restapi/wechat/bindPhone',
      data: {
        loginName,
        phonenumber: phone,
        vcode
      },
      method: 'POST',
      success(res) {
        if (res.data.code == 1) {
           that.setData({
             vcode: null,
           });
          wx.showModal({
            title: '提示',
            content:res.data.msg,
            showCancel:false,
            confirmColor:'#4359b5'
          });
          log.info('[绑定手机号]', '[绑定手机号]', '[失败code==1]', res.data);
        } else {
          wx.setStorageSync("userInfo", res.data);
          wx.setStorageSync("isLogin", true);
          //跳转到上一页
          log.info('[绑定手机号]', '[绑定手机号]', '[成功返回上一个界面]', res.data);
          wx.navigateBack();
        }
      },
      fail(e){
        getApp().showNetworkError();
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    // 页面显示
    if (userInfo && isLogin) {
      this.setData({
        userInfo: userInfo,
        isLogin: isLogin
      });
      if ((!userInfo.userId && userInfo.userId != 0)){
        log.info('[首页]', '[已登陆未有用户ID跳转登录界面]');
        let url = `/pages/login/phone_login/phone_login`;
        wx.navigateTo({
          url
        });
        return;
      }
    } else {
      //未登录信息
      this.setData({
        userInfo: {}
      });
      let url = `/pages/login/phone_login/phone_login`;
      wx.navigateTo({
        url
      });
      return;
    }

    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
        })
      }
    });
  },

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

  },

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

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

  },

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

  },

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

  },

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

  },

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

  }
})