// 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 api = "http://www.xyzshops.cn/mobile/index.php";


function getReq(app,data, callback, method)
{
  let options = { 
    client_type: 'mini'
  }
  
  data = Object.assign({}, options, data);
  let session_id = wx.getStorageSync('session_id');
  if (!app.globalData.fMinistart && data['op'] != 'ministart') {
    setTimeout(() => {
      getReq(app,data, callback, method)
    }, 0);
    return;
  }
  let act = data['act'];
  if(act.indexOf('member_') == 0)
  {
    if (app != null && !app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/auth',
      })
      return;
    }
  }
  
  console.log('act=' + act + '&' + 'op=' + data['op']);
  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) 
    {
      console.log('header:', res.header["Set-Cookie"])
      var cookies = res.header["Set-Cookie"];
      if (cookies) {
        var cookie = getCookieValue(cookies, 'MPHPSESSID');
        if(cookie) wx.setStorageSync('session_id', cookie);
      }
      if (res.data.code == 10014) { //ErrUnLogin = 10014;
        wx.navigateTo({
          url: '/pages/auth/auth',
        })
      }
      else {
        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 getCookieValue(cookies,name) {
  var cookie_pos = cookies.indexOf(name,0);
  if (cookie_pos != -1) {
    cookie_pos += name.length + 1;
    var cookie_end = cookies.indexOf(";", cookie_pos);
    if (cookie_end == -1) {
      cookie_end = cookies.length;
    }
    var value = unescape(cookies.substring(cookie_pos, cookie_end));
    return value;
  } else {
    return '';
  }
}

function buyVGoods(app,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
  }
  console.table(params)
  wx.showLoading({
    title: '加载中',
    mask: true
  });
  params = Object.assign({}, params);
  getReq(app,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) {
          wx.hideLoading()
          successCallback && successCallback(res)
        },
        fail: function (res) {
          wx.showToast({
            icon: 'none',
            title: '支付失败',
            duration: 2000
          })
          failCallback && failCallback(res)
        }
      });
    }
    else {
      wx.showToast({
        icon: 'none',
        title: '支付未完成，订单将在10分钟后取消...',
        duration: 2000
      })
    }
  })
}

function payOrder(app, pay_sn) {
  let params = {
    act: 'member_order',
    op: 'pay',
    pay_sn: pay_sn,
    payment: 'minipay'
  }
  getReq(app, params, function (res) {
    if (res.code == 200) {
      let param = res.datas.param.data;
      wx.requestPayment({
        timeStamp: param.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: param.nonceStr,   //随机串
        package: param.package,
        signType: param.signType,   //微信签名方式：
        paySign: param.paySign,     //微信签名
        success: function (res) {
          wx.redirectTo({
            url: "/pages/order_tabs/orderTabs?state_type=state_pay"
          })
          console.log("支付成功:", res);
        },
        fail: function (res) {
          setTimeout(() => {
            wx.showToast({
              icon: 'none',
              title: '支付未完成，订单将在10分钟后取消...',
              duration: 2000
            })
          }, 200);
          console.log("失败:", res);
        }
      });
    }
  })
}

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