const system=require("../../system");
const ServiceBase=require("../sve.base");
const settings=require("../../../config/settings");
const uuidv4 = require('uuid/v4');
class CopyrightinfoService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(CopyrightinfoService));
     this.orderDao=system.getObject("db.orderDao");
     this.orderflowDao=system.getObject("db.orderflowDao");
     this.partnerinfoDao=system.getObject("db.partnerinfoDao");
     this.tradeDao=system.getObject("db.tradeDao");
     this.userDao=system.getObject("db.userDao");
     this.accountDao=system.getObject("db.accountDao");
  }
  async getUUId(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;
    // return  myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+Math.round(Math.random()*500)+""+user.id;
  }
  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 findByIds(ids){
    var apps=await this.dao.findByIds(ids);
    return apps;
  }
  async findByCodes(codes){
    var apps=await this.dao.findByCodes(codes);
    return apps;
  }
  async findOneByCode(code){
    return this.dao.findOneByCode(code);
  }
 async findByOrderNum(orderNum){
   var apps=await this.dao.findByOrderNum(orderNum);
   return apps;
 }

 async aiadive(obj){
   var sql="select req from h_aiadive where search='"+ obj.seltype[0]+" / "+obj.seltype[1] + "'";
   var tmpResult=await this.dao.customQuery(sql);
   var nclinfo=[];
   tmpResult.forEach(n=>{
     nclinfo.push(n.req);
   })
   var info="{'ncl':["+nclinfo+"]}";
   var result=info.replace(/'/g,"\"");
   return result;
 }
 async hookOrder(obj){
   var self=this;
   return this.db.transaction(async function(t){
     var sql="update h_order_info set isHooked=1 where id=?";
     var params={replacements: [obj.oid],transaction:t};
     await self.dao.customExecAddOrPutSql(sql,params);
     var  ids=obj.cids;
     sql=`update h_copyright_info set orderNum=?,status=?,statusName=? where id in ( ${ids} )`;
     params={replacements: [obj.orderNum,"2","已创建订单",obj.cids],transaction:t};
     var rtn=await self.dao.customExecAddOrPutSql(sql,params);
     return rtn;
   });
 }
 // async changeStatus(obj){
 //   var ids = obj.ids;
 //   var status = obj.status;
 //   console.log(obj);
 //   var self = this;
 //   return this.db.transaction(async function(t){
 //     for(var i=0;i<ids.length;i++){
 //       await self.dao.update({id:ids[i],statusProgress:status},t);
 //     }
 //     return {code:1}
 //   })
 // }
 async changeStatus(obj){
   var ids = obj.ids;
   var status = obj.status;
   console.log(obj);
   var self = this;
   for(var i=0;i<ids.length;i++){
     var copyright = await self.dao.findById(ids[i]);
     if(copyright.statusProgress=='FINISH'){
       return {code:-101,mag:"修改失败,不能修改完成状态数据"}
     }
   }
   var sumObj={bao:0,ren:0};
   return this.db.transaction(async function(t){
     for(var i=0;i<ids.length;i++){
       await self.dao.update({id:ids[i],statusProgress:status},t);
       var cr = await self.dao.findById(ids[i]);
       var crorder = await self.orderDao.model.findOne({where:{orderNum:cr.orderNum}});
       var orderObj = crorder.dataValues;
       var user = await self.userDao.findById(orderObj.user_id);
       var userObj = user.dataValues;
       var account = await self.accountDao.findById(userObj.account_id);

       if(status=="FINISH" && orderObj.orderStatus!="32" && cr && crorder && user){
         if(Number(orderObj.totalPublicExpense)>0){
           var orderPersonFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.totalPublicExpense,remark:"官费",tradeDate:new Date(),tradeType:"publicExpense",status:"settled",orderNum:orderObj.orderNum};
           var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj,t);//官费
         }
         if(Number(orderObj.totalInvoiceTaxes)>0){
           var orderPersonFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.totalInvoiceTaxes,remark:"税费",tradeDate:new Date(),tradeType:"invoiceTaxes",status:"settled",orderNum:orderObj.orderNum};
           var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj,t);//税费
         }
         if(Number(orderObj.userProfit)>0){
           var orderPersonFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.userProfit,remark:"个人分润",tradeDate:new Date(),tradeType:"orderPersonFee",status:"settled",orderNum:orderObj.orderNum};
           var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj,t);//个人分润
           sumObj.ren = parseFloat(sumObj.ren)+parseFloat(orderPersonFee.renAmount);
         }//平台帐户中减去此笔交易

         //判断来源是移动商城时，需要对店铺利润进行处理
         if(orderObj.orderSourceType=="2" && orderObj.shopkeeperProfit>0){
           var orderPersonFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.shopkeeperProfit,remark:"店主分润",tradeDate:new Date(),tradeType:"orderPersonFee",status:"settled",orderNum:orderObj.orderNum};
           var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj,t);//移动端店主分润
           sumObj.ren = parseFloat(sumObj.ren)+parseFloat(orderPersonFee.renAmount);
         }//平台帐户中减去此笔交易
         if(Number(orderObj.referrerProfit)>0 && account.referrerOnlyCode!="" && account.referrerOnlyCode!=null){
           //拥有推荐人 建立推荐人分润
            var o={unionId:account.referrerOnlyCode,}
            var user2 = await self.userDao.findOne(o);//推荐人信息
            user2=user2.dataValues;
           var recommendFeeObj={app_id:user2.app_id,account_id:user2.account_id,user_id:user2.id,username:user2.userName,nickName:user2.nickName,
             renAmount:orderObj.referrerProfit,remark:"推荐分润",tradeDate:new Date(),tradeType:"recommendFee",status:"settled",orderNum:orderObj.orderNum};
           var recommendFee = await self.tradeDao.createOrderTrade(recommendFeeObj,t);//推荐分润
           sumObj.ren = parseFloat(sumObj.ren)+parseFloat(recommendFee.renAmount);
         }//平台帐户中减去此笔交易
         if(Number(orderObj.platformProfit)>0){
           var orderPlatformFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.platformProfit,remark:"平台分润",tradeDate:new Date(),tradeType:"orderPlatformFee",status:"settled",orderNum:orderObj.orderNum};
           var orderPlatformFee = await self.tradeDao.createOrderTrade(orderPlatformFeeObj,t);//平台分润

         }
         if(Number(orderObj.totalPlatformCost)>0){
           var platUseFeeObj={app_id:orderObj.app_id,account_id:user.account_id,user_id:user.id,username:user.userName,nickName:user.nickName,
             renAmount:orderObj.totalPlatformCost,remark:"平台使用费",tradeDate:new Date(),tradeType:"platUseFee",status:"settled",orderNum:orderObj.orderNum};
             console.log(platUseFeeObj);
           var platUseFee = await self.tradeDao.createOrderTrade(platUseFeeObj,t);//平台使用费

         }
         console.log("sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总");
         console.log(sumObj);
         await self.orderDao.model.update({orderStatus:"32"},{where:{id:orderObj.id}, transaction:t});
         await self.tradeDao.updatePAccount(sumObj,t);
       }
       var orderflowObj={app_id:orderObj.app_id,user_id:user.id,userName:user.userName,nickName:user.nickName,orderNum:orderObj.orderNum,opContent:"订单"+cr.statusProgressName};
       var orderflow = await self.orderflowDao.create(orderflowObj,t);//订单流程
     }
     return {code:1}
   })
 }
}
module.exports=CopyrightinfoService;
