const system=require("../../system");
const ServiceBase=require("../sve.base");
const settings=require("../../../config/settings");
const uuidv4 = require('uuid/v4');
class CalculatepriceService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(CalculatepriceService));
     this.orderDao=system.getObject("db.orderDao");
     this.trademarkDao=system.getObject("db.trademarkDao");
     this.tmcustomerinfoDao=system.getObject("db.tmcustomerinfoDao");
     this.servicesitemDao=system.getObject("db.servicesitemDao");
     this.orderflowDao=system.getObject("db.orderflowDao");
     this.partnerinfoDao=system.getObject("db.partnerinfoDao");
     this.tmapplierinfoSve=system.getObject("service.tmapplierinfoSve");
     this.trademarkSve=system.getObject("service.trademarkSve");
     this.orderSve=system.getObject("service.orderSve");
  }
  async hookOrder(obj){
    var self=this;
    return this.db.transaction(async function(t){
      var sql="update h_order_info set nclCalcIds=?,isHooked=1 where id=?";
      var params={replacements: [obj.cids,obj.oid],transaction:t};
      await self.dao.customExecAddOrPutSql(sql,params);
      var  ids=obj.cids;
      sql=`update h_ncl_calc set orderNum=?,order_id=? where id in ( ${ids} )`;
      params={replacements: [obj.orderNum,obj.oid],transaction:t};
      var rtn=await self.dao.customExecAddOrPutSql(sql,params);
      return rtn;
    });


  }
  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 createOrder(ids,user,app){
   var self=this;
   var sum_ncl_total_public_expense=0;//官费
   var sum_invoice_taxes=0;//税费
   var sum_ncl_service_charge=0;//服务费
   var userProfit=0;//个人利润
   var referrerProfit=0;//推荐人利润
   var platformProfit=0;//平台利润
   var totalPlatformCost=0;//平台使用费
   // var isFirstorder=await this.cacheManager["CheckFirstOrderCache"].get(user.id);
   var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
   var platformUseProfit = pconfig.find(item => {//单个商标大类的平台使用费
       return item.configType === "platformUseProfit";
   });
   platformUseProfit=Number(platformUseProfit.configValue);
   var referrerProfitRatio= pconfig.find(item => {//推荐人分润比例
       return item.configType === "referrerProfitRatio";
   });
   referrerProfitRatio=Number(referrerProfitRatio.configValue);
   var platformProfitRatio= pconfig.find(item => {//平台分润比例
       return item.configType === "platformProfitRatio";
   });
   platformProfitRatio=Number(platformProfitRatio.configValue);

   return this.db.transaction(async function (t){
       var calculates=await self.dao.findByIds(ids);
       var calcs=calculates.rows;
       if(calcs.length!=ids.length || ids.length<1){
         return {code:"-1",msg:"核价单数据为空"};
       }else{
         //var uuid=uuidv4();
         var u=await self.orderSve.getCreateOrderNum();//====================订单号生成
         for(var i=0;i<calcs.length;i++){
           sum_ncl_total_public_expense=Number(sum_ncl_total_public_expense)+Number(calcs[i].dataValues.nclTotalPublicExpense);
           sum_invoice_taxes=Number(sum_invoice_taxes)+Number(calcs[i].dataValues.invoiceTaxes);
           sum_ncl_service_charge=Number(sum_ncl_service_charge)+Number(calcs[i].dataValues.nclServiceCharge);
           if(calcs[i].dataValues.status!="1"){
             return {code:"-2",tmName:calcs[i].dataValues.tmName,msg:"商标名称为"+calcs[i].dataValues.tmName+"的核价单不能生成二次订单"};
           }
           var c=calcs[i].dataValues;
           // if(c.nclSmallCodes!=null && c.nclSmallCodes!=""){
           //   var nclOne=JSON.parse(c.nclSmallCodes).ncl;
           //   console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa");
           //   console.log(nclOne.length);
           //   console.log(platformUseProfit);
           //   var price = nclOne.length * Number(platformUseProfit);
           //   totaiadivealPlatformCost=Number(totalPlatformCost)+Number(price);//计算平台使用费总额
           // }
           totalPlatformCost=Number(totalPlatformCost)+Number(c.totalPlatformCost);//计算平台使用费总额
         }
         console.log(totalPlatformCost);
         if(user.account.referrerOnlyCode!="" && user.account.referrerOnlyCode!=null && Number(referrerProfitRatio)>0){
           console.log("推荐人收益");
           referrerProfit=Number(totalPlatformCost)*Number(referrerProfitRatio)/100;//推荐人收益
           referrerProfit = Number(referrerProfit).toFixed(0);
           totalPlatformCost=parseFloat(totalPlatformCost)-parseFloat(referrerProfit);
           console.log(referrerProfit);
           console.log(referrerProfitRatio);
         }
         userProfit=Number(sum_ncl_service_charge);//个人收益
         if(Number(platformProfitRatio)>0){
           console.log("平台收益");
           platformProfit=Number(sum_ncl_service_charge)*platformProfitRatio/100;//平台收益
           platformProfit = Number(platformProfit).toFixed(0);
           sum_ncl_service_charge=parseFloat(sum_ncl_service_charge)-parseFloat(platformProfit);
           console.log(sum_ncl_service_charge);
           console.log(platformProfitRatio);
           console.log(platformProfit);
         }
         var serviceItem=await self.servicesitemDao.findOneByCode("sbzc");//服务项信息
         serviceItem=serviceItem.dataValues;
         var total_sum=parseFloat(sum_ncl_total_public_expense)+parseFloat(sum_invoice_taxes)+parseFloat(sum_ncl_service_charge)+parseFloat(totalPlatformCost)+parseFloat(referrerProfit)+parseFloat(platformProfit);//订单总额
         // console.log("判断首单");
         // console.log(isFirstorder);
         // if(isFirstorder && isFirstorder!="false"){//判断首单
         //    console.log("首单首单首单首单首单首单首单首单首单首单首单首单首单首单首单首单首单首单");
         //     if(user.account.referrerOnlyCode!="" && user.account.referrerOnlyCode!=null){//判断是否有推荐人
         //       referrerProfit=Number(totalPlatformCost);
         //       totalPlatformCost=0;
         //     }
         //     await self.cacheManager["CheckFirstOrderCache"].set(user.id,false);
         //     // partnerinfo.firstOrder="1";
         //     // var partner= await self.partnerinfoDao.update2(partnerinfo,t);//关闭首单开关
         // }
         var orderObj={applyName:calcs[0].dataValues.applyName,
          referrerProfit:referrerProfit,userProfit:userProfit,userName:user.userName,totalPlatformCost:totalPlatformCost,
          platformProfitRatio:platformProfitRatio,referrerProfitRatio:referrerProfitRatio,
          platformProfit:platformProfit,userProfit:userProfit,
          orderNum:u,orderType:"1",app_id:app.id,user_id:user.id,onlyCode:user.onlyCode,shopOnlyCode:user.onlyCode,nickName:user.nickName,
          customerContact:calcs[0].dataValues.customerContact,customerMobile:calcs[0].dataValues.mobile,
          itemCode:"sbzc",itemName:serviceItem.name,itemOrderNum:1,itemOrderConsumeNum:1,
          itemType:"ip",
          totalPublicExpense:sum_ncl_total_public_expense,totalInvoiceTaxes:sum_invoice_taxes,orderStatus:"1",
          totalServiceCharge:sum_ncl_service_charge,totalSum:total_sum,orderSourceType:"1"};
         return self.orderDao.create(orderObj,t).then(async function(order){//订单
           var calc=calcs[0].dataValues;
            var customerObj={zipCode:calc.zipCode,order_id:order.id,orderNum:order.orderNum,customerContact:calc.customerContact,mobile:calc.mobile,email:calc.email};
            var orderflowObj={app_id:app.id,user_id:user.id,userName:user.userName,nickName:user.nickName,orderNum:order.orderNum,opContent:"创建订单"};
            var orderflow = await self.orderflowDao.create(orderflowObj,t);//订单流程
            var customer=await self.tmcustomerinfoDao.create(customerObj,t);//联系人
            for(var i=0;i<calcs.length;i++){
              var obj=calcs[i].dataValues;
              obj.orderNum=order.orderNum;
              obj.status="2";
              obj.order_id=order.id;
              var c= await self.dao.update(obj,t);//更新核价单
            }
            return {code:"1",msg:"success",order:order};
         });
       }

   });
 };
 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 updateweituoshupic(o,req){
   var app=req.session.app;
   var obj={
     "appKey":app.appid,
     "jpgpath":o.key
   };
   var url = settings.apiconfig.wtsUrl;
   var rc=system.getObject("util.execClient");
   var rtn=await rc.execPost(obj,url);
   var j=JSON.parse(rtn.stdout);
   var self = this;
   var nclCalc_id=o.nclCalc_id;
   var fobj={nclCalc_id:nclCalc_id};
   // var tminfo=await this.trademarkSve.refQuery(fobj);
   var tminfo=await this.trademarkSve.dao.model.findAll({where:fobj});
   if(tminfo){
     return this.db.transaction(async function (t){
       for(var i=0;i<tminfo.length;i++)
       {
         tminfo[i].sealAuthorizeStuff=j.data.url;
         var g=await self.trademarkSve.update(tminfo[i].dataValues,t);
       }
       return {code:'0',data:j.data.url};
     })
   }
   else {
     return {code:'0',data:null};
   }
 }
}
module.exports=CalculatepriceService;
