const cfg = require("./sdk-mini-conf")
const asdkUrl = "https://h5sdk.szzyqw.com"
let a_params = ''
let interval = ''

//bool
if (!cfg.a_gameid || !cfg.a_gamekey || !cfg.a_pub || !cfg.a_appid || !cfg.c_cpid) {
  console.error("缺少参数")
}

//http
function asdkRequest(url, data) {
  return new Promise((resolve, reject) => {
    qg.request({
      url: asdkUrl + url,
      method: "POST",
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      data,
      success: function (a_res) {
        resolve(a_res.data)
      },
      fail: function (a_res) {
        resolve(a_res.data)
      }
    })
  })
}

// 初始化
function asdkInit(callback) {
  let url = '/mini/datatrans.php?action=mini_init'
  let data = {
    "a_gameid": cfg.a_gameid,
    "a_gamekey": cfg.a_gamekey,
    "a_pub": cfg.a_pub,
    "a_appid": cfg.a_appid,
    "c_cpid": cfg.c_cpid,
  }
  asdkRequest(url, data).then(a_res => {
    console.log('初始化返回：'+JSON.stringify(a_res))
    callback(a_res)
  })
}

// 登录
function asdkLogin(callback) {
  login().then(res => {//每次都重新登录
    callback(res)
  })
}

function login(){
  return new Promise((resolve, reject) => {
    if (qg.getSystemInfoSync().platformVersionCode >= 1063) {
      qg.login().then((res) => {
        if (res.data.token) {
          console.log('渠道返回当前用户信息: ' + JSON.stringify(res.data));
          let url = '/othersdkdatatrans.php?sdkabbr=vivominih5sdk&a_pub='+cfg.a_pub+'&a_gameid='+cfg.a_gameid+'&a_gamekey='+cfg.a_gamekey
          let data = {
            "a_gameid": cfg.a_gameid,
            "a_gamekey": cfg.a_gamekey,
            "a_pub": cfg.a_pub,
            "a_appid": cfg.a_appid,
            "c_cpid": cfg.c_cpid,
            "token": res.data.token
          }
          asdkRequest(url, data).then(a_res => {
            if (a_res.code == 0) {
              a_params = {
                "a_accountid": a_res.data.account.accountid,
                "a_sessionid": a_res.data.account.sessionid,
                "a_openid": a_res.data.account.extdata1,
              }
              console.log("login data:"+JSON.stringify(a_params))
            }
            resolve(a_res)
          })
        }
      }, (err) => {
        console.log('获取用户信息失败' + JSON.stringify(err));
        let data = {'code':-1,'msg':'获取用户信息失败' + JSON.stringify(err)}
        resolve(data)
      })
    }else{
      console.log('版本不符合，请更新');
      let data = {'code':-1,'msg':'版本不符合，请更新'}
      resolve(data)
    }
  })
}

// 上报角色信息
function asdkSendRole(roleInfo, callback) {
  let url = '/datatrans.php?action=mini_uploadinfo'
  let data = {
    "a_gameid": cfg.a_gameid,
    "a_gamekey": cfg.a_gamekey,
    "a_pub": cfg.a_pub,
    "a_sessionid": a_params.a_sessionid,
    "a_accountid": a_params.a_accountid,
    "playerid": roleInfo.playerid,
    "playername": roleInfo.playername,
    "playerlevel": roleInfo.playerlevel,
    "serverid": roleInfo.serverid,
    "servername": roleInfo.servername
  }
  asdkRequest(url, data).then(res => {
    callback(res)
  })
}

// 支付
function asdkPay(payOrder, payCallback) {
  //查询支付列表
  let url = '/datatrans.php?action=generatepayorder'
  let data = {
    "callbackurl": payOrder.callbackurl,
    "paymoney": payOrder.paymoney*100,
    "custominfo": payOrder.custominfo,
    "customorderid": payOrder.customorderid,
    "productdesc": payOrder.productdesc,
    "productfeecode": payOrder.productfeecode,
    "appid":cfg.a_appid,
    "openid":a_params.a_openid
  }
  payOrder.a_gameid = cfg.a_gameid;
  payOrder.a_gamekey = cfg.a_gamekey;
  payOrder.a_pub = cfg.a_pub;
  payOrder.a_sessionid =  a_params.a_sessionid;
  payOrder.a_accountid = a_params.a_accountid;
  payOrder.extdata = JSON.stringify(data);
 
  asdkRequest(url, payOrder).then(a_res => {
    if (a_res.code == 0) {
      console.log("pay info:"+JSON.stringify(a_res))
      let params = {
        "appId":cfg.a_appid,
        "cpOrderNumber":a_res.data.orderid,
        "productName":payOrder.productdesc,
        "productDesc":payOrder.productdesc,
        "orderAmount":payOrder.paymoney*100,
        "notifyUrl":a_res.data.extdata1,
        "extInfo":a_res.data.orderid,
        "vivoSignature":a_res.data.extdata2,
      }
      qg.pay({
        orderInfo: JSON.stringify(params),
        success: function(ret) {
          console.log("支付成功")
          payCallback(ret)
        },
        fail: function (err) {
          console.log("支付失败")
          payCallback(ret)
        },
        cancel: function (ret) {
          console.log("支付取消")
          payCallback(ret)
        },
        complete: function(){
          console.log("支付完成")
          payCallback(ret)
        }
      })
    }else{
      console.log("支付失败")
      payCallback({'code':-1,'msg':a_res.msg})
    }
  })
}

qg.asdk = {
  asdkInit,
  asdkLogin,
  asdkSendRole,
  asdkPay,
  asdkRequest,
}