var system = require("../../../../system");
const sha235 = require("sha256");
var settings = require("../../../../../config/settings");
class BaiduHandler {
  constructor() {
    this.icUrl = settings.icUrl() + "/web/bizchance";
    this.userService = system.getObject("service.auth.userSve");
    this.cmpService = system.getObject("service.common.companySve");
    this.msgService = system.getObject("service.msg.msgSve")
    this.cacheManager = system.getObject("db.common.cacheManager");
  }

  /**
   * 需要调用生成者接口，把数据丢入队列
   * 组装生产者需要的数据结构
   * @param {*} datajson 
   */
  //新商机处理
  async addChance(datajson, channelobj) {
    try {
      var cachestr = sha235(JSON.stringify(datajson));
      var cacheInfo = await this.cacheManager["AliCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        return {
          "status": 1,    //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      }
      else {
        var rc = system.getObject("util.execClient");
        var requrl = this.icUrl + "/bizoptCtl/insertInfo";
        let { actionBody } = datajson;
        var params = {
          businessMode: actionBody.intentionBizId,
          servicerCode: "10",
          servicerName: "公司宝",
          serviceName: actionBody.area,
          contactsPhone: actionBody.phone || actionBody.mobile,
          currentStatus: "beforeSubmission",
          channelSource: channelobj.name,
          channelNumber: channelobj.code,
          memoInfo: actionBody.description,
        }
        if (actionBody.type_code) {
          if (actionBody.type_code == "icpsq") {
            params.businessType = "/qcfw/icp/";
            params.businessName = "icp";
          }
          if (actionBody.type_code == "edisq") {
            params.businessType = "/qcfw/edi/";
            params.businessName = "edi"
          }
          if (actionBody.type_code == "NC") {
            params.businessType = "wangwen";
            params.businessName = "wangwen"
          }
          if (actionBody.type_code == "RT") {
            params.businessType = "guangbo";
            params.businessName = "guangbo"
          }
          if (actionBody.type_code == "food") {
            params.businessType = "food";
            params.businessName = "food"
          }
          if (actionBody.type_code == "GSREG") {
            params.businessType = "companyCase";
            params.businessName = "companyCase"
          }
        }

        var rtn = await rc.execPost3({ "d": params }, requrl);
        var j = JSON.parse(rtn.stdout);
        console.log(JSON.stringify(j), "RRRRRRRRRRRRRRR");
        if (j.status == 1) {
          await this.cacheManager["AliCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);//插入redis缓存
        }
        return j;
      }
    }
    catch (error) {
      console.log("TTTTTTTTTTTTTT");
      console.log(error);
      return system.getResultError(error);
    }
  }

  async updateChanceStatus(datajson) {
    try {
      var cachestr = sha235(JSON.stringify(datajson));
      var cacheInfo = await this.cacheManager["AliCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        return {
          "status": 1,    //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      } else {
        let { actionBody } = datajson;
        var rc = system.getObject("util.execClient");
        var requrl = this.icUrl + "/bizoptCtl/updateStatusByDemandCode";
        var stau;
        switch (actionBody.status) {
          case "createSolution":
            stau = {
              "businessMode": actionBody.intentionBizId,
              "currentStatus": "beforeConfirmation"
            }
            break
          case "closeNeed":
            stau = {
              "businessMode": actionBody.intentionBizId,
              "currentStatus": "isClosed"
            }
            break
          case "followingUp":
            stau = {
              "businessMode": actionBody.intentionBizId,
              "currentStatus": "followingUp"
            }
            break
          default:
            return system.getResultError("status 状态值错误");
        }
        let rtn = await rc.execPost3({ "d": stau }, requrl);//更新商机状态为已完成
        var j = JSON.parse(rtn.stdout);
        if (j.status == 0) {
          j.status = 1;
          await this.cacheManager["AliCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);//插入redis缓存
        }
        return j
      }
    } catch (error) {
      return system.getResultError(error);
    }
  }


  //交付单处理
  async pushOrderDelivery(datajson, channelobj) {
    console.log("put in queue-----------------------------------------------------------------------------------------------------", datajson);
    try {
      console.log("交付单数据:" + JSON.stringify(datajson));
      var cachestr = sha235(JSON.stringify(datajson));
      var cacheInfo = await this.cacheManager["AliCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        console.log("pushOrderDelivery 已缓存:" + cachestr + ", 缓存内容: " + JSON.stringify(cacheInfo));
        return {
          "status": 1,    //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      }
      let rc = system.getObject("util.execClient");
      let obj = await this.actionBodyHandler(datajson.actionBody);
      let requrl = this.icUrl + "/deliverybillCtl/createOrderByPush";
      //渠道名称和渠道编码
      obj.channelSource = channelobj.name;
      obj.channelNumber = channelobj.code;

      //如果订单状态为已支付
      if (datajson.actionBody.needsolution.status == "PAID") {
        //查询业务员信息并填充到obj
        if (datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId) {
          //去数据库查询该业务员信息
          obj.salesmanOpcode = `root10/bizgroup01/g1members/${datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId}`;
          try {
            let resInfo = await this.userService.getSalesmanInfo(datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId);
            if (resInfo) {
              obj.salesmanOpcode = resInfo.opath;
              obj.salesmanName = resInfo.nickName;
              obj.servicerCode = resInfo.company_id;
            }
          } catch (error) {
            console.log("salesmanChannelId: " + datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId + "获取业务员opcode失败:" + error)
          }
        }

      }

      //获取交付商id
      if (!obj.servicerCode) {
        let companyInfo = await this.userService.getCompanyIdByName(obj.servicerName);
        if (companyInfo && companyInfo.id) {
          obj.servicerCode = companyInfo.id;
        }
      }


      //设置成本
      if (obj.skuCode) {
        obj.costPrice = await this.userService.findCostBySkuCode(obj.skuCode)
      }

      //异步更新需求状态 channelNeedNo
      if (datajson.actionBody && datajson.actionBody.channelNeedNo) {
        var stau = {
          "businessMode": datajson.actionBody.channelNeedNo,
          "currentStatus": "isFinished"
        }
        rc.execPost3({ "d": stau }, this.icUrl + "/bizoptCtl/updateStatusByDemandCode");//更新商机状态为已完成
      }

      var rtn = await rc.execPost3({ "d": obj }, requrl);
      console.log("pushOrderDelivery插入数据成功---------------------------------" + rtn.stdout);
      var j = JSON.parse(rtn.stdout);
      if (j.status == 0) {
        await this.cacheManager["AliCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);
        j.status = 1;
      }
      return j
    } catch (error) {
      console.log("error-------------------------------------" + error);
      return system.getResultError(error);
    }
  }


  //客户状态处理 
  async deliveryNotify(datajson) {
    try {
      var cachestr = sha235(JSON.stringify(datajson));
      var cacheInfo = await this.cacheManager["AliCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        return {
          "status": 1,    //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      }
      else {
        var rc = system.getObject("util.execClient");
        var requrl = this.icUrl + "/deliverybillCtl/updateFileAndStatusByDelivertCode";
        var params = {
          "d": {
            "deliverNumber": datajson.actionBody.orderNo,
          }
        }
        if (datajson.actionBody.needsolution.status == "CLOSE" || datajson.actionBody.needsolution.status == "ABC_CLOSE_PRODUCE") {//方案关闭
          params.d.deliverStatus = "closed";
          params.d.memoInfo = datajson.actionBody.needsolution.customerRemark
        } else {
          throw new Error(`needsolution.status 状态错误`);
        }
        var rtn = await rc.execPost3(params, requrl);
        var j = JSON.parse(rtn.stdout);
        if (j.status == 0) {
          await this.cacheManager["AliCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);//插入缓存
          j.status = 1;

        }
        return j;
      }
    }
    catch (error) {
      return system.getResultError(error);
    }
  }

  async actionBodyHandler(actionBody) {
    let data = actionBody;
    let obj = {};
    obj.baseInfo = {};
    obj.companyInfo = {};
    obj.registeredInfo = {};
    obj.positionInfo = {};
    obj.regInfo = {};
    obj.express_info = {};

    if (data.orderNo) {//交付单编号
      obj.deliverNumber = data.orderNo;
    }
    if (data.servicer) {//服务商信息
      if (data.servicer.name) {//服务商名称
        obj.servicerName = data.servicer.name;
      }
    }
    if (data.channelNeedNo) {//需求编号
      obj.businessMode = data.channelNeedNo;
    }
    if (data.channelSolutionNo) {//方案编号
      obj.schemeNumber = data.channelSolutionNo;
    }
    if (data.needsolution.solution.Area) {//服务地区编码和服务地区
      obj.serviceCode = data.needsolution.solution.Area;
      obj.serviceName = data.needsolution.solution.Area;
      obj.baseInfo.serviceName = data.needsolution.solution.Area;
    }

    if (data.needsolution.solution.area) {//服务地区编码和服务地区
      obj.serviceCode = data.needsolution.solution.area;
      obj.serviceName = data.needsolution.solution.area;
      obj.baseInfo.serviceName = data.needsolution.solution.area;
    }

    if (data.needsolution.solution.CompanyName) {//公司名称
      obj.baseInfo.companyName = data.needsolution.solution.CompanyName;
      obj.companyName = data.needsolution.solution.CompanyName;
    }
    if (data.needsolution.solution.companyName) {//公司名称
      obj.baseInfo.companyName = data.needsolution.solution.companyName;
      obj.companyName = data.needsolution.solution.companyName;
    }
    if (data.needsolution.solution.CompanyAddress) {//公司地址
      obj.baseInfo.companyAddress = data.needsolution.solution.CompanyAddress;
    }
    if (data.needsolution.solution.companyLocation) {//服务地区编码和服务地区
      obj.serviceCode = data.needsolution.solution.companyLocation;
      obj.serviceName = data.needsolution.solution.companyLocation;
      obj.baseInfo.serviceName = data.needsolution.solution.companyLocation;
    }

    if (data.needsolution.solution.ActionType) {//证件类型:新办 续期 变更
      obj.baseInfo.actionType = data.needsolution.solution.ActionType;
    }
    if (data.needsolution.solution.LicenseType) {//⽹⽂类型：⽹络表演
      obj.baseInfo.licenseType = data.needsolution.solution.LicenseType;
    }
    if (data.needsolution.solution.taxpayerType) {//工商
      obj.baseInfo.taxpayerType = data.needsolution.solution.taxpayerType;
    }
    if (data.needsolution.solution.companyProperties) {//工商
      obj.baseInfo.companyProperties = data.needsolution.solution.companyProperties;
    }



    if (data.needsolution.bizType) { //产品编码
      if (data.needsolution.bizType == "icpsq") {
        obj.businessType = "ICP";
      }
      if (data.needsolution.bizType == "edisq") {
        obj.businessType = "EDI";
      }
      if (data.needsolution.bizType == "bdnc") {
        obj.businessType = "wangwen";
      }
      if (data.needsolution.bizType == "bdrt") {
        obj.businessType = "guangbo";
      }
      if (data.needsolution.bizType == "food") {
        obj.businessType = "food";
      }
      if (data.needsolution.bizType == "GSREG") {
        obj.businessType = "companyCase";
      }
    }
    if (data.needsolution.typeName) { //产品名称
      if (data.needsolution.typeName == "icp申请") {
        obj.businessName = "icp";
      } else if (data.needsolution.typeName == "edi申请") {
        obj.businessName = "edi";
      } else if (data.needsolution.typeName == "文网文") {
        obj.businessName = "文网文";
      } else {
        obj.businessName = data.needsolution.typeName
      }
    }
    if (data.skuCode) { //产品的sku
      obj.skuCode = data.skuCode;
    }
    if (data.needsolution.status) { //交付单状态码
      if (data.needsolution.status == "PAID") {//已支付
        obj.deliverStatus = "received";
      }
      if (data.needsolution.status == "USER_PAY_PRODUCE") {//已支付
        obj.deliverStatus = "received";
      }
    }
    if (data.needsolution.customerRemark) { //状态原因
      obj.statusReason = data.needsolution.customerRemark;
    }
    // if (data.needsolution.status) { //成本
    //   obj.costPrice = data.needsolution.status;
    // }
    if (data.needsolution.totalSum) { //价格
      obj.sellingPrice = data.needsolution.totalSum;
    }

    if (data.needsolution.salesmanInfo) {//业务员id
      if (data.needsolution.salesmanInfo.salesmanId) {
        obj.salesmanId = data.needsolution.salesmanInfo.salesmanId;
      }
      if (data.needsolution.salesmanInfo.salesmanName) {//业务员name
        obj.salesmanName = data.needsolution.salesmanInfo.salesmanName;
      }
      if (data.needsolution.salesmanInfo.salesmanMobile) {//业务员手机
        obj.salesmanPhone = data.needsolution.salesmanInfo.salesmanMobile;
      }
    }


    if (data.needsolution.customerInfo) {//联系人
      if (data.needsolution.customerInfo.publishName) {
        obj.baseInfo.contactsName = data.needsolution.customerInfo.publishName;
      }
      if (data.needsolution.customerInfo.publishMobile) {//联系电话
        obj.baseInfo.contactsPhone = data.needsolution.customerInfo.publishMobile;
      }
    }
    if (data.needsolution.customerRemark) {//备注信息
      obj.baseInfo.memoInfo = data.needsolution.customerRemark;
    }
    if (data.needsolution.customerMaterial) {//客户上传所有材料
      obj.baseInfo.customerMaterial = data.needsolution.customerMaterial;
    }
    if (data.needsolution.solutionFlowList) {//流程记录
      obj.baseInfo.solutionFlowList = data.needsolution.solutionFlowList;
    }
    return obj;
  }

}



module.exports = new BaiduHandler();