import Notify from '../miniprogram_npm/@vant/weapp/notify/notify';
const api = require('../api/index')
const config = {  
  tabbar:["pages/index/index","pages/hotProduct/hotProduct","pages/mine/mine"]
};
function getPages(){
  var obj = {
    type: 'danger'
  }
  var pages = getCurrentPages()
  var route = pages[pages.length - 1]?.route
  if(route && config.tabbar.indexOf(route)==-1){
    obj.top = wx.getStorageSync('height')
  }
  return obj
}
function payMoney(data){
  return new Promise((resolve, reject) => { 
    api.weixinpay(data).then(res=>{
      console.log(res)
      if(res.code == 200){
        var obj = res.data.data
        wx.hideLoading()
        wx.requestPayment
            (
              {
                "timeStamp": `${obj.timestamp}`,
                "nonceStr": obj.nonceStr,
                "package": "prepay_id="+obj.prepayId,
                "signType":obj.signType,
                "paySign": obj.signature,
                "success":function(res){
                  // console.log(res)
                  // resolve(res); 
                },
                "fail":function(res){
                  var obj = getPages()
                  if(res.errMsg == 'requestPayment:fail cancel'){
                    obj.message = '取消支付'
                  }else{
                    obj.message = '支付失败'
                  }
                  if(obj.message){
                    Notify(obj)
                  }
                  // console.log(res)
                  // resolve(res); 
                },
                "complete":function(res){
                  // console.log(res)
                  resolve(res); 
                }
              }
            )
      }else if(res.code == 901){
        var obj = {
          errMsg: 'requestPayment:ok'
        }
        resolve(obj); 
      }
    }).catch(error=>{
      reject(error || '未知错误'); 
    })
  })
}

function open(data,selector='myPay'){
  var pages = getCurrentPages()
  const actionSheetRef = pages[pages.length-1].selectComponent('#'+selector)
  actionSheetRef.show(data)
}

// 导出请求方法  
module.exports = {  
  payMoney: (data) => payMoney(data),
  openPay: (data,selector) => open(data,selector)
};