const asdkUrl = "https://h5sdk.szzyqw.com"
let a_params = ''
let interval = ''
let a_gameid = "666666100216"//游戏ID，我方分配
let a_gamekey = "9f9dcda16864e268"//游戏KEY，我方分配
let a_pub = "oppominih5sdk_cnlccxx_001"//游戏PUB，我方分配
let a_appid = "32932575"
let c_cpid = ""
let iscreate = 0
let cdate = ''
let isone = 0
let isend = 0


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) {
          // 获取服务器返回的数据后调用文档的发起支付接口
          console.log('接口返回: ' + JSON.stringify(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) {
  qg.hasShortcutInstalled({
    success: function(status) {
      if(status) {
        iscreate = 1
        console.log('已创建')
      }else{
        iscreate = 0
        console.log('未创建')
      }
    }
  })
  var result = localStorage.getItem("keysdK")
  if(result!=""&&result!=null&&result!="null"){
    isone = JSON.parse(result).isone
    isend = JSON.parse(result).isend
    cdate = JSON.parse(result).cdate
  }
  
  if(iscreate==0){
    if(cdate==""){
      cdate = getDate()
      localStorage.setItem("keysdK", '{"isone":1,"isend":0,"cdate":"'+cdate+'"}')
      createIcon(0)
    }else{
      if(getDate()==cdate){//缓存时间一致
        if(isone==0){
          localStorage.setItem("keysdK", '{"isone":1,"isend":'+isend+',"cdate":"'+cdate+'"}')
          createIcon(0)
        }
      }else{
        cdate = getDate()
        localStorage.setItem("keysdK", '{"isone":1,"isend":'+isend+',"cdate":"'+cdate+'"}')
        createIcon(0)
      }
    } 
  }
  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 => {
    callback(a_res);
  })
}

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

function login(){
  return new Promise((resolve, reject) => {
    if (qg.getSystemInfoSync().platformVersionCode >= 1040) {
      qg.login({
        success: function(res) {
          let url = '/othersdkdatatrans.php?sdkabbr=oppominih5sdk&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.uid,
            "session": res.token
          }
          asdkRequestPsot(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,
                "a_token": res.token,
              }
            }
            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 data = {
    "callbackurl": payOrder.callbackurl,
    "paymoney": payOrder.paymoney*100,
    "custominfo": payOrder.custominfo,
    "customorderid": payOrder.customorderid,
    "productdesc": payOrder.productdesc,
    "productfeecode": payOrder.productfeecode,
    "appid":a_appid,
    "openid":a_params.a_token,
    "engineVersion":qg.getSystemInfoSync().platformVersionCode,
  }
  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(data);

  asdkRequestPsot(url, payOrder).then(a_res => {
    if (a_res.code == 0) {

      qg.pay({
        appId:a_appid,
        token: a_params.a_token,
        timestamp: a_res.data.extdata1,
        paySign: a_res.data.extdata2,
        orderNo:a_res.data.extdata3,
        success: function(res){
          console.log("支付成功")
          payCallback(ret)
        },
        fail: function(res){
          console.log("支付失败")
          payCallback(ret)
        }
      });
    }else{
      console.log("支付失败")
      payCallback({'code':-1,'msg':a_res.msg})
    }
  })
}

function asdkQuit(){
  console.log('oppo系统退出无效')
  var result = localStorage.getItem("keysdK")
  if(result!=""&&result!=null&&result!="null"){
    isone = JSON.parse(result).isone
    isend = JSON.parse(result).isend
    cdate = JSON.parse(result).cdate
  }
  if(iscreate==0){
    if(getDate()==cdate){//缓存时间一致
      if(isend==0){
      	localStorage.setItem("keysdK", '{"isone":'+isone+',"isend":1,"cdate":"'+cdate+'"}')
        createIcon(1)
      }else{
        qg.exitApplication()
      }
    }else{
      cdate = getDate()
      localStorage.setItem("keysdK", '{"isone":'+isone+',"isend":1,"cdate":"'+cdate+'"}')
      createIcon(1)
    }
  }else{
    qg.exitApplication()
  }
}

function asdkCreateIcon(payCallback){
  qg.installShortcut({
    success: function() {
      iscreate = 1
      let data = {'code':0,'msg':'创建icon成功'}
      payCallback(data)
    },
    fail:function(){
      let data = {'code':-1,'msg':'创建icon失败'}
      payCallback(data)
    },
  })
}

function getDate(){
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  return year+""+month+""+strDate
}

function createIcon(type){
  qg.installShortcut({
    success: function() {
      iscreate = 1
      console.log('创建icon成功')
      if(type==1)
        qg.exitApplication()
    },
    fail:function(){
      if(type==1)
        qg.exitApplication()
    }
  })
}

function asdkRewardedAd(payOrder, payCallback){
  try {
    console.log("创建OPPO激励视频广告")
    this.videoAd = window['qg'].createRewardedVideoAd({
        adUnitId: payOrder
    });
    this.videoAd.load()
    this.videoAd.onLoad(() => {
        this.videoAd.show();
    })
    this.videoAd.onError(err => {
      console.log('onError:' + JSON.stringify(err));
      let data = {'code':-1,'msg':'激励视频广告加载失败：'+JSON.stringify(err)}
      payCallback(data)
    })
    this.videoAd.onClose((res) => {
      if (res == undefined) {
        //看完广告,给奖励
        console.log("正常播放结束，可以下发游戏奖励")
        let data = {'code':0,'msg':'播放成功'}
        payCallback(data)
      } else {
        // 用户点击了【关闭广告】按钮
        console.log('==> oppoRewardVideoAd onClose', res)
        if (res.isEnded) {
          //看完广告,给奖励
          console.log("正常播放结束，可以下发游戏奖励");
          let data = {'code':0,'msg':'播放成功'}
          payCallback(data)
        } else {
          console.log("播放中途退出，不下发游戏奖励");
          let data = {'code':1,'msg':'播放失败,不提供奖励'}
          payCallback(data)
        }
      }
    });
  } catch (error) {
    let data = {'code':-1,'msg':'激励视频广告加载失败：'+JSON.stringify(error)}
    payCallback(data)
  }
}

qg.asdk = {
  asdkInit,
  asdkLogin,
  asdkSendRole,
  asdkPay,
  asdkQuit,
  asdkCreateIcon,
  asdkRewardedAd,
}
