const system=require("../../../system");
const settings=require("../../../../config/settings");
const ServiceBase=require("../../sve.base")
var WXPay = require('wx-pay');
const uuidv4 = require('uuid/v4');
class ApiTradeService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ApiTradeService));
  }
  async create(tradeObj){
    var self=this;
    return this.db.transaction(async function (t){
      //获取缓存二个值，一个是赠送次数,一个是调用价格
      var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
      var apiInitGift = pconfig.find(item => {
          return item.configType === "apiInitGift";
      });
      var apiCallPrice = pconfig.find(item => {
          return item.configType === "apiCallPrice";
      });
      var app=await self.cacheManager["AppCache"].cacheApp(tradeObj.appkey,null,1);
      tradeObj.app_id=app.id;
      var callCache=await self.cacheManager["ApiCallCountCache"].getApiCallCount(tradeObj.appkey,tradeObj.op);
      var callAccuCache=await self.cacheManager["ApiAccuCache"].getApiCallAccu(tradeObj.appkey);
      var calledCount=Number(callCache.callcount);
      var balance=Number(callCache.amount);
      if(calledCount>Number(apiInitGift.configValue)){//调用次数大于免费次数
         tradeObj.amount=Number(apiCallPrice.configValue);
      }else{
         tradeObj.amount=0;
      }
      //解决日志大于4000写入的问题
      if(tradeObj.params.length>3980){
        tradeObj.params=tradeObj.params.substring(0,3980);
      }
      var apitrade=await self.dao.model.create(tradeObj,{transaction:t});
      //按照调用方法缓存
      await self.cacheManager["ApiCallCountCache"].addCallCount(tradeObj.appkey,tradeObj.op,1);
      await self.cacheManager["ApiCallCountCache"].addCallBalance(tradeObj.appkey,tradeObj.op,tradeObj.amount);
      //累计缓存调用次数和金额
      await self.cacheManager["ApiAccuCache"].addCallCount(tradeObj.appkey,1);
      await self.cacheManager["ApiAccuCache"].addCallBalance(tradeObj.appkey,tradeObj.amount);
  //    await self.cacheManager["ApiCircuitBreakers"].addCallCount(-1);
      return apitrade;
    });
  }

  async beforesel(tradeObj){
    var self=this;
    var callCaches=await self.cacheManager["ApiCircuitBreakers"].getApiCall();
    var calledCounts=Number(callCaches.callcount);
    if( calledCounts>100 ){
//      return {status:-1,msg:"服务器繁忙，请稍候再试",data:null};
    }
    else {
//      await self.cacheManager["ApiCircuitBreakers"].addCallCount(1);
    }
    var callCache=await self.cacheManager["ApiCircuitBreakerCache"].getApiCall(tradeObj.appkey);
    var calledCount=Number(callCache.callcount);
    if( calledCount>1000 ){
      return {status:-1,msg:"调用次数太多，请稍候再试",data:null};
    }
    else {
      var result=await self.cacheManager["ApiCircuitBreakerCache"].addCallCount(tradeObj.appkey,1);
    }
    return {status:1,msg:"OK"};
  }
}
module.exports=ApiTradeService;
