var System=require("../../system")
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const logCtl=System.getObject("web.oplogCtl");
class TradeCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(TradeCtl));
     //this.appS=system.getObject("service.appSve");
    this.accountSve=System.getObject("service.accountSve");
    this.pconfigSve=System.getObject("service.pconfigSve");
    this.orderSve=System.getObject("service.orderSve");
    this.userSve=System.getObject("service.userSve");
    this.profitcenterSve=System.getObject("service.profitcenterSve");
   }
   async getBankCardInfo(queryobj,qobj,req){
     var result=await this.service.getBankCardInfo();
     console.log(result);
     return System.getResult2(result,null);
   }
   async initNewInstance(queryobj,qobj){
     var u=uuidv4();
     var aid=u.replace(/\-/g,"");
     var rd={name:"",appid:aid}
     return System.getResult2(rd,null);
   }
   async closeOrder(queryobj,qobj){
     var tradekey=qobj.idkey;
     var result=await this.service.closeWxOrder(tradekey);
     return System.getResult2(result,null);
   }
   //充值微信平台通知回调
   async wxNotityFillMoney(tradekey,webopenid,amount){
     try {
       var tmpTrade=await this.service.findOneByIdKey(tradekey);//查询是否已经生成了交易
       //按照openid,查询出user,
       var user=await this.userSve.dao.model.findOne({where:{openId:webopenid},include:{model:this.userSve.db.models.app},raw:true});
       console.log("user.app.appid...................................");
       console.log(user['app.appid']);
       if(!tmpTrade){
         var trade=await this.wxNotityFillmoney(tradekey,amount,user);
         console.log("user account_id......................................."+user.account_id);
         console.log("user app_id......................................."+user.app_id);
         var accountBalance = await this.accountSve.getAccountBalance(user.account_id,user.app_id);
         trade.dataValues["accountBalance"]=accountBalance;
         return System.getResult2(trade,null);
       }else{
         //var user=req.session.user;
         var accountBalance = await this.accountSve.getAccountBalance(user.account_id,user.app_id);
         tmpTrade.dataValues["accountBalance"]=accountBalance;
         return System.getResult2(tmpTrade,null);
       }
     } catch (e) {
       console.log(e);
       console.log("error ....");
       return System.getResult2(null,null);
     }
   }
   async wxNotityFillmoney(tradekey,amount,user){
     var fillamount=Number(amount);
     var appkey=user['app.appid'];
     //查询出兑换率，计算兑换宝币数量
     var price=await this.pconfigSve.findOrSetPrice(null,appkey);
     var tradeObj={
       idkey:tradekey,
       username:user.nickName,
       tradeDate:new Date(),
       status:"settled",
       baoAmount:fillamount * Number(price),
       tradeType:"fill",
       renAmount:Math.abs(fillamount) *(-1)};

     var trade=await this.service.create(user,tradeObj);
     return trade;
   }
   async checkPayState(queryobj,qobj,req){
     var tradekey=qobj.idkey;
     //查询微信订单
     console.log("checkPayState.........................");
     console.log(tradekey);
     try {
       var result=await this.service.queryWxOrder(tradekey);
       console.log("11111111");
       console.log(result);
       if(result.trade_state=="SUCCESS" && result.return_code=="SUCCESS" && result.result_code=="SUCCESS"){
         //表示已经支付成功
         var tmpTrade=await this.service.findOneByIdKey(tradekey);//查询是否已经生成了交易
         if(!tmpTrade){
           console.log("return order.....");
           return System.getResult2(null,null);
         }else{
           var user=req.session.user;
           var accountBalance = await this.accountSve.getAccountBalance(user.account_id,user.app_id);
           tmpTrade.dataValues["accountBalance"]=accountBalance;
           return System.getResult2(tmpTrade,null);
         }
       }else{
         console.log("return order.....");
         return System.getResult2(null,null);
       }
     } catch (e) {
       console.log(e);
       console.log("error ....");
       return System.getResult2(null,null);
     }
   }
   async checkOrderPayState(queryobj,qobj,req){
     var payOrderNum=qobj.payOrderNum;
     var orderNum = qobj.orderNum;
     var payUser = qobj.payUser;
     //查询微信订单
     console.log("checkPayState.........................");
     console.log(payOrderNum);
     try {
       var result=await this.service.queryWxOrder(payOrderNum);
       console.log(result);
       if(result.trade_state=="SUCCESS" && result.return_code=="SUCCESS" && result.result_code=="SUCCESS"){
         var tradeObj={
           idkey:orderNum,
           tradeDate:new Date(),
           status:"settled",
           tradeType:"orderTrade",
           remark:"订单交易",
           renAmount:Number(result.total_fee)/100,
         };
         console.log(tradeObj);
         var trade= await this.service.createOrderTrade(tradeObj,orderNum,result,payUser);
         console.log(trade);
         return {result:result,trade:trade.dataValues,order:trade.dataValues.order};
       }else{
         console.log("return order.....");
         return {result:result};
       }
     } catch (e) {
       console.log("error ....");
       return System.getResult2(null,null);
     }
   }
   async createUnifiedOrder(queryobj,qobj,req){
     var fillamount=Number(qobj.amount);
     var desc=qobj.desc;
     var webuseropenid=req.session.user.openId;
     try{
       var result=await this.service.createUnifiedOrder(desc,fillamount,'http://boss.gongsibao.com/wx/pay',-1,webuseropenid);
       console.log(result);
       //充值下单成功后初始化业务锁
       this.cacheManager["CacheLocker"].init(result.out_trade_no);
       return System.getResult2(result,null);
     }catch(e){
       return System.getResult2(null,null);
     }
   }

   //用于商标自动提报 微信支付
   async createUnifiedOrder2(queryobj,qobj,req){
    var fillamount=Number(qobj.amount);
    var desc=qobj.desc;
    if(!qobj.orderNum){
      return System.getResult2(null,null);
    }
    var webuseropenid=req.session.user.openId+";"+qobj.orderNum;
    try{
      var result=await this.service.createUnifiedOrder(desc,fillamount,'http://boss.gongsibao.com/wx/pay',-1,webuseropenid);
      console.log(result);
      //充值下单成功后初始化业务锁
      this.cacheManager["CacheLocker"].init(result.out_trade_no);
      return System.getResult2(result,null);
    }catch(e){
      return System.getResult2(null,null);
    }
  }

   async createOrderPaid(queryobj,qobj,req){
     console.log("createOrderPaid+++++++++++++++++++++++++++++++++++");
     try{
       var wxOrder=null;
       var payQrCreateTime=qobj.payQrCreateTime;
       var passTime=(new Date().getTime()-Number(payQrCreateTime))/1000;
       console.log("passed seconds "+passTime);
       if(qobj.payOrderNum!="" && qobj.payOrderNum!=null){
         wxOrder=await this.service.queryWxOrder(qobj.payOrderNum);
       }
       console.log(wxOrder);
      if(passTime<300 && wxOrder && wxOrder!=null && wxOrder.return_code=='SUCCESS' && wxOrder.result_code=='SUCCESS' && wxOrder.trade_state=='NOTPAY'){
          var result={"return_code":'notPay'};
          return System.getResult2(result,null);
       }else{
         var result=await this.service.createOrderPaid(qobj);
         console.log(result);
         qobj.payQr=result.qrurl;
         qobj.payQrCreateTime=new Date().getTime();
         qobj.payOrderNum=result.tradekey;
         var orderResult = await this.orderSve.update(qobj);
         return System.getResult2(result,null);
       }
     }catch(e){
       return System.getResult2(null,null);
     }
   }
   async fillmoney(tradekey,amount,req){
     var fillamount=Number(amount);
     var user=req.session.user;
     var appkey=req.session.app.appid;
     //查询出兑换率，计算兑换宝币数量
     var price=await this.pconfigSve.findOrSetPrice(null,appkey);
     var tradeObj={
       idkey:tradekey,
       username:user.nickName,
       tradeDate:new Date(),
       status:"settled",
       baoAmount:fillamount * Number(price),
       tradeType:"fill",
       renAmount:Math.abs(fillamount) *(-1)};

     var trade=await this.service.create(user,tradeObj);
     return trade;
   }

   //提现申请操作
   async withdrawMoney(gobj,pobj,req){
     var user=req.session.user;
     console.log("88888888888888888888888888888888888888888888888888888888");
     console.log(user);
     console.log("888888888888888888888888888888888888888888888888----------------------------");
     console.log(user.partnerinfo);
     if(user==null){
       return {code:-90,msg:"用户信息为空"}
     }
     var partnerinfo=user.partnerinfo;
     if(partnerinfo==null){
       return {code:-100,msg:"合伙人信息为空"}
     }
     if(partnerinfo.identityCard==null||partnerinfo.cardNo==null||partnerinfo.realName==null){
       return {code:-110,msg:"合伙人信息为空"}
     }
     if(pobj==null||pobj.moneys==null){
       return {code:-120,msg:"请求信息为空"}
     }

     try{
       var amount=pobj.moneys.moneyNum==null?parseFloat(0):parseFloat(pobj.moneys.moneyNum);
       if(amount<=0){
         return {code:-130,msg:"输入的金额有误"}
       }
       //提现日期范围是否有限制
       var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
       if(pconfig!=null||pconfig!="undefined"){
         var result= pconfig.find(item => {
             return item.configType === "withdrawalData";
         });
         if(result!=null&&result.configValue!="-1"){
           var withdrawalData= result.configValue.split('-');
           if(withdrawalData.length==2){
             var myDate=new Date();
             var nowDay= myDate.getDate()
             if(nowDay>withdrawalData[1]||nowDay<withdrawalData[0]){
               return {code:-170,msg:"不在提现日期内，提现日期为每月的 "+withdrawalData[0]+"号到 "+withdrawalData[0]+"号"};
             }
           }
         }
       }//提现日期范围有限制

       var trade=await this.service.setWithdrawMoneyApplying(user,partnerinfo,amount);
       return trade;
     }catch(e){
       //日志记录
       logCtl.error({
          optitle:"提现申请异常",
          op:"base/controller/impl/tradeCtl/withdrawMoney",
          content:e.stack,
          clientIp:""
        });
       return {code:-200,msg:"提现申请失败"};
     }
  }
  //提现申请发放
  async applyWithdrawMoney(gobj,pobj,req){
    var user=req.session.user;
    if(user==null){
      return {code:-90,msg:"用户信息为空"}
    }
    try{
      var rd=await this.profitcenterSve.getApplyingSum();
      var applyingSum=rd?rd:0;
      if(applyingSum<=0){
        return {code:-100,msg:"将要发放额度：0元，无需发放"}
      }
      //银行余额
      var bankSum=await this.service.getBankCardInfo();
      if(bankSum.code!=1){
        return {code:-110,msg:"商户账号余额不足，请及时充值"}
      }
      var tmpSum=parseFloat(bankSum.msg)-parseFloat(applyingSum);
      if(tmpSum<0){
        var ttSum=parseFloat(applyingSum)-parseFloat(bankSum.msg);
        return {code:-120,msg:"商户账号余额不足，将要发放额度为："+applyingSum+" 元，应充值额度大于："+ttSum.toFixed(2)+" 元"}
      }
      //提现日期范围是否有限制
      var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
      if(pconfig!=null||pconfig!="undefined"){
        var result= pconfig.find(item => {
            return item.configType === "withdrawalData";
        });
        if(result!=null&&result.configValue!="-1"){
          var withdrawalData= result.configValue.split('-');
          if(withdrawalData.length==2){
            var myDate=new Date();
            var nowDay= myDate.getDate()
            if(nowDay>withdrawalData[1]||nowDay<withdrawalData[0]){
              return {code:-130,msg:"不再提现日期内，提现日期为每月的 "+withdrawalData[0]+"号到 "+withdrawalData[0]+"号"};
            }
          }
        }
      }//提现日期范围有限制

      var trade=await this.service.setWithdrawMoney(user);
      trade.totalBank=tmpSum;
      trade.totalApplying=0;
      return trade;
    }catch(e){
      //日志记录
      logCtl.error({
         optitle:"产提现申请发放异常",
         op:"base/controller/impl/tradeCtl/applyWithdrawMoney",
         content:e.stack,
         clientIp:""
       });
      return {code:-200,msg:"提现申请发放失败"};
    }
  }
}
module.exports=TradeCtl;
