var system = require("../../../system");
const http = require("http");
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const moment = require('moment');
const appconfig = system.getSysConfig();
class DeliverybillCtl extends CtlBase {
  constructor() {
    super("bizchance", CtlBase.getServiceName(DeliverybillCtl));
    this.materialService = system.getObject("service.bizchance.materialSve");
    this.schemeService = system.getObject("service.bizchance.schemeSve");
    this.bizoptService = system.getObject("service.bizchance.bizoptSve");
    this.logService = system.getObject("service.bizchance.statuslogSve");
    this.cacheService = system.getObject("service.bizchance.cacheinfoSve");
    this.shisService = system.getObject("service.bizchance.salesmanhisSve");
    this.receiveUrl = settings.receiveUrl();
    this.queueUrl = settings.queueUrl();
    this.wdyUrl = settings.wdyUrl();
    this.dateUtil = system.getObject("util.dateClient");
  }

  /*根据用户id获取商机信息，分页获取*/
  async findAndCountAll(pobj, qobj, req) {
    try {
      //TODO 根据业务员id获取该业务员所有交付单列表
      if (pobj.search && pobj.search.dateType) {
        if (pobj.search.dateType !== '全部') {
          pobj.search.created_at = this.dateUtil.betweenTime(pobj.search.dateType);
        }
        delete pobj.search.dateType
      }

      const rs = await this.service.findAndCountAll(pobj);
      let rarr = [];
      let results = rs.results.rows;
      console.log("-----------------------------------------" + JSON.stringify(results));
      results.forEach(element => {
        let robj = {};
        robj.id = element.id;//数据的id
        robj.deliverNumber = element.delivery_code;//交付单编号
        robj.delivery_code = element.delivery_code;//交付单编号-shousuo
        robj.businessName = element.product_name;//产品名称
        robj.businessType = element.product_code;//产品编码
        robj.product_name = element.product_name;//产品名称-shousuo
        robj.product_code = element.product_code;//产品编码-shousuo
        robj.sourceName = element.source_name;//渠道来源
        robj.source_name = element.source_name;//渠道来源--前端服务
        robj.channelNumber = element.source_number;//渠道编码
        robj.facilitator_name = element.facilitator_name;//服务商--前端服务
        robj.facilitator_id = element.facilitator_id;//服务商--id
        if (element.delivery_info.serviceName && element.delivery_info.serviceName != 'undefined') {
          robj.serviceName = element.delivery_info.serviceName;
        }
        robj.baseInfo = element.delivery_info;//交付单详情
        robj.payStatus = element.delivery_info.payStatus;//交付状态
        if (element.pay_status && element.pay_status != 'undefined') {
          robj.pay_status = element.pay_status;//交付状态---前端服务
        }
        else {
          robj.pay_status = "";//交付状态---前端服务
        }

        robj.costPrice = this.FenToYuan(element.cost_price);//成本
        robj.settle_status = element.settle_status;
        robj.settlebill = element.settlebill;
        if (robj.businessName == '公司注册') {
          if (robj.baseInfo.isWhether == "yes" || robj.baseInfo.isVirtual == "yes") {//如果有刻章需求或者是虚拟地址
            robj.relatedProducts = '有';
          }
          else {
            robj.relatedProducts = '无';
          }
        }
        else if (robj.businessName == '云上园区注册') {
          robj.registeredType = element.delivery_info.registeredType;//园区注册时，根据该值跳界面
          if (robj.baseInfo.isWhether == "yes" || robj.baseInfo.financial == "yes") {//如果有刻章需求或者是财税服务
            robj.relatedProducts = '有';
          }
          else {
            robj.relatedProducts = '无';
          }
        }
        else {
          robj.relatedProducts = '无';
        };
        robj.payAmount = this.FenToYuan(element.selling_price);//交付单金额
        robj.selling_price = this.FenToYuan(element.selling_price);//交付单金额-shousuo
        robj.deliverStatus = element.delivery_status;//交付单状态
        robj.delivery_status = element.delivery_status;//交付单状态-shousuo
        robj.contactsName = robj.baseInfo.contactsName;//联系人
        robj.contactsPhone = robj.baseInfo.contactsPhone;//联系电话
        robj.v_coname = element.v_coname;//联系人-shousuo
        robj.v_cophone = element.v_cophone;//联系电话-shousuo
        robj.clerkName = element.salesman_name;//业务员名称
        robj.clerkPhone = element.salesman_phone;//业务员电话
        robj.deliveryName = element.delivery_man_name;//交付人员名称
        robj.createdTime = this.timeFormat(element.created_at);//交付单创建时间
        robj.created_at = this.timeFormat(element.created_at);//交付单创建时间-shousuo
        rarr.push(robj);
      });
      rs.results.rows = rarr;
      return system.getResult(rs);
    } catch (error) {
      console.log("error-------------------" + error);
      return system.getResultError(error);
    }
  }

