// let api = "https://passport.lrlz.com/mobile/index.php";
// let api = "http://www.xyzshops.cn/mobile/index.php";
// let api = "http://192.168.1.200/mobile/index.php";
let api = "https://www.xyzshops.cn/mobile/index.php";
let app = getApp();
function getReq(data, callback, method)
{
  let options = {
    client_type: 'mini'
  }
  data = Object.assign({}, options, data);
  let session_id = wx.getStorageSync('session_id');
  if (!session_id && data['op'] != 'ministart') {
    setTimeout(() => {
      getReq(data, callback, method)
    }, 0);
    return;
  }

  let header = {
    'content-type': 'application/json', // 默认值
    'Cookie': 'MPHPSESSID=' + session_id
  }

  if (method == 'POST') {
    header = {
      'content-type': 'application/x-www-form-urlencoded', //数据转换成 query string 
      'Cookie': 'MPHPSESSID=' + session_id
    }
  }
  return wx.request({
    url: api,
    data,
    method: method || 'GET',
    header,
    success(res) {
      callback(res.data)
    },
    fail() {
      wx.showModal({
        confirmText: '重试',
        content: '网络错误',
        success: function (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: "/pages/index/index"
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  })
}

function buyVGoods(goods_id,goods_num, other, successCallback, failCallback) 
{
  let ifcart = 0 ; 
  let cartids = goods_id + '|' + goods_num;
  let params = {
    act: 'member_buy',
    op: 'step_vsecond',
    payment: 'minipay',
    usebonus: 0,
    ifcart : 0,
    cart_id: cartids,
    invoice_id: 0,
    ...other
  }

  params = Object.assign({}, params);
  getReq(params, function (res) {
    wx.hideLoading()
    if (res.code == 200) {
      let param = res.datas.param.data
      let pay_sn = res.datas.pay_sn
      wx.requestPayment({
        timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: param.nonceStr,   //随机串
        package: param.package,
        signType: param.signType, //微信签名方式：
        paySign: param.paySign,   //微信签名
        success: function (res) {
          successCallback && successCallback(res)
        },
        fail: function (res) {
          // wx.redirectTo({
          //   url: `/pages/orderPaySn/orderPaySn?pay_sn=${pay_sn}`
          // })
          wx.showToast({
            icon: 'none',
            title: '支付失败',
            duration: 2000
          })
          failCallback && failCallback(res)
        }
      });
    }
    else {
      wx.showToast({
        icon: 'none',
        title: res.message,
        duration: 2000
      })
      app.globalData.fcodeErr = res.message
      setTimeout(() => {
        wx.navigateBack()
      }, 2000);
    }
  })
}

module.exports = {
  getReq,
  host: api,
  buyVGoods:buyVGoods
}