const system=require("../../system");
const ServiceBase=require("../sve.base");
class IcbcInfoService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(IcbcInfoService));
     this.orderSve=system.getObject("service.orderSve");
     this.servicesitemDao=system.getObject("db.servicesitemDao");
  }
  async addChannelIcbc(obj,appName){
    var result={
          code: "0000",
          message: "success",
          app_code:obj.app_code,
          data: null
      };
    var checkReqParams=await this.isCheckReqParams(obj);
    if(checkReqParams.code!=1){
      result.code="1003";
      result.message=checkReqParams.message;
      return result;
    }
    return await this.addAndPutIcbc(obj,"add",result);
  }
  async putChannelIcbc(obj,appName){
    var result={
          code: "0000",
          message: "success",
          app_code:obj.app_code,
          data: null
      };
    var checkReqParams=await this.isCheckReqParams(obj);
    if(checkReqParams.code!=1){
      result.code="1003";
      result.message=checkReqParams.message;
      return result;
    }
    return await this.addAndPutIcbc(obj,"put",result);
  }
  async getChannelIcbcStatus(obj){
    var result={
          code: "0000",
          message: "success",
          app_code:obj.app_code,
          data: null
      };
    if(obj.app_code==null||obj.app_code==""||obj.app_code=="undefined"){
      result.code="1003";
      result.message="app_code参数有误";
      return result;
    }
    if(obj.channel_order_num==null||obj.channel_order_num==""||obj.channel_order_num=="undefined"){
      result.code="1003";
      result.message="channel_order_num参数有误";
      return result;
    }
    let sqlWhere={channelOrderNum:obj.channel_order_num,app_code:obj.app_code};
    var item= await this.dao.findOne(sqlWhere);
    if(item==null){
      result.code="2003";
      result.message="工商数据为空";
      return result;
    }
    result.data={
      order_num:item.orderNum,
      status:item.statusProgress,
      status_name:item.statusProgressName,
       op_notes:item.opNotes
    };
    return result;
  }
  //验证渠道请求参数
  async isCheckReqParams(obj){
    var result={
       code: 1,
       message: "success",
    };
    if(obj.app_code==null||obj.app_code==""||obj.app_code=="undefined"){
      result.code=-100;
      result.message="app_code参数有误";
      return result;
    }
    if(obj.channel_order_num==null||obj.channel_order_num==""||obj.channel_order_num=="undefined"){
      result.code=-100;
      result.message="channel_order_num参数有误";
      return result;
    }
    if(obj.service_item_code==null||obj.service_item_code==""||obj.service_item_code=="undefined"){
      result.code=-100;
      result.message="service_item_code参数有误";
      return result;
    }
    if(obj.company_name_cn==null||obj.company_name_cn==""||obj.company_name_cn=="undefined"){
      result.code=-100;
      result.message="company_name_cn参数有误";
      return result;
    }
    if(obj.company_nature==null||obj.company_nature==""||obj.company_nature=="undefined"){
      result.code=-100;
      result.message="company_nature参数有误";
      return result;
    }
    if(obj.company_nature.length>25){
      result.code=-100;
      result.message="company_nature长度有误，最长为25字符";
      return result;
    }
    if(obj.reg_capital==null||obj.reg_capital==""||obj.reg_capital=="undefined"){
      result.code=-100;
      result.message="reg_capital参数有误";
      return result;
    }
    if(obj.reg_capital_units==null||obj.reg_capital_units==""||obj.reg_capital_units=="undefined"){
      result.code=-100;
      result.message="reg_capital_units参数有误";
      return result;
    }
    if(obj.icbc_contact_person==null||obj.icbc_contact_person==""||obj.icbc_contact_person=="undefined"){
      result.code=-100;
      result.message="icbc_contact_person参数有误";
      return result;
    }
    if(obj.icbc_contact_person.contact_name==null||obj.icbc_contact_person.contact_name==""||obj.icbc_contact_person.contact_name=="undefined"){
      result.code=-100;
      result.message="contact_name参数有误";
      return result;
    }
    if(obj.icbc_contact_person.contact_mobile==null||obj.icbc_contact_person.contact_mobile==""||obj.icbc_contact_person.contact_mobile=="undefined"){
      result.code=-100;
      result.message="contact_mobile参数有误";
      return result;
    }
    if(obj.icbc_contact_person.contact_email==null||obj.icbc_contact_person.contact_email==""||obj.icbc_contact_person.contact_email=="undefined"){
      result.code=-100;
      result.message="contact_email参数有误";
      return result;
    }
    return result;
  }
  //渠道新增或修改(obj请求参数,reqType请求类型,result返回类型)
  async addAndPutIcbc(obj,reqType,result,appName){
    var self=this;
    return self.db.transaction(async function (t){
        var serviceItem=await self.servicesitemDao.model.findOne({where:{code:obj.service_item_code,itemType:"icbc"}});
        if(serviceItem==null){
          result.code="2002";
          result.message="服务项目为空";
          return result;
        }
        var tTotalSum=Number(serviceItem.serviceCharge)+Number(serviceItem.publicExpense)+Number(serviceItem.platformCost);
        var param={
          companyNameCn:obj.company_name_cn,//公司中文名称
          companyNameEn:obj.app_code==null||obj.app_code==""||obj.app_code=="undefined"?null:obj.company_name_en,//公司英文名称
          regCapital:parseFloat(obj.reg_capital),//serviceItem注册资金
          regCapitalUnits:obj.reg_capital_units,
          companyNature:obj.company_nature,//公司性质
          statusProgress:"WAITARTIFICIALEXAMINE",//进展状态,等待人工审核
          notes:obj.notes==null||obj.notes==""||obj.notes=="undefined"?null:obj.notes,//备注
          //---联系人
          customerContact:obj.icbc_contact_person.contact_name,//客户联系人
          customerMobile:obj.icbc_contact_person.contact_mobile,//客户联系人手机号
          customerEmail:obj.icbc_contact_person.contact_email,//联系人邮箱
          customerFax:obj.contact_fax==null||obj.contact_fax==""||obj.contact_fax=="undefined"?null:obj.contact_fax,//联系人传真
          customerTel:obj.contact_tel==null||obj.contact_tel==""||obj.contact_tel=="undefined"?null:obj.contact_tel,//联系人座机
          //---附件
          zipFileUrl:obj.zip_file_url==null||obj.zip_file_url==""||obj.zip_file_url=="undefined"?null:obj.zip_file_url,//压缩文件（包含股东身份证、其他资料）
          businessLicensePic:obj.business_license_pic==null||obj.business_license_pic==""||obj.business_license_pic=="undefined"?null:obj.business_license_pic,//营业执照照片
          regDocument:obj.reg_document==null||obj.reg_document==""||obj.reg_document=="undefined"?null:obj.reg_document,//注册文档
          regExcel:obj.reg_excel==null||obj.reg_excel==""||obj.reg_excel=="undefined"?null:obj.reg_excel,//注册表格
        //------渠道信息
          app_code:obj.app_code,//应用code，8位数字
          serviceItem_code:obj.service_item_code,//项目编码，如：sbzc
          serviceItem_name:serviceItem.name,//项目名称
          channelUserName:obj.channel_user_name==null||obj.channel_user_name==""||obj.channel_user_name=="undefined"?null:obj.channel_user_name,//渠道用户名
          channelOrderNum:obj.channel_order_num,//渠道方订单号
          totalServiceCharge:serviceItem.serviceCharge,//服务费总额
          totalPublicExpense:serviceItem.publicExpense,//官费总额
          totalPlatformCost:serviceItem.platformCost,//平台费用总额
          totalSum:tTotalSum,//总额（平台费用+服务费+官费+发票税费）
          platformProfitRatio:serviceItem.platformProfitRatio,//平台与渠道的服务费分成比率（如：总额100，字段值30，则平台的利润为30=100*(30/100)，剩下的则为渠道利润）
          channelProfit:tTotalSum-tTotalSum*(100-serviceItem.platformProfitRatio/100),//渠道服务费利润
          platformProfit:tTotalSum*(serviceItem.platformProfitRatio/100),//平台服务费利润
          sourceType:"4",//来源类型，1PC，2移动商城，4渠道方，默认为2
          sourceNotes:appName,//来源备注
        };
        var item=null;
        if(reqType=="add"){
          //工商类型："Hongkong": "香港", "gnjssqs": "国内江苏省宿迁市"
          param.icbcType=obj.icbcType;
          param.orderNum=await self.orderSve.getCreateOrderNum();//====================订单号生成
          item=await self.dao.create(param,t);
          item=item.get({plain:true});
        }else {
          var oldItem=self.dao.model.findOne({where:{channelOrderNum:obj.channel_order_num,app_code:obj.app_code},attributes:["orderNum"],raw:true},{transaction:t});
          if(oldItem==null){
            return{code:"2002",message:"订单数据为空",order_num:"",proxy_code:""};
          }
          var putSqlWhere={where:{channelOrderNum:obj.channel_order_num,app_code:obj.app_code}};
          item=await self.dao.updateByWhere(param,putSqlWhere,t);
          param.orderNum=oldItem.orderNum;
        }
        result.data={
          order_num:param.orderNum,
          status:"WAITARTIFICIALEXAMINE",
          status_name:"等待人工审核",
           op_notes:null
        };
        //是否有回调Url
        if(obj.notify_url!=null&&obj.notify_url!=""&&obj.notify_url.indexOf("http")>=0){
          self.channeltmSve.callbackNotify(result,obj.notify_url,obj.app_code,appName,obj.clientIp,reqType);
        }
       return result;
    });

  }
  //操作通知:params=>reqObj请求参数,notifyUrl回调链接,appCode应用码,appName应用名称,tClientIp
  async callbackNotify(reqObj,notifyUrl,appCode,appName,tClientIp,reqType){
    try {
        //日志记录
        logCtl.info({
           optitle:"工商回调操作info:appCode="+appCode+"，appName="+appName+"，请求类型="+reqType,
           op:"service/icbcinfoSve/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:appCode="+appCode+"，appName="+appName+"，请求类型="+reqType,
             op:"service/icbcinfoSve/callbackNotify",
             content:JSON.stringify(callbackResult)+"，notifyUrl："+notifyUrl,
             clientIp:tClientIp
           });
        }
    } catch (e) {
      //日志记录
      logCtl.console.error({
         optitle:"工商回调返回结果error:appCode="+appCode+"，appName="+appName+"，请求类型="+reqType,
         op:"service/icbcinfoSve/callbackNotify",
         content:JSON.stringify(callbackResult)+"，notifyUrl："+notifyUrl,
         clientIp:tClientIp
       });
    }
  }
}
module.exports=IcbcInfoService;