  /*根据交付单编号获取交付单xinxi*/
  async findInfoByDeliverCode(mobj, qobj, req) {
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj);
        if (rs) {
          return system.getResult(rs);
        }
        else {
          return system.getResultError("数据不存在");
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误！");
    }
  }

  /*根据交付单编号获取交付单详情和材料详情*/
  async dealInfo(mobj, qobj, req) {
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj);
        var ms = await this.materialService.findInfoByDeliverNumber(pobj);
        var rarr = {
          "baseInfo": {},
          "contactsInfo": {},
          "statusInfo": {},
          "companyInfo": {},
          "registeredInfo": {},
          "contributionInfo": {},
          "positionInfo": {},
          "managerInfo": {},
          "regInfo": {},
          "expressInfo": {}
        }
        if (rs) {
          console.log("D___________________________" + JSON.stringify(rs));
          rarr.id = rs.id;//数据的id
          rarr.baseInfo.deliverNumber = rs.delivery_code;//交付单编号
          rarr.baseInfo.businessName = rs.product_name;//产品名称
          rarr.baseInfo.businessMode = rs.demand_code;//shangjibianhao
          rarr.baseInfo.businessType = rs.product_code;//产品编码
          rarr.baseInfo.channelSource = rs.source_name;//渠道名称
          rarr.baseInfo.channelNumber = rs.source_number;//渠道编码
          rarr.baseInfo.serviceCode = rs.service_address;//服务地区编码
          rarr.baseInfo.servicerCode = rs.facilitator_id;//服务商编码
          rarr.baseInfo.servicerName = rs.facilitator_name;//服务商名称
          rarr.baseInfo.clerkName = rs.salesman_name;//业务员名称
          rarr.baseInfo.clerkPhone = rs.salesman_phone;//业务员电话
          rarr.deliveryName = rs.delivery_man_name;//交付人员名称
          rarr.baseInfo.sellingPrice = this.FenToYuan(rs.selling_price);//价格
          rarr.baseInfo.costPrice = this.FenToYuan(rs.cost_price);//成本价
          rarr.baseInfo.deliverStatus = rs.delivery_status;//状态
          rarr.baseInfo.statusReason = rs.close_reason;//状态原因
          if (rarr.businessName == "云上园区注册") {
            rarr.baseInfo.serviceArea = appconfig.pdict.registeredParkDict[rarr.serviceCode];//服务地区名称
          }
          else {
            rarr.baseInfo.serviceArea = appconfig.pdict.registeredAreaDict[rarr.serviceCode];//服务地区名称
          }

          if (rs.delivery_info.contactsName && rs.delivery_info.contactsName != 'undefined') {
            rarr.contactsInfo.contactsName = rs.delivery_info.contactsName;//联系人信息
            rarr.baseInfo.contactsName = rs.delivery_info.contactsName;//联系人信息
          }
          if (rs.delivery_info.contactsPhone && rs.delivery_info.contactsPhone != 'undefined') {
            rarr.contactsInfo.contactsPhone = rs.delivery_info.contactsPhone;//联系电话信息
            rarr.baseInfo.contactsPhone = rarr.contactsInfo.contactsPhone;//联系电话信息
          }

          if (rs.delivery_info.isWhether && rs.delivery_info.isWhether != 'undefined') {
            rarr.baseInfo.isWhether = rs.delivery_info.isWhether;//是否刻章
          }
          //财税服务
          if (rs.delivery_info.financial && rs.delivery_info.financial != 'undefined') {
            rarr.baseInfo.financial = rs.delivery_info.financial;
          }
          if (rs.delivery_info.payStatus && rs.delivery_info.payStatus != 'undefined') {
            rarr.baseInfo.payStatus = rs.delivery_info.payStatus;//支付状态
          }
          if (rs.delivery_info.officialSeal && rs.delivery_info.officialSeal != 'undefined') {
            rarr.baseInfo.officialSeal = rs.delivery_info.officialSeal;//公章扫描件
          }
          if (rs.delivery_info.isAdviser && rs.delivery_info.isAdviser != 'undefined') {
            rarr.baseInfo.isAdviser = rs.delivery_info.isAdviser;//是否分配顾问
          }
          if (rs.delivery_info.businessLicense && rs.delivery_info.businessLicense != 'undefined') {
            rarr.baseInfo.businessLicense = rs.delivery_info.businessLicense;//营业执照扫描件
          }
          if (rs.delivery_info.taxpayerType && rs.delivery_info.taxpayerType != 'undefined') {
            rarr.baseInfo.taxpayerType = rs.delivery_info.taxpayerType;//纳税人类型
          }
          if (rs.delivery_info.buyDuration && rs.delivery_info.buyDuration != 'undefined') {
            rarr.baseInfo.buyDuration = rs.delivery_info.buyDuration;//购买时长
          }
          if (rs.delivery_info.buyTime && rs.delivery_info.buyTime != 'undefined') {
            rarr.baseInfo.buyTime = rs.delivery_info.buyTime;//购买时间
          }
          if (rs.delivery_info.startTime && rs.delivery_info.startTime != 'undefined') {
            rarr.baseInfo.startTime = rs.delivery_info.startTime;//开始计费时间
          }
          if (rs.delivery_info.buyDuration && rs.delivery_info.buyDuration != 'undefined' && rarr.baseInfo.startTime && rarr.baseInfo.startTime != 'undefined') {
            console.log("ddddddddddd____________________________" + rarr.baseInfo.startTime);
            var d = new Date(rarr.baseInfo.startTime);
            console.log("ddddddddddd____________________________" + d);
            rarr.baseInfo.endTime = this.oneYearPast(d, 1);//到期时间
            var ss = moment();
            rarr.baseInfo.surplusDuration = this.diffDays(ss, rarr.baseInfo.endTime);//剩余时长
          }
          if (rs.delivery_info.isRenew && rs.delivery_info.isRenew != 'undefined') {
            rarr.baseInfo.isRenew = rs.delivery_info.isRenew;//是否自动续费
          }
          if (rs.delivery_info.whetherType && rs.delivery_info.whetherType != 'undefined') {
            rarr.baseInfo.whetherType = rs.delivery_info.whetherType;//刻章类型
          }
          if (rs.delivery_info.subjectType && rs.delivery_info.subjectType != 'undefined') {
            rarr.baseInfo.subjectType = rs.delivery_info.subjectType;//代理记账主体类型
          }
          rarr.baseInfo.createdTime = this.timeFormat(rs.created_at);
          rarr.baseInfo.updateTime = this.timeFormat(rs.updated_at)


          rarr.statusInfo.deliverStatus = rs.delivery_status;//状态
          rarr.statusInfo.statusReason = rs.close_reason;//状态原因
          rarr.companyInfo = ms.company_info;//公司详情
          rarr.registeredInfo = ms.registered_info;//注册信息
          rarr.contributionInfo = ms.contribution_info;//出资比例信息
          rarr.positionInfo = ms.position_info;//任职信息；公司注册和个人独资时取该值
          rarr.managerInfo = ms.position_info;//经营者信息，个体工商户的经营者信息取该值
          rarr.regInfo = ms.file_info;//注册文件信息
          rarr.expressInfo = ms.express_info;//邮寄信息
        }
        return system.getResult(rarr);
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误！");
    }
  }

  async updateFileAndStatusByDelivertCode(mobj, qobj, red) {//阿里更新状态和盖章文件
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj)//先得到交付单详情
        if (rs && rs != 'undefined') {
          pobj.baseInfo = rs.delivery_info;
          if (pobj.customerMaterial && pobj.customerMaterial != 'undefined') {
            pobj.baseInfo.customerMaterial = pobj.customerMaterial;
          }
          await this.service.updateInfoByDeliverCode(pobj);
          return system.getResult("更新成功");
        }
        else {
          return system.getResultError("数据不存在！");
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }

  }

  async updatestartTimeByDeliverCode(mobj, qobj, red) {//根据交付单编号更新开始计费时间
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined' && pobj.baseInfo.startTime && pobj.baseInfo.startTime != 'undefined') {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj)//先得到交付单详情
        if (rs && rs != 'undefined') {
          rs.delivery_info.startTime = pobj.baseInfo.startTime;
          var d = new Date(rs.delivery_info.startTime);
          rs.delivery_info.endTime = this.oneYearPast(d, 1);//到期时间
          //回传信息给庄冰，放队列
          var rc = system.getObject("util.execClient");
          var requrl = this.queueUrl;
          var params = {
            "actionType": "produceData",
            "actionBody": {
              "pushUrl": this.receiveUrl,
              "actionType": "updateOrderStatus",
              "identifyCode": "ic-manage",
              "messageBody": {
                "orderNum": pobj.deliverNumber,//订单编码
                "status": appconfig.pdict.ddyDict[rs.delivery_status],
                "deliverContent": { "baseInfo": rs.delivery_info }
              }
            }
          }
          var rtn = await rc.execPost(params, requrl);
          var j = JSON.parse(rtn.stdout);
          console.log("RRRRRRRRRRRRRR");
          console.log(JSON.stringify(j));

          params = {
            "actionType": "produceData",
            "actionBody": {
              "pushUrl": this.wdyUrl,
              "actionType": "jftime",
              "identifyCode": "ic-manage",
              "messageBody": {
                "orderNum": pobj.deliverNumber,//订单编码
                "startTime": rs.delivery_info.startTime,
                "endTime": rs.delivery_info.endTime
              }
            }
          }
          rtn = await rc.execPost(params, requrl);
          var j1 = JSON.parse(rtn.stdout);
          console.log("R1RRRRR1RR1RRRR1RR1");
          console.log(JSON.stringify(j1));
          if (j.status == 1 && j1.status == 1) {
            //更新详情
            var uarr = {
              "deliverNumber": pobj.deliverNumber,
              "baseInfo": rs.delivery_info
            };
            await this.service.updateInfoByDeliverCode(uarr);
            return system.getResult("更新成功");
          }
          else {
            return system.getResultError("更新失败！");
          }
        }
        else {
          return system.getResultError("数据不存在！");
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }
  /*根据交付单编号更新交付单状态*/
  async updateStatusByDeliverCode(mobj, qobj, req) {
    var pobj = mobj.d;
    console.log("--------------------" + JSON.stringify(pobj));
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined' && pobj.deliverStatus && pobj.deliverStatus != 'undefined') {
      try {
        //调商城接口，回传状态信息，放队列
        var rc = system.getObject("util.execClient");
        var requrl = this.queueUrl;
        var params = {
          "actionType": "produceData",
          "actionBody": {
            "pushUrl": this.receiveUrl,
            "actionType": "updateOrderStatus",
            "identifyCode": "ic-manage",
            "messageBody": {
              "orderNum": pobj.deliverNumber,//订单编码
              "status": appconfig.pdict.ddyDict[pobj.deliverStatus]
              //"deliverContent":pobj
            }
          }
        }
        var rtn = await rc.execPost(params, requrl);
        console.log("_____________________________" + rtn.stdout);
        var j = JSON.parse(rtn.stdout);

        var j1status = 1;
        if (pobj.deliverStatus == "closed") {//退款
          params = {
            "actionType": "produceData",
            "actionBody": {
              "pushUrl": this.wdyUrl,
              "actionType": "refundOrder",
              "identifyCode": "ic-manage",
              "messageBody": {
                "orderNum": pobj.deliverNumber//订单编码
              }
            }
          }
          rtn = await rc.execPost(params, requrl);
          console.log("_____________________________tuifei" + rtn.stdout);
          var j1 = JSON.parse(rtn.stdout);
          j1status = j1.status;
        }
        if (j.status == 1 && j1status == 1) {
          await this.service.updateStatusByDeliverCode(pobj);
          var pInfo = await this.service.findInfoByDeliverCode(pobj);
          if (pInfo) {
            var logInfo = {
              "flowType": "DELIVERY",
              "flowId": pInfo.id,
              "statusCode": pobj.deliverStatus,
              "clerkName": pInfo.salesman_name,
              "clerkId": pInfo.salesman_id,
              "deliveryId": pInfo.delivery_man_id,
              "deliveryName": pInfo.delivery_man_name
            }
            if (pInfo.statusReason && pInfo.statusReason != 'undefined') {
              logInfo.statusReason = pInfo.statusReason;
            }
            await this.logService.insertInfo(logInfo);//插入状态日至表
          }
          return system.getResult("更新成功！");
        }
        else {
          return system.getResultError("更新状态失败！");
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }

  async UpdateofficialSealByDeliverCode(mobj, qobj, req) {//更新营业执照扫描件和公章扫描件
    var pobj = mobj.d;
    if ((pobj.deliverNumber && pobj.deliverNumber != 'undefined' && ((pobj.baseInfo.officialSeal && pobj.baseInfo.officialSeal != 'undefined') || (pobj.baseInfo.businessLicense && pobj.baseInfo.businessLicense != 'undefined')))) {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj)//先得到交付单详情
        if (rs && rs != 'undefined') {
          if (pobj.baseInfo.officialSeal && pobj.baseInfo.officialSeal != 'undefined') {
            rs.delivery_info.officialSeal = pobj.baseInfo.officialSeal;
          }
          if (pobj.baseInfo.businessLicense && pobj.baseInfo.businessLicense != 'undefined') {
            rs.delivery_info.businessLicense = pobj.baseInfo.businessLicense;
          }
          //回传信息给庄冰，放队列
          var rc = system.getObject("util.execClient");
          var requrl = this.queueUrl;
          var params = {
            "actionType": "produceData",
            "actionBody": {
              "pushUrl": this.receiveUrl,
              "actionType": "updateOrderStatus",
              "identifyCode": "ic-manage",
              "messageBody": {
                "orderNum": pobj.deliverNumber,//订单编码
                "status": appconfig.pdict.ddyDict[rs.delivery_status],
                "deliverContent": { "baseInfo": rs.delivery_info }
              }
            }
          }
          var rtn = await rc.execPost(params, requrl);
          var j = JSON.parse(rtn.stdout);
          console.log("RRRRRRRRRRRRRR");
          console.log(JSON.stringify(j));
          if (j.status == 1) {
            //更新详情
            var uarr = {
              "deliverNumber": pobj.deliverNumber,
              "baseInfo": rs.delivery_info
            };
            await this.service.updateInfoByDeliverCode(uarr);
            return system.getResult("更新成功");
          }
          else {
            return system.getResultError("更新失败！");
          }
        }
        else {
          return system.getResultError("数据不存在！");
        }

      }
      catch (error) {
        console.log("##########");
        console.log(error);
        return system.getResultError(error);
      }
    }
    else {
      console.log("参数错误" + pobj);
      return system.getResultError("参数错误！");
    }
  }

  async updateExpressInfoByDeliverCode(mobj, qobj, req) {//更新邮寄信息
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined' && pobj.expressInfo && pobj.expressInfo != 'undefined') {
      try {
        var deliverInfo = await this.service.findInfoByDeliverCode(pobj)//先得到交付单详情
        if (deliverInfo && deliverInfo != 'undefined') {
          //回传信息给庄冰，放队列
          var rc = system.getObject("util.execClient");
          var requrl = this.queueUrl;
          console.log("deliverNumber---------------------------" + pobj.deliverNumber);
          var params = {
            "actionType": "produceData",
            "actionBody": {
              "pushUrl": this.receiveUrl,
              "actionType": "updateOrderStatus",
              "identifyCode": "ic-manage",
              "messageBody": {
                "orderNum": pobj.deliverNumber,//订单编码
                "status": appconfig.pdict.ddyDict[deliverInfo.delivery_status],
                "deliverContent": { "expressInfo": pobj.expressInfo }
              }
            }
          }
          var rtn = await rc.execPost(params, requrl);
          var j = JSON.parse(rtn.stdout);
          console.log("EXEXEXEXEXEEEEEEEEEEEEEEEEEEE" + rtn.stdout);
          if (j.status == 1) {
            await this.materialService.updateInfoByDeliverNumber(pobj);
            return system.getResult("更新成功");
          }
          else {
            return system.getResultError("更新失败！");
          }

        }
        else {
          return system.getResultError("数据不存在！");
        }

      }
      catch (error) {
        console.log("Error-----------------------------------------------" + error);
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误！");
    }
  }

  /*更新业务员/交付员信息*/
  async updateUsermanInfoByDeliverCode(mobj, qobj, req) {
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var res = await this.service.findInfoByDeliverCode(pobj);
        if (res) {
          var sInfo = {
            "flowType": "DELIVERY",
            "flowId": res.id,
            "flowCode": pobj.deliverNumber,
            "salesmanInfo": {
              //"oldClerkPhone": res.salesman_phone,
              "oldFacilitatorId": res.facilitator_id,
              "oldFacilitatorName": res.facilitator_name,
              //"newClerkPhone": pobj.salesmanPhone,
              "newFacilitatorId": pobj.facilitatorId,
              "newFacilitatorName": pobj.facilitatorName
            }
          }
          if (pobj.type == "deliverman") {
            sInfo.salesmanInfo = {
              "oldOpcode": res.delivery_man_opcode,
              "oldClerkName": res.delivery_man_name,
              "oldClerkId": res.delivery_man_id,
              "newOpcode": pobj.deliverymanOpcode,
              "newClerkName": pobj.deliverymanName,
              "newClerkId": pobj.deliverymanId,
            }
          }
          if (pobj.type == "salesman") {
            sInfo.salesmanInfo = {
              "oldOpcode": res.sales_man_opcode,
              "oldClerkName": res.sales_man_name,
              "oldClerkId": res.sales_man_id,
              "newOpcode": pobj.salesmanOpcode,
              "newClerkName": pobj.salesmanName,
              "newClerkId": pobj.salesmanId,
            }
          }
          await this.shisService.insertInfo(sInfo);//之前业务员转历史
          await this.service.updateSalesmanInfoByDeliverCode(pobj);//更新业务员信息
          return system.getResult("操作成功！");
        }
        else {
          return system.getResultError("未找到相关数据");
        }

      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }

  /*根据交付单编号更新交付单详情*/
  async updateInfoByDeliverCode(mobj, qobj, req) {//
    var pobj = mobj.d;
    console.log("根据交付单编号更新交付单详情-------------------------" + JSON.stringify(pobj));
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var rs = await this.service.findInfoByDeliverCode(pobj)//先得到交付单详情
        var baseInfo = rs.delivery_info;
        if (pobj.contactsInfo.contactsName && pobj.contactsInfo.contactsName != 'undefined') {
          baseInfo.contactsName = pobj.contactsInfo.contactsName;
        }
        if (pobj.contactsInfo.contactsPhone && pobj.contactsInfo.contactsPhone != 'undefined') {
          baseInfo.contactsPhone = pobj.contactsInfo.contactsPhone;
        }
        var parms = {
          "deliverNumber": pobj.deliverNumber
        }
        if (rs.product_code == "psCase") {
          parms.deliverStatus = "checking";//状态为园区入驻审核
          baseInfo.payStatus = "已交付";
        }
        else if (rs.product_code == "companyCase") {
          parms.deliverStatus = "auditing";//状态为工商审核环节
          baseInfo.payStatus = "已交付";
        }
        parms.baseInfo = baseInfo;
        await this.service.updateInfoByDeliverCode(parms);
        //更新材料信息
        await this.materialService.updateInfoByDeliverNumber(pobj);
        //return system.getResult("操作成功！");
        //传给庄冰，tongbu
        baseInfo.clerkName = rs.salesman_name;//业务员名称
        baseInfo.clerkPhone = rs.salesman_phone;
        baseInfo.deliveryName = rs.delivery_man_name;//交付人员名称
        pobj.baseInfo = baseInfo;
        var rc = system.getObject("util.execClient");
        var requrl = this.receiveUrl;
        var params = {
          "actionType": "updateOrderStatus",
          "actionBody": {
            "orderNum": pobj.deliverNumber,//订单编码
            //"status":appconfig.pdict.ddyDict["collecting"],
            "deliverContent": pobj
          }
        }
        if (rs.product_code == "psCase") {
          params.actionBody.status = appconfig.pdict.ddyDict["checking"];
        }
        else if (rs.product_code == "companyCase") {
          params.actionBody.status = appconfig.pdict.ddyDict["auditing"];
        }
        else {
          params.actionBody.status = appconfig.pdict.ddyDict[rs.delivery_status];
        }
        var rtn = await rc.execPost(params, requrl);
        console.log("rtn-------------------------------------------" + rtn.stdout);
        var j = JSON.parse(rtn.stdout);
        if (j.status == 1) {
          return system.getResult("操作成功！");
        }
        else {
          return system.getResultError("更新交付单状态出错！");
        }
      }
      catch (error) {
        console.log("error-------------------------------------------" + error);
        return system.getResultError(error);
      }
    }
    else {
      console.log("参数错误-------------------------------------------参数错误！");
      return system.getResultError("参数错误！");
    }

  }

  async settleApplyForTacent(p, q, req) {
    let ids = p.ids
    let spname = p.spname
    let spid = p.spid
    let rtn = await this.service.settleApplyForTacent(ids, p.userid, p.username, spname, spid)
    return system.getResult({})
  }
  async settleApply(p, q, req) {
    let ids = p.ids
    let spname = p.spname
    let spid = p.spid
    let rtn = await this.service.settleApply(ids, p.userid, p.username, spname, spid)
    return system.getResult({})
  }

  async dealAliDeliveryInfo(nobj, qobj, req) {//插入交付单信息-阿里用
    var pobj = nobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var res = await this.service.findInfoByDeliverCode(pobj);
        if (res) {
          if (res.delivery_status != 'received'){//如果数据库中状态是已接单，说明是第一次提交文件，状态为传过了的状态；如果不是已接单，说明是客户驳回后重新提交的文件，状态改为已驳回
            pobj.deliverStatus = "userConfirmationReject";//状态改成驳回,
          }
          await this.service.updateInfoByDeliverCode(pobj);
          return system.getResultSuccess();
          //return await this.service.updateInfoByDeliverCode(pobj);
        }
        else {
          return await this.service.insertInfoall(pobj);
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }

  /*根据商机编号插入交付单信息*/
  async insertInfo(nobj, qobj, req) {//队列的时候用
    var pobj = nobj.d;
    console.log("根据交付单编号更新交付单详情-------------------------" + JSON.stringify(pobj));
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        //pobj.deliverStatus = "received";
        pobj.businessType = appconfig.pdict.dyDict[pobj.businessType];
        if (pobj.companyInfo.companyPropertiesName && pobj.companyInfo.companyPropertiesName != 'undefined') {
          if (pobj.businessName == "公司注册") {
            pobj.companyInfo.companyProperties = appconfig.pdict.companyNatureDictT[pobj.companyInfo.companyPropertiesName];
            pobj.baseInfo.companyProperties = pobj.companyInfo.companyProperties;
            pobj.baseInfo.companyType = pobj.companyInfo.companyProperties;
          }
          else if (pobj.businessName == "云上园区注册") {
            pobj.companyInfo.companyProperties = appconfig.pdict.registeredTypeDictT[pobj.companyInfo.companyPropertiesName];
            pobj.baseInfo.companyProperties = pobj.companyInfo.companyProperties;
            pobj.baseInfo.companyType = pobj.companyInfo.companyProperties;
          }
          else {
            pobj.companyInfo.companyType = pobj.companyInfo.companyPropertiesName;
            pobj.baseInfo.companyProperties = pobj.companyInfo.companyPropertiesName;
            pobj.baseInfo.companyType = pobj.companyInfo.companyPropertiesName;
          }

        }
        if (pobj.companyInfo.engagedIndName && pobj.companyInfo.engagedIndName != 'undefined') {
          pobj.companyInfo.engagedIndustry = appconfig.pdict.engagedIndustryDictT[pobj.companyInfo.engagedIndName];
        }
        if (pobj.baseInfo.taxpayerName && pobj.baseInfo.taxpayerName != 'undefined') {
          pobj.baseInfo.taxpayerType = appconfig.pdict.TaxpayerTypeDictT[pobj.baseInfo.taxpayerName];
          if (pobj.businessName == "公司注册" || pobj.businessName == "云上园区注册") {
            pobj.companyInfo.taxpayerType = pobj.baseInfo.taxpayerType;
          }
        }
        pobj.schemeNumber = "";
        pobj.salesmanOpcode = "";
        pobj.salesmanName = "";
        pobj.salesmanId = "";
        pobj.salesmanPhone = "";
        // pobj.channelSource = "tencentCloud";//目前渠道只有腾讯
        // pobj.channelNumber = "1111111";
        pobj.cacheInfo = {
          "cmpDeliverInfo": {},
          "cmpContactInfo": {}
        };
        if (pobj.businessMode && pobj.businessMode != 'undefined') {//如果有商机编号，需要取方案编号
          var schemeInfo = await this.schemeService.findInfoByDemandCode(pobj);
          if (schemeInfo && schemeInfo != 'undefined') {
            pobj.schemeNumber = schemeInfo.scheme_number;
            pobj.salesmanOpcode = schemeInfo.salesman_opcode;
            pobj.salesmanName = schemeInfo.salesman_name;
            pobj.salesmanId = schemeInfo.salesman_id;
            pobj.salesmanPhone = schemeInfo.salesman_phone;
            pobj.cacheInfo.cmpDeliverInfo = schemeInfo.scheme_info;//获取方案中的缓存信息
          }
        }
        //缓存信息和交付单保持一致
        console.log("---------------------------------------------------------------------------------------------------------------------------------------");
        if (pobj.companyInfo.companyProperties && pobj.companyInfo.companyProperties != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.companyProperties = pobj.companyInfo.companyProperties;
        }
        else {
          if (pobj.cacheInfo.cmpDeliverInfo.companyType && pobj.cacheInfo.cmpDeliverInfo.companyType) {
            pobj.cacheInfo.cmpDeliverInfo.companyProperties = pobj.cacheInfo.cmpDeliverInfo.companyType;
          }
        }
        console.log("---------------------------------------------------------------------------------------------------------------------------------------");

        if (pobj.baseInfo.memoInfo && pobj.baseInfo.memoInfo != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.memoInfo = pobj.baseInfo.memoInfo;
        }

        if (pobj.baseInfo.isWhether && pobj.baseInfo.isWhether != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.isWhether = pobj.baseInfo.isWhether;
        }
        if (pobj.baseInfo.financial && pobj.baseInfo.financial != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.financial = pobj.baseInfo.financial;
        }

        if (pobj.baseInfo.addressType && pobj.baseInfo.addressType != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.addressType = pobj.baseInfo.addressType;
        }

        if (pobj.baseInfo.companyName && pobj.baseInfo.companyName != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.companyName = pobj.baseInfo.companyName;
        }
        if (pobj.serviceCode && pobj.serviceCode != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.serviceArea = pobj.serviceCode;
        }
        if (pobj.serviceName && pobj.serviceName != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.serviceAreaName = pobj.serviceName;
          pobj.baseInfo.serviceName = pobj.serviceName;
        }
        if (pobj.companyInfo.businessScope && pobj.companyInfo.businessScope != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.businessScope = pobj.companyInfo.businessScope;
        }
        if (pobj.baseInfo.taxpayerType && pobj.baseInfo.taxpayerType != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.taxpayerType = pobj.baseInfo.taxpayerType;
        }
        if (pobj.baseInfo.taxpayerName && pobj.baseInfo.taxpayerName != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.taxpayerName = pobj.baseInfo.taxpayerName;
        }
        if (pobj.companyInfo.engagedIndustry && pobj.companyInfo.engagedIndustry != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.engagedIndustry = pobj.companyInfo.engagedIndustry;
        }
        if (pobj.companyInfo.engagedIndName && pobj.companyInfo.engagedIndName) {
          pobj.cacheInfo.cmpDeliverInfo.engagedIndName = pobj.companyInfo.engagedIndName
        }
        if (pobj.companyInfo.fullAddress && pobj.companyInfo.fullAddress != 'undefined') {
          pobj.cacheInfo.cmpDeliverInfo.fullAddress = pobj.companyInfo.fullAddress;
          pobj.cacheInfo.cmpDeliverInfo.residenceAddress = pobj.companyInfo.fullAddress;
        }
        if (pobj.baseInfo.contactsName && pobj.baseInfo.contactsName != 'undefined') {
          pobj.cacheInfo.cmpContactInfo.contactsName = pobj.baseInfo.contactsName;
        }

        if (pobj.baseInfo.contactsPhone && pobj.baseInfo.contactsPhone != 'undefined') {
          pobj.baseInfo.contactsPhone = pobj.baseInfo.contactsPhone;
          pobj.cacheInfo.cmpContactInfo.contactsPhone = pobj.baseInfo.contactsPhone;
        }
        if (pobj.baseInfo.virtualPrice && pobj.baseInfo.virtualPrice != 'undefined') {//虚拟地址价格
          pobj.cacheInfo.virtualPrice = pobj.baseInfo.virtualPrice;
        }

        if ((pobj.deliverNumber != pobj.txOrderNum) && (pobj.businessType == "sealSevCase" || pobj.businessType == "agentCase")) {
          pobj.companyInfo = {};
        }

        //更新状态给庄冰
        var rc = system.getObject("util.execClient");
        var requrl = this.queueUrl;
        var params = {
          "actionType": "produceData",
          "actionBody": {
            "pushUrl": this.receiveUrl,
            "actionType": "updateOrderStatus",
            "identifyCode": "ic-manage",
            "messageBody": {
              "orderNum": pobj.deliverNumber,//订单编码
              "status": 20,//已接单
              "deliverContent": pobj
            }
          }
        }
        var rtn = await rc.execPost(params, requrl);
        console.log("rtn---------------------------" + rtn.stdout);
        var j = JSON.parse(rtn.stdout);
        if (j.status == 1) {
          // var res = await this.service.insertInfo(pobj);//插入交付单列表
          // pobj.deliverId = res.id;
          // //插入暂存
          // if (pobj.cacheInfo && (pobj.businessType == "companyCase" || pobj.businessType == "psCase")) {
          //   await this.cacheService.insertInfo(pobj);
          // }
          // var logInfo = {
          //   "flowType": "DELIVERY",
          //   "flowId": res.id,
          //   "statusCode": res.delivery_status,
          //   "statusReason": res.close_reason,
          //   "clerkName": res.salesman_name,
          //   "clerkId": res.salesman_id
          // }
          // await this.logService.insertInfo(logInfo);//插入状态日至表
          // await this.materialService.insertInfo(pobj);//插入材料信息
          // return system.getResult("插入成功！");
          return await this.service.insertInfoall(pobj);
        }
        else {
          return system.getResultError("插入数据失败！");
        }

      }
      catch (error) {
        console.log("ERROR---------------------------" + error);
        return system.getResultError(error);
      }
    } else {
      return system.getResultError("参数错误!");
    }
  }
  /*获取压缩文件的信息 */
  async findZipUrlByDeliverCode(mobj, qobj, req) {//
    var pobj = mobj.d;
    if (pobj.deliverNumber && pobj.deliverNumber != 'undefined') {
      try {
        var ms = await this.materialService.findInfoByDeliverNumber(pobj);
        if (ms && ms != 'undefined') {
          if (ms.download_url && ms.download_url != undefined) {
            var comInfo = ms.company_info;
            var rtndata = {
              "zipUrl": ms.download_url,
              "companyName": comInfo.companyName
            }
            if (comInfo.companyProperties == "limitedLiabilityCompany") {
              rtndata.companyProperties = "有限责任公司"
            }
            else if (comInfo.companyProperties == "incorporatedCompany") {
              rtndata.companyProperties = "股份有限公司"
            }
            else if (comInfo.companyProperties == "groupLimitedCompany") {
              rtndata.companyProperties = "集团有限公司"
            }
            else if (comInfo.companyProperties == "selfEmployed") {
              rtndata.companyProperties = "个体工商户"
            }
            else if (comInfo.companyProperties == "soleProprietorship") {
              rtndata.companyProperties = "个人独资企业"
            }
            else if (comInfo.companyProperties == "company") {
              rtndata.companyProperties = "有限公司"
            }
            return system.getResult(rtndata);
          }
          else {
            return system.getResultError("暂没有url信息!");
          }
        }
        else {
          return system.getResultError("没有相关信息!");
        }
      }
      catch (error) {
        return system.getResultError(error);
      }
    }
    else {
      return system.getResultError("参数错误!");
    }
  }

  timeFormat(date) {
    let localTime = moment.utc(date).toDate();
    localTime = moment(localTime).format("YYYY-MM-DD");
    return localTime;
  }

  //元转分 - 解决精度问题 yuan:要转换的钱，单位元； digit：转换倍数
  YuanToFen(yuan, digit) {
    var m = 0,
      s1 = yuan.toString(),
      s2 = digit.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  }

  FenToYuan(fen) {
    var num = fen;
    num = fen * 0.01;
    num += '';
    var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, '$1');
    num = this.toDecimal2(num);
    return num;
  }

  toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    return s;
  }

  //time时间n年后的的前一天
  oneYearPast(time, n) {
    //var time=new Date();
    try {
      var year = time.getFullYear() + n;
      var d = time.setFullYear(year);
      var date = time.getDate(d) - 1;
      var xx = time.setDate(date);
      return moment(new Date(xx)).format('yyyy-MM-DD');
    }
    catch{
      return "";
    }

  }

  //计算俩日期相差多少天
  diffDays(time1, time2) {
    try {
      var m1 = moment(time1);
      var m2 = moment(time2);
      return m2.diff(m1, 'day');
    }
    catch{
      return "";
    }

  }
}
module.exports = DeliverybillCtl;

// var task = new DeliverybillCtl();
// // var d = new Date("2020-06-05");
// // console.log("dddddddddddd:" + d);
// // var oneYear = task.oneYearPast(d,1);
// // var ss = moment();
// // var diff = task.diffDays(ss,oneYear);
// // console.log(oneYear);
// // console.log(diff);
// var obj={"d":{"deliverNumber":"1111111","facilitatorId":"10","facilitatorName":"猪八戒","salesmanId":"12","salesmanName":"zhangsan","salesmanOpcode":"root/ic/zhangsan"}};
// task.updateSalesmanInfoByDeliverCode(obj,{},{}).then(d=>{
//   console.log(d);
//   //console.log(d[0].analyse);
// })
