// pages/buyService/buyService.js
var Service = require('../../utils/service.js');
var Util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [{
        name: '男',
        value: '男',
        checked: 'true'
      },
      {
        name: '女',
        value: '女',
      }
    ],
    idTypeArr: ['身份证', '非中国大陆居民'],
    idType: 0,
    date: '请选择',
    agree: true, //同意知情书
    name: "",
    idCard: "",
    sex: '男',
    age: '请选择',
    phone: '',
    code: '',
    lastid: '',
    ServicePay_datas: '',
    t_userInfo: '',
    serviceName: '',
    time: 0,
    phoneYes: false,
    iPhoneX: false,
    backCode: '',
    backPhone: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.checkModal();
    var ServicePay_datas = JSON.parse(options.ServicePay_datas);
    var t_userInfo = wx.getStorageSync('t_userInfo');
    var orderInfo = wx.getStorageSync('orderInfo');
    wx.removeStorageSync('t_userInfo');
    wx.removeStorageSync('orderInfo');
    var timestamp = (new Date()).valueOf();
    that.setData({
      ServicePay_datas: ServicePay_datas,
      t_userInfo: t_userInfo,
      orderTime: options.orderTime,
      orderInfo: orderInfo,
      serviceName: options.name,
      endTime: Util.timestampToTime(timestamp)
    })
    that.getLastUserData(ServicePay_datas.patient_unionid);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    let userInfo = currPage.data.item;
    console.log("userInfo", userInfo)
    if (userInfo) {
      that.setData({
        lastid: userInfo.id,
        name: userInfo.name,
        idTypr: userInfo.idtype ? userInfo.idtype : 0,
        idCard: userInfo.card ? userInfo.card : '',
        sex: userInfo.sex,
        age: userInfo.age,
        date: userInfo.birthday ? userInfo.birthday : '请选择',
        phone: userInfo.phone,
      })
      if (userInfo.sex == '女') {
        that.setData({
          items: [{
              name: '男',
              value: '男',
            },
            {
              name: '女',
              value: '女',
              checked: 'true'
            }
          ],
        })
      } else {
        that.setData({
          items: [{
              name: '男',
              value: '男',
              checked: 'true'
            },
            {
              name: '女',
              value: '女',
            }
          ],
        })
      }
    }
  },
  //微信获取手机号 add lq dateTime 2020-03-23 
  getPhoneNumber(e) {
    var user = wx.getStorageSync('user')
    var data = {
      openid: user.openid,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      session_key: user.session_key
    }
    Service.getWxUserPhone(data).then((res) => {
      if (res.code == 1) {
        this.setData({
          phone: res.data,
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '绑定失败',
          showCancel: false,
        })
      }
    })
  },
  //获取验证码 add lq dateTime 2020-04-10 
  getPhoneCode() {
    var that = this;
    // 开始倒计时
    that.setData({
      time: 60,
      timer: setInterval(function () {
        let time = that.data.time
        that.setData({
          time: time - 1
        })
        if (that.data.time == 0) {
          // 读秒结束 清空计时器
          clearInterval(that.data.timer);
        }
      }, 1000)
    })
    var data = {
      tel: that.data.phone,
      type: 1
    }
    Service.getCode(data).then((res) => {
      that.setData({
        backCode: res.code,
        backPhone: that.data.phone
      })
    });

  },
  radioChange: function (e) {
    this.setData({
      sex: e.detail.value
    })
  },
  bindDateChange: function (e) {
    var age = Util.getAge(e.detail.value)
    this.setData({
      date: e.detail.value,
      age: age
    })
  },
  bindIdType(e) {
    this.setData({
      idType: e.detail.value,
    })
  },
  //知情同意书
  zqtys: function (e) {
    wx.showLoading({
      mask:true,
    });
    wx.navigateTo({
      url: '/packageA/consent/consent'
    })
    wx.hideLoading();
  },
  //同意知情同意书
  agree: function (e) {
    var that = this;
    var agree = that.data.agree ? false : true;
    that.setData({
      agree: agree
    })
  },
  //更换用户
  changeUser: function () {
    wx.showLoading({mask:true,});
    if (this.data.ServicePay_datas.counsel == 20) {
      wx.navigateTo({
        url: '/packageA/selectUser/selectUser?type=1'
      })
    } else {
      wx.navigateTo({
        url: '/packageA/selectUser/selectUser?type=1&noIdCard=1'
      })
    }
    wx.hideLoading();
  },
  bindName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindIdCard: function (e) {
    this.setData({
      idCard: e.detail.value,
    })
    if (Util.validateIdCard(e.detail.value) && this.data.idType == 0) {
      var date = Util.getBirthdayFromIdCard(e.detail.value);
      var age = Util.getAge(date)
      this.setData({
        date: date,
        age: age
      })
    }
  },
  bindCode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  bindPhone: function (e) {
    this.setData({
      phone: e.detail.value
    })
    if (e.detail.value.length == 11) {
      this.setData({
        phoneYes: true
      })
    } else if (e.detail.value.length == 0) {
      this.setData({
        phoneYes: false
      })
    }
  },
  //上一次购买服务的用户资料(用户唯一id) add 刘权 dateTime 2020-03-23
  getLastUserData(unionid) {
    var that = this;
    var data = {
      unionid: unionid
    }
    Service.lastUserBuyInfo(data).then((res) => {
      if (res.code == 1) {
        if (res.data != null) {
          that.setData({
            lastid: res.data.id,
            name: res.data.name,
            idType: res.data.idtype ? res.data.idtype : 0,
            idCard: res.data.card ? res.data.card : '',
            date: res.data.birthday ? res.data.birthday : '请选择',
            sex: res.data.sex,
            age: res.data.age,
            phone: res.data.phone,
          })
          if (res.data.sex == '女') {
            that.setData({
              items: [{
                  name: '男',
                  value: '男',
                },
                {
                  name: '女',
                  value: '女',
                  checked: 'true'
                }
              ],
            })
          }
        }
      } else {
        console.log(res.msg);
        that.setData({
          phoneYes: false,
        })
      }
    })
  },
  //去支付
  goPay: Util.debouce(function () {
    var that = this;
    console.log(that.data.name)
    if (that.data.name.length < 1) {
      wx.showModal({
        title: '提示',
        content: '姓名不能为空',
        showCancel: false,
      })
      return;
    } else if (that.data.date == "请选择" || that.data.date == "") {
      wx.showModal({
        title: '提示',
        content: '请选择生日',
        showCancel: false,
      })
      return;
    } else if (that.data.phone.length < 11) {
      wx.showModal({
        title: '提示',
        content: '电话不能为空',
        showCancel: false,
      })
      return;
    } else if (that.data.ServicePay_datas.counsel == 20) {
      if (that.data.idCard == '') {
        console.log(1)
        wx.showModal({
          title: '提示',
          content: '请填写正确的身份证号',
          showCancel: false,
        })
        return;
      } else if (!Util.validateIdCard(that.data.idCard) && that.data.idType == 0) {
        console.log(0)
        wx.showModal({
          title: '提示',
          content: '请填写正确的身份证号',
          showCancel: false,
        })
        return;
      } else {
        //非大陆和新疆不走验证
        if (that.data.idType == 1||that.data.idCard.substring(0,2)=='65') {
          that.servicePay();
        } else {
          Util.verifyIdCardAnName(that.data.name, that.data.idCard, res => {
            switch (res.code) {
              case 0:
                if (that.data.phoneYes) {
                  if (that.data.backPhone == '') {
                    wx.showModal({
                      title: '提示',
                      content: '请填写正确的验证码',
                      showCancel: false,
                    })
                    return;
                  } else if (that.data.phone != that.data.backPhone) {
                    wx.showModal({
                      title: '提示',
                      content: '填写的手机号与获取验证码手机号不符',
                      showCancel: false,
                    })
                    return;
                  } else if (that.data.code.length < 4 || that.data.code != that.data.backCode) {
                    wx.showModal({
                      title: '提示',
                      content: '请填写正确的验证码',
                      showCancel: false,
                    })
                    return;
                  } else {
                    that.servicePay();
                  }
                } else {
                  that.servicePay();
                }
                break;
              case 6000:
              case 6001:
              case 6002:
              case 6003:
              case 6004:
              case 6005:
                wx.showModal({
                  title: '提示',
                  content: res.msg,
                  showCancel: false,
                })
                return;
            }
          })
        }
      }
    } else if (that.data.phoneYes) {
      if (that.data.backPhone == '') {
        wx.showModal({
          title: '提示',
          content: '请填写正确的验证码',
          showCancel: false,
        })
        return;
      } else if (that.data.phone != that.data.backPhone) {
        wx.showModal({
          title: '提示',
          content: '填写的手机号与获取验证码手机号不符',
          showCancel: false,
        })
        return;
      } else if (that.data.code.length < 4 || that.data.code != that.data.backCode) {
        wx.showModal({
          title: '提示',
          content: '请填写正确的验证码',
          showCancel: false,
        })
        return;
      } else {
        that.servicePay();
      }
    } else {
      that.servicePay();
    }
  }, 1000, true),
  servicePay: function () {
    var that = this;
    wx.showLoading({
      title: '正在拉起支付',
      mask: true
    })
    let ServicePay_datas = {
      unitid: that.data.ServicePay_datas.unitid,
      counsel: that.data.ServicePay_datas.counsel,
      patient_unionid: that.data.ServicePay_datas.patient_unionid,
      consultant_unionid: that.data.ServicePay_datas.consultant_unionid,
      put_trade_no: that.data.ServicePay_datas.put_trade_no,
      money: that.data.ServicePay_datas.money, //金额
      type: that.data.ServicePay_datas.type,
      name: that.data.name,
      age: that.data.age,
      birthday: that.data.date,
      sex: that.data.sex,
      phone: that.data.phone,
      lastid: that.data.lastid,
    }
    if (ServicePay_datas.counsel == 20) {
      ServicePay_datas.idType = that.data.idType;
      ServicePay_datas.card = that.data.idCard;
    }
    console.log("ServicePay_datas", ServicePay_datas)
    Service.servicePayEdit(ServicePay_datas).then((aress) => {
      if (aress.code == 0) {
        var orderInfo = that.data.orderInfo;
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: orderInfo.timeStamp,
          nonceStr: orderInfo.nonceStr,
          package: orderInfo.package,
          signType: 'MD5',
          paySign: orderInfo.paySign,
          success(res) {
            wx.showLoading({
              title: '正在支付',
              mask: true
            })
            if (res.errMsg && res.errMsg == "requestPayment:ok") {
              that.paySucceedCallback({
                ordernumber: that.data.ServicePay_datas.put_trade_no,
                fromwhere: 1,
                inquiry_id: aress.data
              })
            }
          },
          fail(res) {
            wx.hideLoading();
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: aress.msg,
          showCancel: false,
        })
      }
    })
  },
  paySucceedCallback(data) {
    let that = this;
    Service.paySucceedCallback(data).then((res) => {
      let t_unionid = that.data.t_userInfo.unionid;
      var orderId = data.inquiry_id;
      if (res.code == 1) {
        wx.hideLoading();
        wx.reLaunch({
          url: '/packageA/chat/chat?t_unionid=' + t_unionid + '&orderId=' + orderId + "&groupID=" + res.chat_id,
        })
      } else {
        setTimeout(function () {
          that.paySucceedCallback(data);
        }, 400)
      }
    })
  },
  //判断是否是iPhonex
  checkModal: function () {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        // iPhone X   iPhone XR  iPhone XS Max     iPhone XS iPhone 11 Pro Max iPhone 11 
        if (/^iPhone X.*/i.test(res.model) || /^iPhone XR.*/i.test(res.model) || /^iPhone XS.*/i.test(res.model) || /^iPhone 11*/i.test(res.model) || /^iPhone 11 Pro Max*/i.test(res.model)) {
          that.setData({
            iPhoneX: true,
            winH: res.windowHeight,
          })
        } else {
          that.setData({
            iPhoneX: false,
            winH: res.windowHeight,
          })
        }
      }
    });
  },
    /**
   * 图片加载失败函数
   * @param {*} e 
   */
  binderrorimg(e) {
    let up = "t_userInfo.image";
    this.setData({
      [up]: '/images/doctor_img.png'
    })
  },
})