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

  /**
   * 需要调用生成者接口，把数据丢入队列
   * 组装生产者需要的数据结构
   * @param {*} datajson 
   */
  //新商机处理
  async addChance(datajson) {
    console.log("put in queue  [addChance]", 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 + "/bizoptCtl/insertInfo";
        let { actionBody } = datajson;
        var params = {
          businessMode: actionBody.intentionBizId,
          servicerCode: "10",
          servicerName: "公司宝",
          serviceName: actionBody.area,
          contactsPhone: actionBody.phone || actionBody.mobile,
          currentStatus: "beforeSubmission",
          channelSource: "阿里云",
          channelNumber: "aliCloud",
          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"
          }
        }

        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 }), 180000);//插入redis缓存
        }
        return j;
      }
    }
    catch (error) {
      console.log("TTTTTTTTTTTTTT");
      console.log(error);
      return system.getResultError(error);
    }
  }

  async updateChanceStatus(datajson) {
    console.log("put in queue  [updateChanceStatus]" + JSON.stringify(datajson) + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
    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
          default:
            return system.getResultError("status 状态值错误");
        }
        let rtn = await rc.execPost3({ "d": stau }, requrl);//更新商机状态为已完成
        var j = JSON.parse(rtn.stdout);
        return j
      }
    } catch (error) {
      return system.getResultError(error);
    }
  }


  //退回商机处理
  async needClose(datajson) {
    console.log("put in queue" + JSON.stringify(datajson) + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
    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 + "/schemeCtl/updateStatusByDemandCode";
        var params = {
          "d": {
            "businessMode": datajson.actionBody.NeedNum,
            "schemeNumber": datajson.actionBody.SolutionNum,
            "currentStatus": "isReject",
            "statusReason": datajson.actionBody.RefusalContent
          }
        }
        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 }), 180000);//插入缓存

          //给业务员发信息
          var selUrl = this.icUrl + "/schemeCtl/findInfoByDemandCode";
          var selpar = {
            "d": {
              "businessMode": datajson.actionBody.NeedNum
            }
          }
          rtn = await rc.execPost3(selpar, selUrl);
          var jj = JSON.parse(rtn.stdout);
          console.log("jj------------------------------" + rtn.stdout);
          if (jj.status == 0 && jj.data) {
            var msg = {
              "title": "你有退回的商机，请尽快处理",
              "content": "商机编号" + jj.data.businessMode + ",商机类型是" + jj.data.businessName,
              "sender": "管理员",
              "sender_id": 0,
              "msgType": "single",
              "target": { "id": jj.data.clerkId, "name": jj.data.clerkName },
            }
            if (jj.data.businessType == "ICP" || jj.data.businessType == "EDI" || jj.data.businessType == "ICPANNUALREPORT" || jj.data.businessType == "EDIANNUALREPORT") {
              msg.app_key = "5ae2da88-0ced-4b7a-98ea-60d5e1ff7e2e";
              msg.jump_address = "allDispose"
            }
            else {
              msg.app_key = "42d814c1-4daa-4643-88b2-f5dd3ec853f3";
              msg.jump_address = "myChance"
            }
            var msgInfo = await this.msgService.create(msg);
            console.log("msgInfo -----------------------------" + msgInfo);
          }

          return {
            "status": 1,    //1代表成功，否则失败
            "msg": "成功",
            "data": "",
            "requestId": ""
          }
        }
        else {
          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": ""
        }
      }
      // else {
      //   var rc = system.getObject("util.execClient");
      //   var requrl = this.icUrl + "/deliverybillCtl/findInfoByDeliverCode";
      //   var delInfo = await rc.execPost3({ "d": { "deliverNumber": datajson.actionBody.orderNo } }, requrl);
      //   console.log("jdelInfo---------------------------------------------" + delInfo.stdout);
      //   var jdelInfo = JSON.parse(delInfo.stdout);
      //   if (jdelInfo.status == 0) {
      //     return {
      //       "status": 1,    //1代表成功，否则失败
      //       "msg": "数据已存在",
      //       "data": "",
      //       "requestId": ""
      //     }
      //   }
      //   else {}
      // }
      let rc = system.getObject("util.execClient");
      let obj = await this.actionBodyHandler(datajson.actionBody);
      let requrl = this.icUrl + "/deliverybillCtl/dealAliDeliveryInfo";
      // var bizurl = this.icUrl + "/bizoptCtl/updateStatusByDemandCode";
      //渠道名称和渠道编码
      obj.channelSource = channelobj.name;
      obj.channelNumber = channelobj.code;

      //如果订单状态为已支付
      if (datajson.actionBody.needsolution.status && datajson.actionBody.needsolution.status == "PAID") {
        //查询业务员信息并填充到obj
        if (datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId) {
          //去数据库查询该业务员信息
          try {
            let resInfo = await this.userService.getSalesmanInfo(datajson.actionBody.needsolution.salesmanInfo.salesmanChannelId);
            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)
          }
        }

        //分配交付员
        var ConsultTypeName = "";
        if (obj.businessName && obj.businessName != 'undefined') {
          console.log("productTypeName-----------------------------" + obj.businessName);
          ConsultTypeName = obj.businessName;
        }
        try {
          var deliveryInfo = await this.userService.getBizUserForAliDelivery(obj.baseInfo.contactsName, obj.servicerName, ConsultTypeName, obj.skuCode, obj.serviceName);
        } catch (error) {
          console.log("分配交付员失败.", error);
        }

        if (deliveryInfo && deliveryInfo != 'undefined') {
          obj.clerkOpcode = deliveryInfo.opath;//交付员opcode
          obj.clerkId = deliveryInfo.userId;//交付员id
          // obj.costPrice = deliveryInfo.cost;//成本
          obj.clerkName = deliveryInfo.nickName;//交付员名称
          // obj.clerkPhone = deliveryInfo.mobile;//交付人员电话
          // obj.servicerCode = deliveryInfo.compId;
        }
        //设置成本
        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");//更新商机状态为已完成
        }
      }

      console.log("推送数据obj: " + JSON.stringify(obj));
      var rtn = await rc.execPost3({ "d": obj }, requrl);
      console.log("pushOrderDelivery插入数据成功---------------------------------" + rtn.stdout);
      let cacheDeliveryInfo = await this.cacheManager["AliCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);
      console.log("交付单缓存信息: " + JSON.stringify(cacheDeliveryInfo));
      return {
        "status": 1,    //1代表成功，否则失败
        "msg": "",
        "data": "",
        "requestId": ""
      }
    }
    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.orderNum,
            "baseInfo": {}
            // "deliverStatus": "closed",
            // "statusReason": datajson.actionBody.refusalContent
          }
        }
        title = "";
        if (datajson.actionBody.status == "USER_CONFIRMED") {//用户已确认递交文件
          title = "用户已确认递交文件";
          params.d.deliverStatus = "userConfirmationResolve";
          params.d.customerMaterial = datajson.actionBody.customerMaterial;
        }
        else if (datajson.actionBody.status == "CLOSE") {//方案关闭
          title = "方案已关闭";
          params.d.deliverStatus = "closed";
        }
        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);//插入缓存
          //给业务员发信息
          var selUrl = this.icUrl + "/deliverybillCtl/findInfoByDeliverCode";
          var selpar = {
            "d": {
              "deliverNumber": datajson.actionBody.orderNum
            }
          }
          rtn = await rc.execPost3(selpar, selUrl);
          var jj = JSON.parse(rtn.stdout);
          console.log("jj-------------------------" + rtn.stdout);
          if (jj.status == 0 && jj.data) {
            var msg = {
              "title": "你有" + title + "的交付单，请尽快处理",
              "content": "交付单编号" + jj.data.delivery_code + ",产品类型是" + jj.data.product_name,
              "sender": "管理员",
              "sender_id": 0,
              "msgType": "single",
              "target": { "id": jj.data.salesman_id, "name": jj.data.salesman_name },
            }
            if (jj.data.product_code == "ICP" || jj.data.product_code == "EDI" || jj.data.product_code == "ICPANNUALREPORT" || jj.data.product_code == "EDIANNUALREPORT") {
              msg.app_key = "5ae2da88-0ced-4b7a-98ea-60d5e1ff7e2e";
              msg.jump_address = "deliveryAll"
            }
            else {
              msg.app_key = "42d814c1-4daa-4643-88b2-f5dd3ec853f3";
              msg.jump_address = "myDeliver"
            }
            await this.msgService.create(msg);
          }
          return {
            "status": 1,    //1代表成功，否则失败
            "msg": "",
            "data": "",
            "requestId": ""
          }

        }
        else {
          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.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.bizType) { //产品编码
      if (data.needsolution.bizType == "icpsq") {
        obj.businessType = "ICP";
      }
      if (data.needsolution.bizType == "edisq") {
        obj.businessType = "EDI";
      }
    }
    if (data.needsolution.typeName) { //产品名称
      if (data.needsolution.typeName == "icp申请") {
        obj.businessName = "icp";
      }
      if (data.needsolution.typeName == "edi申请") {
        obj.businessName = "edi";
      }
    }
    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_UPLOADED") {//已上传
        obj.deliverStatus = "collecting";
      }
    }
    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 AliHandler();

// (async ()=>{
//   var task = new AliHandler();
//   var d = await task.userService.getBizUserForDelivery("16512345678","公司宝","公司注册","sv_business_registration_category_limited1","北京");
//   console.log("ddddddddddddd");
//   console.log(JSON.stringify(d));
//   console.log("dddddddddddddd");
// })()

// let userService = system.getObject("service.auth.userSve");
// start();
// async function start() {
//   console.log('开始:')
//   try {
//     let result = await userService.getBizUserForAliDelivery(" ", "公司宝", "icp", "sv_vat_shareholder_domestic1015", "北京市");
//     console.log('=-=-=-=-=-=:'+JSON.stringify(result));
//   } catch (error) {
//     console.log("getBizUserForAliDelivery err: "+ error);
//   }  
// }
// let userService = system.getObject("service.auth.userSve");
// start();
// async function start() {
//   let resInfo = await userService.getSalesmanInfo("5ddf5f5d8b13b0000a3f2b18");
//   console.log("ceshi:" + JSON.stringify(resInfo));
// }