// pages/real_name/read_name.js
const app = getApp();
const util = require('../../utils/utils.js');
let timer1 = null;
Page({
  data: {
    state1: '1', //步骤一
    state2: '', //步骤二
    state3: '', //步骤三
    state4: '', //步骤四
    index: 0, //0 手机验证 1 实名认证 2 缴纳押金  3完成
    index1: 0, //0 选择获取手机号码方式  1 手动输入页面
    nameVal: '', //输入的名字
    cardVal: '', //输入的身份证号码
    smsVal: '', //输入的短信验证码
    phoneVal: '', //输入的手机号码
    code: '获取验证码', //获取短信验证码
    phoneDisabele: false, //输入的手机号是否能更改
    currentTime: 60, //倒计时秒数
    codeDisabled: false, //是否禁用按钮
    timer: null, //定时器
    money: wx.getStorageSync('setting').deposit,
    payment: true,
    count: 10,
    statusIndex: 0, //0  缴纳押金 1退回押金  2退押金状态
    pay: 0, // 1 支付押金   0 支付/缴纳/退回
    popShow: true, //是否显示弹窗
    money: '',
    depoSuce: true,
    imgUrl: 'http://resource.weilaibike.com/xiaobanma/moneyBg.png',
    depShow: true, //是否选中缴纳押金   true选中  false 未选中
    curShow: '', //是否选中购买免押金卡  undefined 未选中  有值选中
    cardList: [], //免押金卡列表
    state: [],
    userState: wx.getStorageSync('userState'),
    title: app.globalData.title,
    setting: wx.getStorageSync('setting'),
    hidden: true
  },
  onLoad: function (options) {
    if (options.index) {
      this.setData({
        index: options.index,
        state2: options.state2
      })
    }
    if (options.hidden) {
      this.setData({
        hidden: false
      })
    }
    this.getState();
    // this.setData({
    //   money: wx.getStorageSync('setting').deposit
    // })
    // if (wx.getStorageSync('setting') == '') {
    //   wx.showModal({
    //     title: '提示',
    //     content: '您附近暂无运营区域~',
    //     showCancel: false,
    //     success: function (res) {
    //       if (res.confirm) {
    //         wx.navigateBack()
    //       }
    //     }
    //   })
    // } else {
    //   this.setData({
    //     money: wx.getStorageSync('setting').deposit
    //   })
    // }
    if (options.home) {
      this.setData({
        pay: 1
      })
    }
    this.getCard();
  },
  student: function () {
    wx.navigateTo({
      url: '../student_certification/student_certification',
    })
  },
  //返回首页
  backPage() {
    clearInterval(timer1);
    if (app.globalData.compatible) {
      wx.reLaunch({
        url: '/pages/compatible/index/index',
      })
    } else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
  //验证名字
  ckName(e) {
    this.setData({
      nameVal: e.detail.value
    })
  },
  name(e) {
    this.setData({
      nameVal: e.detail.value
    })
  },
  namefirm(e) {
    this.setData({
      nameVal: e.detail.value
    })
  },
  //验证身份证号
  ckCard(e) {
    this.setData({
      cardVal: e.detail.value
    })
  },
  input(e) {
    this.setData({
      cardVal: e.detail.value
    })
  },
  valuefirm(e) {
    this.setData({
      cardVal: e.detail.value
    })
  },
  //验证手机号
  ckPhone(e) {
    this.setData({
      phoneVal: e.detail.value
    })
  },
  //验证短信验证码
  ckSms(e) {
    this.setData({
      smsVal: e.detail.value
    })
  },
  //获取短信验证码
  getCode: util.throttle(function () {
    let self = this
    let currentTime = self.data.currentTime
    let timer = self.data.timer
    if (self.data.phoneVal.length != 11) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2000
      })
    } else {
      self.setData({
        phoneDisabele: true
      })
      // 调用短信验证码接口
      let data = {
        mobile: this.data.phoneVal,
        type: 1
      }
      app.request('/verification-code', data, 'POST').then(res => {
        if (res.statusCode == 200) {
          //60秒倒计时
          if (!timer) {
            timer = setInterval(() => {
              if (currentTime > 0 && currentTime <= 60) {
                currentTime--;
              }
              if (currentTime !== 0) {
                self.setData({
                  code: "重新发送" + "(" + currentTime + ")",
                  codeDisabled: true,
                })
              } else {
                clearInterval(timer);
                self.setData({
                  code: '获取验证码',
                  phoneDisabele: false,
                  codeDisabled: false,
                  currentTime: 60,
                  timer: null,
                })
              }
            }, 1000)
          }
        }
      })
    }
  }, 1000),
  //提交申请按钮
  submit: util.throttle(function () {
    let reg = /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/;
    let reg1 = /^[\u4E00-\u9FA5]{2,4}$/;
    var that = this;
    if (!reg1.test(this.data.nameVal)) {
      wx.showToast({
        title: '请输入正确的姓名',
        icon: 'none',
        duration: 2000
      })
    } else if (!reg.test(this.data.cardVal)) {
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.checkIDCard(that.data.cardVal)
    }
  }, 1000),
  // 一键获取手机号
  checkIDCard(idcode) {
    // 加权因子
    var that = this;
    var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    // 校验码
    var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
    var code = idcode + ''
    var last = idcode[17] //最后一位
    var seventeen = code.substring(0, 17)
    // ISO 7064:1983.MOD 11-2
    // 判断最后一位校验码是否正确
    var arr = seventeen.split('')
    var len = arr.length
    var num = 0
    for (var i = 0; i < len; i++) {
      num = num + arr[i] * weight_factor[i]
    }
    // 获取余数
    var resisue = num % 11
    var last_no = check_code[resisue]
    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/
    // 判断格式是否正确
    var format = idcard_patter.test(idcode)
    console.log(format)
    console.log(last)
    console.log(last_no)
    // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
    if(last==last_no && format==true){
      wx.showLoading({
        title: '认证中...',
        mask: true
      })
      if (app.globalData.req) {
        let data = {
          card_id: that.data.cardVal,
          name: that.data.nameVal
        }
        app.request('/user/real-name-authentication', data, 'POST', app.globalData.req).then(res => {
          console.log(res)
          if (res.statusCode == 200) {
            if (that.data.hidden == false) {
              wx.navigateBack()
            } else {
              that.setData({
                state3: 3,
                index: 2
              })
            }
            wx.hideLoading()
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        wx.showToast({
          title: '您的操作过于频繁，请稍后再试~',
          icon: 'none'
        })
      }
    }else{
      wx.showToast({
        title: '身份证号输入有误~',
        icon:'none'
      })
    }
    
  },
  getPhoneNumber(e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let data = {
        session_key: wx.getStorageSync('session_key'),
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData
      }
      app.request('/user/bind-wechat-mobile', data, 'POST').then(res => {
        if (res.statusCode == 200) {
          //获取成功判断当前有没有实名认证，如果有跳到交押金 没有则正常执行
          if (wx.getStorageSync('setting').is_card == 0 && wx.getStorageSync('setting').is_deposit == 1) {
            this.setData({
              state3: 3,
              index: 2,
              state2: 2
            })
          } else if (wx.getStorageSync('setting').is_card == 0 && wx.getStorageSync('setting').is_deposit == 0) {
            this.setData({
              state3: 3,
              index: 3,
              state2: 2,
              state4: 4
            })
            if (!timer1) {
              let count = that.data.count;
              timer1 = setInterval(() => {
                if (count > 0) {
                  that.setData({
                    count: --count
                  })
                }
                if (count <= 0) {
                  clearInterval(timer1)
                  that.backPage();
                }
              }, 1000)
            }
          } else {
            if (wx.getStorageSync('userState').is_card_certified == 1) {
              this.setData({
                state3: 3,
                index: 2,
                state2: 2
              })
            } else {
              this.setData({
                state2: 2,
                index: 1
              })
            }
          }
        }
      })
    } else {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 手动输入手机号码
  manual() {
    this.setData({
      index1: 1
    })
  },
  //立即验证按钮
  verify: util.throttle(function () {
    let reg = 11 && /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
    let reg1 = /^\d{4}$/
    if (!reg1.test(this.data.smsVal)) {
      wx.showToast({
        title: '请输入短信验证码',
        icon: 'none',
        duration: 2000
      })
    }
    if (!reg.test(this.data.phoneVal)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 2000
      })
      return;
    } else if (!this.data.smsVal) {
      wx.showToast({
        title: '短信验证码不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    } else {
      if (app.globalData.req) {
        let data = {
          mobile: this.data.phoneVal,
          code: this.data.smsVal
        }
        app.request('/user/bind-mobile', data, 'POST', app.globalData.req).then(res => {
          if (res.statusCode == 200) {
            if (wx.getStorageSync('userState').is_card_certified == 1) {
              this.setData({
                state3: 3,
                index: 2,
                state2: 2
              })
            } else {
              this.setData({
                state2: 2,
                index: 1
              })
            }
          }
          if (res.statusCode == 422) {
            console.log(res)
            wx.showToast({
              title: res.data.errors,
              icon: 'none',
              duration: 2000
            })
          }
        })
      } else {
        wx.showToast({
          title: '您的操作过于频繁，请稍后再试~',
          icon: 'none'
        })
      }
    }
  }, 1000),
  phone: function () {
    wx.makePhoneCall({
      phoneNumber: wx.getStorageSync('home').customer_service_phone,
    })
  },
  privacy: util.throttle(function () {
    //点击个人隐私条约
    wx.navigateTo({
      url: '/pages/personal/privacy/privacy',
    })
  }, 1000),
  agreement: util.throttle(function () {
    //充值条约
    wx.navigateTo({
      url: '/pages/agreement/agreement',
    })
  }, 1000),
  onReady: function () {

  },
  onShow: function () {
    this.setData({
      money: wx.getStorageSync('setting').deposit,
      setting: wx.getStorageSync('setting')
    })
  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  },
  explain() {
    wx.navigateTo({
      url: '/pages/explain_card_free/explain_card_free',
    })
  },
  getCard() {
    let data = {
      area_id: wx.getStorageSync('home').id
    }
    app.request('/deposit_card/index', data, 'GET').then(res => {
      console.log(res.data);
      this.setData({
        cardList: res.data.data
      })
      console.log(this.data.cardList)
    })
  },
  // 切换免押金卡
  cut(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    if (id == undefined) {
      that.setData({
        depShow: true,
        curShow: "text_undefined",
        depshow: true
      })
    } else {
      that.setData({
        curShow: id,
        depShow: false,
        depshow: false
      })
    }
  },
  //进入页面判断是否缴纳押金
  getState: util.throttle(function (e) {
    app.request('/user/status', '', 'GET').then(res => {
      console.log(res, '判断');
      this.setData({
        statusIndex: res.data.is_deposit,
        state: res.data
      })
    })
  }, 1000),
  //缴纳押金
  pay: util.throttle(function (e) {
    this.setData({
      pay: 1
    })
  }, 100),
  //显示弹窗
  showPop: util.throttle(function (e) {
    this.setData({
      popShow: false,
    })
  }, 1000),
  //取消退回押金
  cancle: util.throttle(function (e) {
    this.setData({
      popShow: true,
    })
  }, 1000),
  //确定退回押金
  confirm: util.throttle(function (e) {
    this.setData({
      popShow: true,
      statusIndex: 1,
    })
    if (app.globalData.req) {
      app.request('/deposit/refund', '', 'POST', app.globalData.req).then(res => {
        console.log(res);
        if (res.statusCode == 200) {
          wx.showToast({
            title: '押金退还成功稍后到账~',
            icon: 'none',
            duration: 3000
          })
          this.setData({
            statusIndex: 0
          })
        }
      })
    } else {
      wx.showToast({
        title: '您的操作过于频繁，请稍后再试~',
        icon: 'none'
      })
    }
  }, 1000),
  //立即支付
  depoSuce: util.throttle(function (e) {
    console.log('支付')
    var that = this;
    let url = '';
    var data = '';
    if (app.globalData.req) {
      console.log(that.data.depShow)
      if (that.data.depShow) { //缴纳押金
        console.log(11111)
        url = "/deposit/pay";
        data = {
          area_id: wx.getStorageSync('home').id
        }
      } else { //购买免押金卡
        console.log(2222)
        url = "/deposit_card/pay";
        data = {
          area_id: wx.getStorageSync('home').id,
          id: that.data.curShow
        }
      }
      app.request(url, data, 'POST', app.globalData.req).then(res => {
        if (res.statusCode == 200) {
          console.log(res)
          wx.requestPayment({
            timeStamp: res.data.timeStamp.toString(),
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success(res) {
              that.setData({
                payment: false,
                state4: 4,
                index: 3,
                depoSuce: true
              })
              if (!timer1) {
                let count = that.data.count;
                timer1 = setInterval(() => {
                  if (count > 0) {
                    that.setData({
                      count: --count
                    })
                  }
                  if (count <= 0) {
                    clearInterval(timer1)
                    that.backPage();
                  }
                }, 1000)
              }
            },
            fail(err) {
              console.log(err)
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              })
              that.setData({
                depoSuce: true
              })
            }
          })
        } else {
          console.log(res)
          that.setData({
            depoSuce: true
          })
        }
      })
    } else {
      wx.showToast({
        title: '您的操作过于频繁，请稍后再试~',
        icon: 'none'
      })
    }
  }, 1000),
  agreement: util.throttle(function (e) {
    //充值条约
    wx.navigateTo({
      url: '/pages/agreement/agreement',
    })
  }, 1000),
})