const crypto = require('crypto');
const cryptoJS = require("crypto-js");
var System=require("../../system");
var settings=require("../../../config/settings");
const logCtl=System.getObject("web.oplogCtl");
class BankTradeApi{
  constructor(){
    this.profitcenterS=System.getObject("service.profitcenterSve");
    this.yunzhanghuAppKey=settings.apiconfig.yunzhanghuAppKey();
    this.yunzhanghuDESKey=settings.apiconfig.yunzhanghuDESKey();
  }
   async test(obj){
     console.log(obj);
     return "xxx";
   }
   async tradecallback(obj){
     var data=obj.data==null?"":obj.data;;
     var mess=obj.mess==null?"":obj.mess;
     var timestamp=obj.timestamp==null?"":obj.timestamp;
     var sign=obj.sign==null?"":obj.sign;
     if(data==""||mess==""||timestamp==""||sign==""||data=="undefined"
        ||mess=="undefined"||timestamp=="undefined"||sign=="undefined"){
          return "info Failure"
     }
     let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
     let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
     let appKey=this.yunzhanghuAppKey;
     var tmp_sign_type="sha256";
     var signContent="data="+data+"&mess="+mess+"&timestamp="+timestamp+"&key="+appKey;
     var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');
     if(tmpSign!=sign){
       return "sign Failure"
     }
     //解密信息
     var bytes = cryptoJS.TripleDES.decrypt(data, keyHex, {
       iv: ivHex
     });
     var plaintext = bytes.toString(cryptoJS.enc.Utf8);
     var tmpResult=JSON.parse(plaintext);
     tmpResult.descStr="云支付返回信息";
     //日志记录
     logCtl.info({
        optitle:"用于云支付回调地址->解密后的数据",
        op:"base/api/impl/banktrade/tradecallback",
        content:"云支付返回信息：：：："+JSON.stringify(tmpResult),
        clientIp:""
      });
     var putItem={
         bankTradeNum:tmpResult.data.ref,
         opDesc:JSON.stringify(tmpResult)
     };
     var sqlWheres={where:{tradeOrderNum:tmpResult.data.order_id}};
     if(tmpResult.data.status!=1){
       //打款失败
       putItem.opType="issueError";
     }
     //更改提现申请状态
     await this.profitcenterS.dao.updateByWhere(putItem,sqlWheres);
     return tmpResult.data.status!=1?"Failure":"success";
   }
}
module.exports=BankTradeApi;
