const System=require("../../system");
const settings=require("../../../config/settings");
const ServiceBase=require("../sve.base")
var WXPay = require('wx-pay');
const uuidv4 = require('uuid/v4');
const querystring = require('querystring');
const crypto = require('crypto');
const cryptoJS = require("crypto-js");
const logCtl=System.getObject("web.oplogCtl");
class TradeService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(TradeService));
     this.appDao=System.getObject("db.appDao");
     this.userDao=System.getObject("db.userDao");
     this.accountDao=System.getObject("db.accountDao");
     this.productDao=System.getObject("db.productDao");
     this.orderDao=System.getObject("db.orderDao");
     this.orderflowDao=System.getObject("db.orderflowDao");
     this.tradeDao=System.getObject("db.tradeDao");
     this.profitcenterDao=System.getObject("db.profitcenterDao");
     this.wxSvr=System.getObject("service.wxSve");
     this.wxpay = WXPay({
     	appid: 'wx6f3ebe44defe336a',
     	mch_id: '1232813602',
     	partner_key: 'sinotone2014sinotone2014sinotone',
     });
     this.yunzhanghuApiUrl=settings.apiconfig.yunzhanghuApiUrl();//云帐户提现接口url
     this.yunzhanghuCallbackApiUrl=settings.apiconfig.yunzhanghuCallbackApiUrl();//云帐户提现回调接口url
     this.yunzhanghuQueryAccountsUrl=settings.apiconfig.yunzhanghuQueryAccountsUrl();//云帐户商户查询余额接口url
     this.yunzhanghuVerifyBankCardUrl=settings.apiconfig.yunzhanghuVerifyBankCardUrl();//云帐户验证银行卡的有效性接口url
     this.yunzhanghuDESKey=settings.apiconfig.yunzhanghuDESKey();
     this.yunzhanghuDealer_id=settings.apiconfig.yunzhanghuDealer_id();
     this.yunzhanghuBroker_id=settings.apiconfig.yunzhanghuBroker_id();
     this.yunzhanghuAppKey=settings.apiconfig.yunzhanghuAppKey();
     this.yunzhanghuDESKey=settings.apiconfig.yunzhanghuDESKey();
     this.yunzhanghuTxXz=settings.apiconfig.yunzhanghuTxXz();
     this.bossWithdrawApplyingKey=settings.apiconfig.bossWithdrawApplyingKey();
  }
  async getCreateUUId(code){
    var tcode=code==null?"":code;
    var myDate=new Date();
    var uid=await this.getUidStr(8,60);
    return  tcode+""+myDate.getFullYear()+""+(myDate.getMonth()+1)+""+myDate.getDate()+""+myDate.getMilliseconds()+""+uid;
  }
  async getUidStr(len, radix) {
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
      var uuid = [], i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
      } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random()*16;
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join('');
  }
  async findOneByIdKey(tradekey){
    var rtn=await this.dao.findOne({idkey:tradekey});
    return rtn;
  }
  async closeWxOrder(idkey){
    return this.wxSvr.closeWxOrder(idkey);
  }
  async queryWxOrder(idkey){
    var s=  await this.wxSvr.queryWxOrder(idkey);
    console.log(s);
    return s;
  }

  async createUnifiedOrder(desc,amount,notify_url,pid,attach,out_trade_no){
    return this.wxSvr.createUnifiedOrder(desc,amount,notify_url,pid,attach,out_trade_no);
  }
  async createOrderPaid(obj){
   var amount= obj.totalSum;
   // if(settings.env=="dev"){
   //   amount=1;
   // }else{
   //   //amount=Number(amount)*100;
   //   amount=1;
   // }
   console.log(amount);
   // var u=uuidv4();
   // var out_trade_no=u.replace(/\-/g,"");
   // var out_trade_no=obj.orderNum;
   var self=this;
   var promise= await this.wxSvr.createUnifiedOrder(obj.itemName,amount,'http://boss.gongsibao.com/wx/pay',obj.itemCode);

   // var promise=new Promise(function(resv,rej){
   //   self.wxpay.createUnifiedOrder({
   //     body: obj.itemName,
   //     out_trade_no: out_trade_no,
   //     total_fee: Number(amount),
   //     spbill_create_ip: '192.168.2.210',
   //     notify_url: 'http://boss.gongsibao.com/web/notify',
   //     trade_type: 'NATIVE',
   //     product_id: obj.itemCode,
   //   }, function(err, result){
   //      if(err){
   //        return rej(err);
   //      }else{
   //        var qrurl=settings.apiconfig.qcurl.replace("{address}",result.code_url);
   //        result.qrurl=qrurl;
   //        result.tradekey=out_trade_no;
   //        return resv(result);
   //      }
   //   });
   // });
   return promise;
 }

  async create(user,tradeObj){
    //var app=await this.appDao.model.findOne({where:{id:user.app_id}});
    //var usr =await this.userDao.model.findOne({where:{id:user.id}});
    var usr = this.db.models.user.build(user);
    var account=await this.accountDao.model.findOne({where:{id:user.account_id}});
    var self=this;
    console.log(tradeObj);
    return this.db.transaction(async function (t){
      self.cacheManager["AccountBalanceCache"].del(user.account_id,user.app_id);
      return  self.dao.create2(usr,account,tradeObj,t);
    });
  }
  async createOrderTrade(qobj,orderNum,payResult,payUser){
    var order = await this.orderDao.findOneByOrderNum(orderNum);
    var user = await this.userDao.findById(order.user_id);
    order=order.dataValues;
    user=user.dataValues;
    var that=this;
    return this.db.transaction(async function (t){
      order.orderStatus="4";
      order.paymentSerialNumber=payResult.transaction_id;
      order.paymentPlatform="微信";
      order.payUserId=payUser.id;
      order.payNickName=payUser.nickName;
      order.payAppId=payUser.appid;
      var orderResult=await that.orderDao.update(order,t);
      order.orderStatusName="付款成功";
      if(order.id!=null){
        var orderflowObj={
           app_id:order.app_id,
           user_id:order.user_id,
           userName:user.userName,
           nickName:user.nickName,
           orderNum:order.orderNum,
           opContent:"订单付款"
        };
        var orderflow = await that.orderflowDao.create(orderflowObj,t);//订单流程
        qobj["app_id"]=order.app_id;
        qobj["account_id"]=user.account_id;
        qobj["user_id"]=order.user_id;
        qobj["username"]=user.userName;
        qobj["nickName"]=user.nickName;
        qobj["orderNum"]=order.orderNum;
        var trade= await that.dao.createOrderTrade(qobj,t);
        trade.dataValues["order"]=order;
        return trade;
      }else{
        return null;
      }
    });
  }
  async withdrawMoney(user,partnerinfo,amount){
    if(amount<=0){
      return {code:-210,msg:"输入的金额有误"};
    }
    //settings配置，云帐户提现是否受限制-1不受限制
    var yunzhanghuTxXzSettings=parseFloat(this.yunzhanghuTxXz);
    if(yunzhanghuTxXzSettings>=0){
       amount=yunzhanghuTxXzSettings;
    }
    var self=this;
    return this.db.transaction(async function (t){
      //提现写表操作
      //是否配置pconfig提现限制，如果配置则验证限制规则
      var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
      if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
         var resultPconfig= pconfig.find(item => {
             return item.configType === "withdrawalLimit";
         });
         if(resultPconfig!=null){
           var pconfigTxXz=parseFloat(resultPconfig.configValue);
           if(pconfigTxXz==0){
             return {code:-220,msg:"目前该系统提现申请发放故障，敬请期待！"};
           }
           if(pconfigTxXz>0&&amount>pconfigTxXz){
             return {code:-230,msg:"提现金额大于单笔交易额度，单笔最大交易额度为"+pconfigTxXz};
           }
         }
      }//提现申请发放额度有限制

      //用户已经申请，待发放的总金额+此次申请的金额=申请总金额
      var rd=await self.profitcenterDao.findSum('totalSum',{where:{account_id:user.account_id,opType:"applying"}});
      var applyingSum=rd?rd:0;
      var tmpSumTotal=parseFloat(amount)+parseFloat(applyingSum);

      //用户交易总金额Sum，tradeType：orderPersonFee订单个人分润、recommendFee推荐分润、cashWithdrawal现金提现
      var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
                           [self.dao.db.Op.and]: [{account_id:user.account_id}]}};
      var sumTotal=await self.dao.findSum('renAmount',tmpWhere);
      var tradeTotalSum=sumTotal?parseFloat(sumTotal):0;
      if(tmpSumTotal>tradeTotalSum){
        return {code:-240,msg:"输入金额有误，已申请金额为："+applyingSum+"，剩余可申请金额为："+(tradeTotalSum-applyingSum)};
      }
      var aid=user.account_id;
      var userAccountInfo=await self.accountDao.findById(aid);
      if(userAccountInfo==null){
        return  {code:-250,msg:"用户信息有误"};
      }
      //用户帐户总金额
      if(tmpSumTotal>userAccountInfo.renBalance){
        return {code:-260,msg:"输入金额有误，已申请金额为："+applyingSum+"，剩余可申请金额为："+(userAccountInfo.renBalance-applyingSum)};
      }
      var tmpOpIdentify= await self.getCreateUUId("sq");
      var orderId=await self.getCreateUUId("tx");
      //添加新的提现申请记录
      var addParams={
          account_id:user.account_id,
          userName:user.userName,
          opTypeName:"申请中",
          opType:"applying",
          totalSum:amount,
          identityCard:partnerinfo.identityCard,
          cardNo:partnerinfo.cardNo,
          realName:partnerinfo.realName,
          opIdentify:tmpOpIdentify,
          tradeOrderNum:orderId
      };
      var item=await self.profitcenterDao.create(addParams,t);
      item=item.get({plain:true});

      let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
      let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
      var cipherParams={
        id:item.id,
        account_id:user.account_id,
        userName:user.userName,
        opType:"applying",
        totalSum:amount,
        identityCard:partnerinfo.identityCard,
        cardNo:partnerinfo.cardNo,
        realName:partnerinfo.realName,
        opIdentify:tmpOpIdentify,
        tradeOrderNum:orderId
      };
      var stringStr = JSON.stringify(cipherParams);
      var ciphertext = cryptoJS.TripleDES.encrypt(stringStr, keyHex, { iv: ivHex }).toString();
      var cipherData=encodeURIComponent(ciphertext);
      var putItem={
          id:item.id,
          cipherData:cipherData
      };
      await self.profitcenterDao.update(putItem,t);
      return {code:1,msg:"提现成功"};
    });
  }
  //提现申请
  async setWithdrawMoneyApplying(user,partnerinfo,amount){
    if(amount<=0){
      return {code:-210,msg:"输入的金额有误"};
    }
    //settings配置，云帐户提现是否受限制-1不受限制
    var yunzhanghuTxXzSettings=parseFloat(this.yunzhanghuTxXz);
    if(yunzhanghuTxXzSettings>=0){
       amount=yunzhanghuTxXzSettings;
    }
    var self=this;
    return this.db.transaction(async function (t){
      //提现写表操作
      //是否配置pconfig提现限制，如果配置则验证限制规则
      var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
      if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
         var resultPconfig= pconfig.find(item => {
             return item.configType === "withdrawalLimit";
         });
         if(resultPconfig!=null){
           var pconfigTxXz=parseFloat(resultPconfig.configValue);
           if(pconfigTxXz==0){
             return {code:-220,msg:"目前该系统提现申请发放故障，敬请期待！"};
           }
           if(pconfigTxXz>0&&amount>pconfigTxXz){
             return {code:-230,msg:"提现金额大于单笔交易额度，单笔最大交易额度为"+pconfigTxXz};
           }
         }
      }//提现申请发放额度有限制

      //用户已经申请，待发放的总金额+此次申请的金额=申请总金额
      var rd=await self.profitcenterDao.findSum('totalSum',{where:{account_id:user.account_id,opType:"applying"}});
      var applyingSum=rd?rd:0;
      var tmpSumTotal=parseFloat(amount)+parseFloat(applyingSum);

      //用户交易总金额Sum，tradeType：orderPersonFee订单个人分润、recommendFee推荐分润、cashWithdrawal现金提现
      // var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
      //                      [self.dao.db.Op.and]: [{user_id: user.id}, {app_id: user.app_id}]}};
      var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
                           [self.dao.db.Op.and]: [{account_id:user.account_id}]}};
      var sumTotal=await self.dao.findSum('renAmount',tmpWhere);
      var tradeTotalSum=sumTotal?parseFloat(sumTotal):0;
      if(tmpSumTotal>tradeTotalSum){
        return {code:-240,msg:"输入金额有误，已申请金额为："+applyingSum+"，剩余可申请金额为："+(tradeTotalSum-applyingSum)};
      }
      var aid=user.account_id;
      var userAccountInfo=await self.accountDao.findById(aid);
      if(userAccountInfo==null){
        return  {code:-250,msg:"用户信息有误"};
      }
      //用户帐户总金额
      if(tmpSumTotal>userAccountInfo.renBalance){
        return {code:-260,msg:"输入金额有误，已申请金额为："+applyingSum+"，剩余可申请金额为："+(userAccountInfo.renBalance-applyingSum)};
      }
      var tmpOpIdentify= await self.getCreateUUId("sq");
      var orderId=await self.getCreateUUId("tx");
      //添加新的提现申请记录
      var addParams={
          app_id:user.app_id,
          user_id:user.id,
          account_id:user.account_id,
          userName:user.userName,
          opTypeName:"申请中",
          opType:"applying",
          totalSum:amount,
          identityCard:partnerinfo.identityCard,
          cardNo:partnerinfo.cardNo,
          realName:partnerinfo.realName,
          opIdentify:tmpOpIdentify,
          tradeOrderNum:orderId
      };
      var item=await self.profitcenterDao.create(addParams,t);
      item=item.get({plain:true});

      let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
      let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
      var cipherParams={
        id:item.id,
        app_id:user.app_id,
        user_id:user.id,
        account_id:user.account_id,
        userName:user.userName,
        opType:"applying",
        totalSum:amount,
        identityCard:partnerinfo.identityCard,
        cardNo:partnerinfo.cardNo,
        realName:partnerinfo.realName,
        opIdentify:tmpOpIdentify,
        tradeOrderNum:orderId
      };
      var stringStr = JSON.stringify(cipherParams);
      var ciphertext = cryptoJS.TripleDES.encrypt(stringStr, keyHex, { iv: ivHex }).toString();
      var cipherData=encodeURIComponent(ciphertext);
      var putItem={
          id:item.id,
          cipherData:cipherData
      };
      await self.profitcenterDao.update(putItem,t);
      return {code:1,msg:"ok"};
    });
  }
  //提现申请发放
  async setWithdrawMoney(user){
      var self=this;
      let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
      let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
      var resultSucceed=0;
      var resultFailure=0;
      var resultTotal=0;
      //申请记录
      var sql="select `id`,`app_id`,`user_id`,`account_id`,`userName`,`nickName`,`opAppId`,`opUserId`,`opUserName`,`opNickName`,`opType`,`totalSum`,`identityCard`,`cardNo`,`realName`,`cipherData`,`signData`,`opIdentify`,`tradeOrderNum` from h_profitcenter where opType=:opType";
      var applyingData= await self.profitcenterDao.customQuery(sql,{opType:"applying"});
      resultTotal=applyingData.length;
      if(applyingData==null||resultTotal<=0){
        return {code:-210,msg:"要发放的数据为空，无需发放",total:resultTotal,succeed:resultSucceed,failure:resultFailure};
      }
      for (let i = 0; i < resultTotal; i++) {
        var executeResult=null;
        var tmpItem=applyingData[i];
        if(tmpItem!=null){
          if(tmpItem.cipherData==null||tmpItem.cipherData==""){
            continue;
          }
        try {
            executeResult= await self.db.transaction(async function (t){
                var cipherDataStr=decodeURIComponent(tmpItem.cipherData);
                var bytes = cryptoJS.TripleDES.decrypt(cipherDataStr, keyHex, {
                  iv: ivHex
                });
                var plaintext = bytes.toString(cryptoJS.enc.Utf8);
                var tmpResult=JSON.parse(plaintext);
                var tmpItemTotalSum= parseFloat(tmpItem.totalSum);
                // console.log("tmpResult--------------------------------------->>>>>>>>>>>>>>");
                // console.log(tmpResult);
                // console.log("tmpItem**********************************************>>>>>>>>>>>>>>");
                // console.log(tmpItem);

                if(tmpResult.id!=tmpItem.id||tmpResult.app_id!=tmpItem.app_id||tmpResult.user_id!=tmpItem.user_id||tmpResult.opType!=tmpItem.opType
                  ||tmpResult.totalSum!=tmpItemTotalSum||tmpResult.identityCard!=tmpItem.identityCard||tmpResult.cardNo!=tmpItem.cardNo
                  ||tmpResult.realName!=tmpItem.realName||tmpResult.account_id!=tmpItem.account_id||tmpResult.opIdentify!=tmpItem.opIdentify
                  ||tmpResult.tradeOrderNum!=tmpItem.tradeOrderNum){
                    return {code:-210,msg:"数据信息解析有误，请您联系技术"};
                }
                //是否配置pconfig提现限制，如果配置则验证限制规则
                var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
                if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
                   var resultPconfig= pconfig.find(item => {
                       return item.configType === "withdrawalLimit";
                   });
                   if(resultPconfig!=null){
                     var pconfigTxXz=parseFloat(resultPconfig.configValue);
                     if(pconfigTxXz==0){
                       return {code:-220,msg:"目前该系统提现申请发放故障，敬请期待！"};
                     }
                     if(pconfigTxXz>0&&tmpResult.totalSum>pconfigTxXz){
                       return {code:-230,msg:"提现金额大于单笔交易额度，单笔最大交易额度为"+pconfigTxXz};
                     }
                   }
                }//提现申请发放额度有限制
                //平台帐户判断,平台现金在提报时利润已经分配处理完毕，在此不用进行处理
                //用户帐户判断
                var aid=tmpResult.account_id;
                var userAccountInfo=await self.accountDao.findById(aid);
                // console.log("用户-------------------------------------------------------------");
                // console.log(userAccountInfo);
                if(userAccountInfo==null){
                  return  {code:-240,msg:"用户信息有误"};
                }
                var userAmount=userAccountInfo.renBalance-tmpResult.totalSum;
                if(userAmount<0){
                  return {code:-250,msg:"用户帐户金额不足"};
                }
                //用户帐户更新
                await self.accountDao.update({renBalance:userAmount,id:aid},t);
                var tmpDate=new Date();
                var tradeLog={app_id:tmpItem.app_id,
                                       account_id:tmpItem.account_id,
                                       user_id:tmpItem.user_id,
                                       username:tmpItem.userName,
                                       nickName:tmpItem.nickName,
                                       renAmount:-tmpResult.totalSum,
                                       remark:"用户提现申请发放操作",
                                       tradeDate:tmpDate,
                                       tradeType:"cashWithdrawal",
                                       status:"unSettle"
                                     };
                //用户添加交易记录
                var addTradeLog = await self.dao.model.create(tradeLog,t);
                // 平台现金在提报时利润已经分配处理完毕，在此不用进行处理

                var tmpOpIdentify= await self.getCreateUUId("ff");
                var putItem={
                    id:tmpResult.id,
                    opType:"issued",
                    opAppId:user.app_id,
                    opUserId:user.user_id,
                    opUserName:user.userName,
                    opNickName:user.nickName,
                    opIdentify:tmpOpIdentify
                };
                //更改提现申请状态
                await self.profitcenterDao.update(putItem,t);
                //发放操作
                self.withdrawMoneySve(tmpResult.tradeOrderNum,tmpResult.totalSum,tmpResult.realName,tmpResult.cardNo,tmpResult.identityCard,tmpResult.id,tmpResult.app_id);
                resultSucceed=resultSucceed+1;
                return {code:1,msg:"ok"}
              });  //处理发放逻辑----------结束
        } catch (e) {
          return {code:-200,msg:e.message};
        }
        // console.log("-------------------------------------------------------executeResult");
        // console.log(executeResult);
        if(executeResult.code!=1){
          resultFailure=resultFailure+1;
          var stringStr = JSON.stringify(tmpItem);
          //日志记录
          logCtl.error({
             optitle:"提现申请发放现金异常,openid="+obj.openid+"，onlycode="+obj.onlycode,
             op:"base/service/impl/tradeSve/setWithdrawMoney",
             content:"返回参数code="+executeResult.code+"，msg="+executeResult.msg+"tmpItem@@="+stringStr,
             clientIp:""
           });
        }
      }
    }
      return {code:1,msg:"ok",total:resultTotal,succeed:resultSucceed,failure:resultFailure};
  }
  //提现Api，交易订单号、交易金额、真实姓名、银行卡号、身份证号、用户id、平台id
  async withdrawMoneySve(orderId,reqAmount,reqRealName,reqCardNo,reqIdentityCard,userId,appId){
    let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
    let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
    let appKey=this.yunzhanghuAppKey;
    var tmpData={
      	order_id:orderId,
      	dealer_id:this.yunzhanghuDealer_id,
      	broker_id:this.yunzhanghuBroker_id,
      	real_name: reqRealName,//开户人
        card_no: reqCardNo,//银行卡
      	phone_no:"",
      	id_card: reqIdentityCard,//身份证号
        pay:reqAmount.toString(),
      	anchor_id: "",
      	notes: userId+"_"+appId,//用户id_用户平台id
      	pay_remark: "",
      	notify_url: this.yunzhanghuCallbackApiUrl
      };
      //data加密
      var cipherDataStr=JSON.stringify(tmpData);
      var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
      var tmpMess=Math.round(Math.random()*100000);
      var tmpTimestamp=parseInt(Date.now() / 1000);
      var tmp_sign_type="sha256";

      var tmpSign={
          data:cipherData,
          mess:tmpMess,
          timestamp:tmpTimestamp,
          key:appKey
      };

      var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
      var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');

      var reqData={
          data:cipherData,
          mess:tmpMess,
          timestamp:tmpTimestamp,
          sign:tmpSign,
          sign_type:tmp_sign_type
      };

      var ttReqData=querystring.stringify(reqData);
      //日志记录
      logCtl.info({
         optitle:"提现Api->info",
         op:"base/service/impl/tradeSve/withdrawMoneySve",
         content:"提现=>info：请求参数待加密字符串cipherDataStr="+cipherDataStr+"，api-ttReqData==::"+ttReqData,
         clientIp:""
       });
      var rc=System.getObject("util.restClient");
      var rtn=await rc.execPost3(ttReqData,this.yunzhanghuApiUrl);

      var apiResult=JSON.parse(rtn.stdout);
      if(apiResult.code!="0000"){
        //日志记录
        logCtl.info({
           optitle:"提现Api->info返回异常：",
           op:"base/service/impl/tradeSve/withdrawMoneySve",
           content:"提现=>info：请求参数待加密字符串cipherDataStr="+cipherDataStr+"，api-ttReqData==::"+ttReqData+"，ResultCode="+apiResult.code+"，ResultStdout="+rtn.stdout,
           clientIp:""
         });
        //提现api接口错误
       return {code:-100,msg:apiResult.code,data:rtn.stdout};
      }
      return {code:1,msg:"ok",data:null};
  }
  //查看商户余额
  async getBankCardInfo(){
    let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
    let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
    let appKey=this.yunzhanghuAppKey;
    var tmpData={
      	dealer_id:this.yunzhanghuDealer_id,
      };
      //data加密
      var cipherDataStr=JSON.stringify(tmpData);
      var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
      var tmpMess=Math.round(Math.random()*100000);
      var tmpTimestamp=parseInt(Date.now() / 1000);
      var tmp_sign_type="sha256";

      var tmpSign={
          data:cipherData,
          mess:tmpMess,
          timestamp:tmpTimestamp,
          key:appKey
      };

      var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
      var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');

      var reqDataInfo="\\?mess\\="+tmpMess+"\\&sign_type\\="+tmp_sign_type+"\\&timestamp\\="+tmpTimestamp+"\\&data\\="+encodeURIComponent(cipherData)+"\\&sign\\="+tmpSign;
      //日志记录
      logCtl.info({
         optitle:"查看商户余额Api->info",
         op:"base/service/impl/tradeSve/getBankCardInfo",
         content:"提现=>info：请求参数待加密字符串cipherDataStr="+cipherDataStr+"，api-reqDataInfo="+reqDataInfo,
         clientIp:""
       });
      var rc=System.getObject("util.restClient");
      var rtn=await rc.execGet3(this.yunzhanghuQueryAccountsUrl+reqDataInfo);//this.yunzhanghuApiUrl

      var apiResult=JSON.parse(rtn.stdout);
      if(apiResult.code!="0000"){
        //日志记录
        logCtl.error({
           optitle:"查看商户余额返回值异常Api->info",
           op:"base/service/impl/tradeSve/getBankCardInfo",
           content:"提现=>info：请求参数待加密字符串cipherDataStr="+cipherDataStr+"，api-reqDataInfo="+reqDataInfo+"，ResultCode="+apiResult.code+"，ResultStdout="+rtn.stdout,
           clientIp:""
         });
        //提现api接口错误
       return {code:-100,msg:apiResult.code,data:rtn.stdout};
      }
      return {code:1,msg:apiResult.data.dealer_infos[0].bank_card_balance,data:apiResult.data.dealer_infos};
  }
  //验证银行卡有效性
  async verifyBankcard(cardNo,idCard,realName){//卡号、身份证、开户姓名
    let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
    let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
    let appKey=this.yunzhanghuAppKey;
    var tmpData={
        card_no:cardNo,
        id_card:idCard,
        real_name:realName
      };
      //data加密
      var cipherDataStr=JSON.stringify(tmpData);
      var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
      var tmpMess=Math.round(Math.random()*100000);
      var tmpTimestamp=parseInt(Date.now() / 1000);
      var tmp_sign_type="sha256";

      var tmpSign={
          data:cipherData,
          mess:tmpMess,
          timestamp:tmpTimestamp,
          key:appKey
      };

      var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
      var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');

      var reqData={
          data:cipherData,
          mess:tmpMess,
          timestamp:tmpTimestamp,
          sign:tmpSign,
          sign_type:tmp_sign_type
      };

      var ttReqData=querystring.stringify(reqData);
      //日志记录
      logCtl.info({
        optitle:"验证银行卡有效性信息info",
        op:"base/service/impl/tradeSve/verifyBankcard",
        content:"请求参数cipherDataStr待加密="+cipherDataStr+"，api-ttReqData="+ttReqData,
        clientIp:""
      });
      var rc=System.getObject("util.restClient");
      var rtn=await rc.execPost3(ttReqData,this.yunzhanghuVerifyBankCardUrl);

      var apiResult=JSON.parse(rtn.stdout);
      if(apiResult.code!="0000"){
        //日志记录
        logCtl.error({
          optitle:"验证银行卡有效性信息info",
          op:"base/service/impl/tradeSve/verifyBankcard",
          content:"请求参数cipherDataStr待加密="+cipherDataStr+"，api-ttReqData="+ttReqData+"，ResultCode="+apiResult.code+"，ResultStdout="+rtn.stdout,
          clientIp:""
        });
        //提现api接口错误
       return {code:-100,msg:apiResult.code,data:rtn.stdout};
      }
      return {code:1,msg:"ok",data:null};
  }
}
module.exports=TradeService;
