const asdkUrl = "https://h5sdk.szzyqw.com";
let a_params = '';
let interval = '';
let a_gameid = "666666100216";//游戏ID，我方分配
let a_gamekey = "9f9dcda16864e268";//游戏KEY，我方分配
let a_pub = "xiaomiminih5sdk_cnlccxx_001";//游戏PUB，我方分配
let a_appid = "2882303761520395492";
let c_cpid = "";

function asdkRequestPsot(url, data) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', asdkUrl+url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('charset', 'UTF-8');
    xhr.onreadystatechange = function () {
        if (xhr.status === 200) {
          // 获取服务器返回的数据后调用文档的发起支付接口
          if(xhr.response!=''){
            var a_res = JSON.parse(xhr.response);
            resolve(a_res)
          }
        }
        else {
          let a_res = {'code':-1,'msg':'error'}
          resolve(a_res)
        }
    };
    xhr.send(JSON.stringify(data));
  });
}

// 初始化
function asdkInit(callback) {
  let url = '/mini/datatrans.php?action=mini_init';
  let data = {
    "a_gameid": a_gameid,
    "a_gamekey": a_gamekey,
    "a_pub": a_pub,
    "a_appid": a_appid,
    "c_cpid": c_cpid,
  }
  asdkRequestPsot(url, data).then(a_res => {
    console.log("init："+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 >= 1050) {
      qg.login({
        success: function(res) {
          let url = '/othersdkdatatrans.php?sdkabbr=xiaomiminih5sdk&a_pub='+a_pub+'&a_gameid='+a_gameid+'&a_gamekey='+a_gamekey;
          let data = {
            "a_gameid": a_gameid,
            "a_gamekey": a_gamekey,
            "a_pub": a_pub,
            "a_appid": a_appid,
            "c_cpid": c_cpid,
            "account": res.data.appAccountId,
            "session": res.data.session
          }
          asdkRequestPsot(url, data).then(a_res => {
            console.log('获取用户信息成功' + JSON.stringify(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": res.data.appAccountId,
                "a_token": res.data.session,
              }
            }
            resolve(a_res)
          })
        },
        fail: function(res){
          console.log('获取用户信息失败' + JSON.stringify(res));
          let data = {'code':-1,'msg':'获取用户信息失败' + JSON.stringify(res)}
          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": a_gameid,
    "a_gamekey": a_gamekey,
    "a_pub": 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
  }
  asdkRequestPsot(url, data).then(res => {
    callback(res)
  })
}

// 支付
function asdkPay(payOrder, payCallback) {
  //查询支付列表
  let url = '/datatrans.php?action=generatepayorder'
  let orderInfo = {
    "appId": a_appid,
    "appAccountId": a_params.a_openid,
    "session": a_params.a_token,
    "cpOrderId": '',
    "cpUserInfo": '',
    "displayName": payOrder.productfeecode,
    "feeValue":payOrder.paymoney*100,
    "sign":'',
  }
  
  payOrder.a_gameid = a_gameid;
  payOrder.a_gamekey = a_gamekey;
  payOrder.a_pub = a_pub;
  payOrder.a_sessionid =  a_params.a_sessionid;
  payOrder.a_accountid = a_params.a_accountid;
  payOrder.extdata = JSON.stringify(orderInfo);

  asdkRequestPsot(url, payOrder).then(a_res => {
    if (a_res.code == 0) {
      orderInfo.cpOrderId = a_res.data.extdata1;
      orderInfo.cpUserInfo = a_res.data.extdata1;
      orderInfo.sign = a_res.data.extdata2;
      console.log("支付参数："+JSON.stringify(orderInfo));
      qg.pay({
        orderInfo,
        success: function(res){
          console.log("支付成功")
          payCallback(ret)
        },
        fail: function(res){
          console.log("支付失败")
          payCallback(ret)
        }
      });
    }else{
      console.log("支付失败")
      payCallback({'code':-1,'msg':a_res.msg})
    }
  })
}

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