const system=require("../../system");
const ServiceBase=require("../sve.base");
const settings=require("../../../config/settings");
const uiconfig=system.getUiConfig2(settings.wxconfig.appId);
const crypto = require('crypto');
const cryptoJS = require("crypto-js");
const logCtl=system.getObject("web.oplogCtl");
class ChanneltmService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(ChanneltmService));
     this.tmflowDao=system.getObject("db.tmflowDao");
     this.trademarkDao=system.getObject("db.trademarkDao");
     this.servicesitemDao=system.getObject("db.servicesitemDao");
     //订单流程-暂时不用
     // this.orderflowDao=system.getObject("db.orderflowDao");
     this.tmflowDao=system.getObject("db.tmflowDao");
     this.channeltmDao=system.getObject("db.channeltmDao");
     this.tmcustomerinfoDao=system.getObject("db.tmcustomerinfoDao");
     this.tmapplierinfoDao=system.getObject("db.tmapplierinfoDao");
     this.orderSve=system.getObject("service.orderSve");
  }
  async getUUId(){
    var myDate=new Date();
    var uid=await this.getUidStr(5,60);
    return  myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+uid;
  }
  //添加渠道商标:params=>obj(附加到obj上的有appName,tKeyHex,tPlatformProfitRatio,addTmStatus,addTmStatusName)
  //author:sy
  async addChannelTm(obj){
    var self=this;
    //日志记录
    logCtl.info({
       optitle:"商标添加操作info:",
       op:"service/channeltmSve/addChannelTm",
       content:JSON.stringify(obj),
       clientIp:obj.clientIp
     });

    return self.db.transaction(async function (t){
      //解密数据
      let keyHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex);
      let ivHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex.substring(0,8));
      // var cipherDataStr=decodeURIComponent(obj.);
      var bytes = cryptoJS.TripleDES.decrypt(obj.data, keyHex, {
        iv: ivHex
      });
      var plaintext = bytes.toString(cryptoJS.enc.Utf8);
      var tmpResult=JSON.parse(plaintext);
      if(tmpResult.app_code!=obj.app_code){
        return{code:"2001",message:"app_code数据不匹配",order_num:"",proxy_code:"",notify_url:""};
      }

      var createOrderNum=await self.orderSve.getCreateOrderNum();//====================订单号生成
      var createProxyCode = await self.getUUId();
      var serviceItem=await self.servicesitemDao.findOneByCode(tmpResult.service_item_code);//服务项信息
      if(serviceItem==null){
        return{code:"2002",message:"服务项目数据为空",order_num:"",proxy_code:"",notify_url:""};
      }
      serviceItem=serviceItem.dataValues;
      var tTotalPublicExpense=0;
      var tPlatformProfit=serviceItem.serviceCharge!=null&&parseFloat(serviceItem.serviceCharge)>0&&obj.tPlatformProfitRatio>0?
                          (parseFloat(serviceItem.serviceCharge)*(obj.tPlatformProfitRatio/100)):0;
      let nclSmallLength=tmpResult.ncl_small_codes.nclthree.length;
      let beyondNclSmall=nclSmallLength-10;
      tTotalPublicExpense=300+(beyondNclSmall>0?beyondNclSmall*30:0);
      var tmParam={
            orderNum:createOrderNum,
            tmType:"p",
            tmFormType:tmpResult.tm_form_type,
            caseType:"sbzc",
            nclOneCodes:tmpResult.ncl_one_codes,
            nclSmallCodes:JSON.stringify(tmpResult.ncl_small_codes),
            tmName:tmpResult.tm_name,
            picUrl:tmpResult.pic_url,
            tmNameEn:tmpResult.tm_name_en,
            known:tmpResult.known,
            tmValue:tmpResult.tm_value,
            proxyCode:createProxyCode,
            sealAuthorizeStuff:tmpResult.seal_authorize_stuff,
            tmStatus:obj.addTmStatus,
            voiceUrl:tmpResult.voice_url,
            descUrl:tmpResult.desc_url,
            colorizedPicUrl:tmpResult.colorized_pic_url,
            remarkInfo:tmpResult.remark_info,
            app_code:tmpResult.app_code,
            channelOrderNum:tmpResult.channel_order_num,
            applyName:tmpResult.applicants.applicants_name,
            clientIp:obj.clientIp,
            tmSourceType:"4"
          };
      if(obj.addTmStatus=="WAITARTIFICIALEXAMINE"){
          await self.trademarkDao.create(tmParam,t);
      }
      //添加渠道商标
      tmParam.serviceItem_code=tmpResult.service_item_code;
      tmParam.serviceItem_name=serviceItem.name;
      tmParam.channelUserName=tmpResult.channel_user_name;
      tmParam.totalServiceCharge=serviceItem.serviceCharge;
      tmParam.totalPublicExpense=tTotalPublicExpense;
      tmParam.totalPlatformCost=serviceItem.platformCost;
      tmParam.totalSum=parseFloat(serviceItem.serviceCharge)+parseFloat(serviceItem.platformCost)+tTotalPublicExpense;
      tmParam.platformProfitRatio=obj.tPlatformProfitRatio;//平台与渠道的服务费分成比率（如：总额100，字段值30，则平台的利润为30=100*(30/100)，剩下的则为渠道利润）
      tmParam.platformProfit=tPlatformProfit;
      tmParam.channelProfit=tPlatformProfit>0?parseFloat(serviceItem.serviceCharge)-tPlatformProfit:0;
      tmParam.customerContact=tmpResult.customer_contact;
      tmParam.customerMobile=tmpResult.customer_mobile;
      tmParam.notes=tmpResult.notes;
      await self.channeltmDao.create(tmParam,t);

      var applierObj={
                      channelOrderNum:tmpResult.channel_order_num,
                      app_code:tmpResult.app_code,
                      orderNum:createOrderNum,
                      type:tmpResult.applicants.applicants_type,
                      applyName:tmpResult.applicants.applicants_name,
                      identityCard:tmpResult.applicants.applicants_type!="person"?"":tmpResult.applicants.identitycard,
                      creditCode:tmpResult.applicants.credit_code,
                      applyAddr:tmpResult.applicants.addr,
                      identityCardPic:tmpResult.applicants.applicants_type!="person"?"":tmpResult.applicants.identitycard_url,
                      businessLicensePic:tmpResult.applicants.applicants_type=="person"?"":tmpResult.applicants.businessLicense_url
                    };
       var customerObj={
                        channelOrderNum:tmpResult.channel_order_num,
                        app_code:tmpResult.app_code,
                        orderNum:createOrderNum,
                        customerContact:tmpResult.tm_contact_person.contact_name,
                        mobile:tmpResult.tm_contact_person.contact_mobile,
                        fax:tmpResult.tm_contact_person.contact_fax,
                        zipCode:tmpResult.tm_contact_person.contact_zipCode,
                        email:tmpResult.tm_contact_person.contact_email};
      //创建商标进度接收人
      var customer=await self.tmcustomerinfoDao.create(customerObj,t);
      //创建商标申请用户
      var applier=await self.tmapplierinfoDao.create(applierObj,t);
      return {code:"0000",message:"success",channel_order_num:tmpResult.channel_order_num,app_code:tmpResult.app_code,order_num:createOrderNum,
              proxy_code:createProxyCode,notify_url:tmpResult.notify_url,tm_status:obj.addTmStatus,tm_status_name:obj.addTmStatusName};
    });
  }

  //获取渠道商标状态:params=>obj(附加到obj上的有appName,tKeyHex)
  //author:sy
  async getChannelTmStatus(obj){
    //日志记录
    logCtl.info({
       optitle:"商标状态获取操作info:",
       op:"service/channeltmSve/getChannelTmStatus",
       content:JSON.stringify(obj),
       clientIp:obj.clientIp
     });

    //解密数据
    let keyHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex);
    let ivHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex.substring(0,8));
    // var cipherDataStr=decodeURIComponent(obj.);
    var bytes = cryptoJS.TripleDES.decrypt(obj.data, keyHex, {
      iv: ivHex
    });
    var plaintext = bytes.toString(cryptoJS.enc.Utf8);
    var tmpResult=JSON.parse(plaintext);
    if(tmpResult.app_code!=obj.app_code){
      return{code:"2001",message:"app_code数据不匹配",order_num:"",proxy_code:"",notify_url:""};
    }
    // let sqlWhere={attributes:["tmStatus","tmStatusName","proxyCode"],channelOrderNum:tmpResult.channel_order_num,app_code:tmpResult.app_code};
    let sqlWhere={channelOrderNum:tmpResult.channel_order_num,app_code:tmpResult.app_code};
    var result= await this.channeltmDao.findOne(sqlWhere);
    if(result==null){
      return{code:"2003",message:"商标数据为空",tm_status:"",tm_status_name:""};
    }
    return{code:"0000",message:"success",tm_status:result.tmStatus,tm_status_name:result.tmStatusName,proxy_code:result.proxyCode,op_remark_info:result.opRemarkInfo};
  }

  //修改渠道商标待:params=>obj(附加到obj上的有appName,tKeyHex,tPlatformProfitRatio,putTmStatus,putTmStatusName)
  //author:sy
  async putChannelTm(obj){
    var self=this;
    //日志记录
    logCtl.info({
       optitle:"商标状态更新操作info:",
       op:"service/channeltmSve/putChannelTm",
       content:JSON.stringify(obj),
       clientIp:obj.clientIp
     });

    return self.db.transaction(async function (t){
      //解密数据
      let keyHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex);
      let ivHex = cryptoJS.enc.Utf8.parse(obj.tKeyHex.substring(0,8));
      // var cipherDataStr=decodeURIComponent(obj.);
      var bytes = cryptoJS.TripleDES.decrypt(obj.data, keyHex, {
        iv: ivHex
      });
      var plaintext = bytes.toString(cryptoJS.enc.Utf8);
      var tmpResult=JSON.parse(plaintext);
      if(tmpResult.app_code!=obj.app_code){
        return{code:"2001",message:"app_code数据不匹配",order_num:"",proxy_code:"",notify_url:""};
      }
      var createProxyCode = await self.getUUId();
      var serviceItem=await self.servicesitemDao.findOneByCode(tmpResult.service_item_code);//服务项信息
      if(serviceItem==null){
        return{code:"2002",message:"服务项目数据为空",order_num:"",proxy_code:""};
      }
      serviceItem=serviceItem.dataValues;
      var oldItem=self.dao.model.findOne({where:{channelOrderNum:tmpResult.channel_order_num,app_code:tmpResult.app_code},attributes:["orderNum"],raw:true},{transaction:t});
      if(oldItem==null){
        return{code:"2002",message:"订单数据为空",order_num:"",proxy_code:""};
      }

      var tTotalPublicExpense=0;
      var tPlatformProfit=serviceItem.serviceCharge!=null&&parseFloat(serviceItem.serviceCharge)>0&&obj.tPlatformProfitRatio>0?
                          (parseFloat(serviceItem.serviceCharge)*(obj.tPlatformProfitRatio/100)):0;
      let nclSmallLength=tmpResult.ncl_small_codes.nclthree.length;
      let beyondNclSmall=nclSmallLength-10;
      tTotalPublicExpense=300+(beyondNclSmall>0?beyondNclSmall*30:0);

      var putSqlWhere={where:{channelOrderNum:tmpResult.channel_order_num,app_code:tmpResult.app_code}};
      var tmParam={
            tmType:"p",
            tmFormType:tmpResult.tm_form_type,
            caseType:"sbzc",
            nclOneCodes:tmpResult.ncl_one_codes,
            nclSmallCodes:JSON.stringify(tmpResult.ncl_small_codes),
            tmName:tmpResult.tm_name,
            picUrl:tmpResult.pic_url,
            tmNameEn:tmpResult.tm_name_en,
            known:tmpResult.known,
            tmValue:tmpResult.tm_value,
            sealAuthorizeStuff:tmpResult.seal_authorize_stuff,
            tmStatus:obj.putTmStatus,
            voiceUrl:tmpResult.voice_url,
            descUrl:tmpResult.desc_url,
            colorizedPicUrl:tmpResult.colorized_pic_url,
            remarkInfo:tmpResult.remark_info,
            app_code:tmpResult.app_code,
            channelOrderNum:tmpResult.channel_order_num,
            applyName:tmpResult.applicants.applicants_name,
            clientIp:obj.clientIp,
            tmSourceType:"4"
          };
      await self.trademarkDao.updateByWhere(tmParam,putSqlWhere,t);
      //添加渠道商标
      tmParam.serviceItem_code=tmpResult.service_item_code;
      tmParam.serviceItem_name=serviceItem.name;
      tmParam.channelUserName=tmpResult.channel_user_name;
      tmParam.totalServiceCharge=serviceItem.serviceCharge;
      tmParam.totalPublicExpense=tTotalPublicExpense;
      tmParam.totalPlatformCost=serviceItem.platformCost;
      tmParam.totalSum=parseFloat(serviceItem.serviceCharge)+parseFloat(serviceItem.platformCost)+tTotalPublicExpense;
      tmParam.platformProfitRatio=obj.tPlatformProfitRatio;//平台与渠道的服务费分成比率（如：总额100，字段值30，则平台的利润为30=100*(30/100)，剩下的则为渠道利润）
      tmParam.platformProfit=tPlatformProfit;
      tmParam.channelProfit=tPlatformProfit>0?parseFloat(serviceItem.serviceCharge)-tPlatformProfit:0;
      tmParam.customerContact=tmpResult.customer_contact;
      tmParam.customerMobile=tmpResult.customer_mobile;
      tmParam.notes=tmpResult.notes;
      await self.channeltmDao.updateByWhere(tmParam,putSqlWhere,t);

      var applierObj={
                      channelOrderNum:tmpResult.channel_order_num,
                      app_code:tmpResult.app_code,
                      type:tmpResult.applicants.applicants_type,
                      applyName:tmpResult.applicants.applicants_name,
                      identityCard:tmpResult.applicants.applicants_type!="person"?"":tmpResult.applicants.identitycard,
                      creditCode:tmpResult.applicants.credit_code,
                      applyAddr:tmpResult.applicants.addr,
                      identityCardPic:tmpResult.applicants.applicants_type!="person"?"":tmpResult.applicants.identitycard_url,
                      businessLicensePic:tmpResult.applicants.applicants_type=="person"?"":tmpResult.applicants.businessLicense_url
                    };
       var customerObj={
                        channelOrderNum:tmpResult.channel_order_num,
                        app_code:tmpResult.app_code,
                        customerContact:tmpResult.tm_contact_person.contact_name,
                        mobile:tmpResult.tm_contact_person.contact_mobile,
                        fax:tmpResult.tm_contact_person.contact_fax,
                        zipCode:tmpResult.tm_contact_person.contact_zipCode,
                        email:tmpResult.tm_contact_person.contact_email};
      //创建商标进度接收人
      var customer=await self.tmcustomerinfoDao.updateByWhere(customerObj,putSqlWhere,t);
      //创建商标申请用户
      var applier=await self.tmapplierinfoDao.updateByWhere(applierObj,putSqlWhere,t);
      return {code:"0000",message:"success",channel_order_num:tmpResult.channel_order_num,app_code:tmpResult.app_code,order_num:oldItem.orderNum,
              proxy_code:createProxyCode,notify_url:tmpResult.notify_url,tm_status:obj.putTmStatus,tm_status_name:obj.putTmStatusName};
  });
}
  //操作通知:params=>reqObj,notifyUrl,appId,appName,tClientIp
  async callbackNotify(reqObj,notifyUrl,appId,appName,tClientIp){
    //日志记录
    logCtl.info({
       optitle:"商标回调操作info:",
       op:"service/channeltmSve/callbackNotify",
       content:JSON.stringify(reqObj)+"，notifyUrl："+notifyUrl,
       clientIp:tClientIp
     });

    var rc=system.getObject("util.restClient");
    var rtn=await rc.execPost(reqObj,notifyUrl);
    var callbackResult=JSON.parse(rtn.stdout);
    if(callbackResult!="success"){
      //日志记录
      logCtl.info({
         optitle:"商标回调返回结果info:",
         op:"service/channeltmSve/callbackNotify",
         content:JSON.stringify(callbackResult)+"，notifyUrl："+notifyUrl,
         clientIp:tClientIp
       });
    }
  }
}
module.exports=ChanneltmService;
