var System = require("../../system");
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const logCtl = System.getObject("web.oplogCtl");
class orderCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(orderCtl));
    this.imgHandleApi = System.getObject("api.imghandle");
    this.cacheManager = System.getObject("db.cacheManager");
    this.accountSve = System.getObject("service.accountSve");
    this.wxSve = System.getObject("service.wxSve");
    this.tradeSve = System.getObject("service.tradeSve");
    this.userSve = System.getObject("service.userSve");
    this.appSve = System.getObject("service.appSve");
    this.trademarkSve = System.getObject("service.trademarkSve");
    this.oplogSve = System.getObject("service.oplogSve");
    this.channelreceiveSve = System.getObject("service.channelreceiveSve");
  }
  async initNewInstance(queryobj, req) {
    return System.getResult2({}, null);
  }
  async getOrderDetail(obj, req) {//订单详情
    var oid = obj.oid;
    return this.service.getOrderDetail(oid);
  }
  async getSubmitOrderDetail(obj, req) {//获取提报详情
    var orderNum = obj.orderNum;
    return this.service.getSubmitOrderDetail(orderNum);
  }
  async orderSubmit(gobj, pobj, req) {//订单开始提报
    //从订单上取出app和user
    //如果是移动端，需要从订单上取得店主onlyCode,需要修改user为店主user,
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    var appid = pobj.order.app_id;
    var uid = pobj.order.user_id;
    //pobj.shopOnlyCode，查询出
    console.log(appid + ":" + uid);
    var qapp = await this.appSve.findById(appid);
    var quser = await this.userSve.findById(uid);
    var user = await quser.get({ plain: true });
    var app = await qapp.get({ plain: true });
    var qaccount = await this.accountSve.findById(quser.account_id);
    var account = await qaccount.get({ plain: true });
    user.account = account;
    if (pobj.order.orderSourceType == "2") {
      //如果订单是小程序下单,店铺的uniqueCode去查询出account_id
      var qshopaccount = await this.accountSve.findOne({ unionId: pobj.order.shopOnlyCode });
      var shopaccount = qshopaccount.get({ plain: true });
      user.account_id = shopaccount.id;
      user.account = shopaccount;
    }
    try {
      var result = await this.service.orderSubmit(pobj, user, app);
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "订单开始提报异常",
        op: "base/controller/impl/orderCtl/orderSubmit",
        content: e.stack,
        clientIp: ""
      });
      return { code: "-2", msg: "提交失败" };
    };
  }
  async changeStatus(queryobj, pobj, req) {//订单修改状态
    try {
      var user = req.session.user;
      var app = req.session.app;
      if (user == null || user == "") {
        return { code: -100, msg: "用户登录状态有误", data: null }
      }
      if (app == null || app == "") {
        return { code: -110, msg: "用户登录状态app有误", data: null }
      }
      var r = await this.service.changeStatus(pobj);
      return r;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "订单修改状态异常",
        op: "base/controller/impl/orderCtl/changeStatus",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1 }
    }
  }
  async tsclResubmit(gobj, pobj, req) {//特殊处理_重新提交：商标列表中的特殊处理商标后的提交
    var user = req.session.user;
    var app = req.session.app;
    if (user == null || user == "") {
      return { code: -100, msg: "用户登录状态有误", data: null }
    }
    if (app == null || app == "") {
      return { code: -110, msg: "用户登录状态app有误", data: null }
    }
    try {
      var result = await this.service.tsclResubmit(pobj, user, app);
      console.log("ctl--------------------------->>>>>>>>>>>>>");
      console.log(result);
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "特殊处理_重新提交异常",
        op: "base/controller/impl/orderCtl/tsclResubmit",
        content: e.stack,
        clientIp: ""
      });
      return { code: "-200", msg: "提交失败" };
    };
  }
  // async orderRepeatSubmit(gobj,pobj,req){//订单再次提报----暂时没有调用的地方--by-sy-20190104
  //   var user=req.session.user;
  //   var app=req.session.app;
  //   try{
  //     var result=await this.service.orderRepeatSubmit(pobj,user,app);
  //     return result;
  //   }catch(e){
  //     return {code:"-2",msg:"提交失败"};
  //   };
  // }
  async pic2pdf(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": app.appid,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.bzLicenseForTMUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e);
      return System.getResult2(null, null);
    }
    // var result=await this.imgHandleApi.bzLicenseForTM(obj);
    // return result;
  }
  async adjustWTSSize(o, req) {
    var app = req.session.app;
    var obj = {
      "appKey": app.appid,
      "jpgpath": o.key
    };
    var url = settings.apiconfig.wtsUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(obj, url);
      var j = JSON.parse(rtn.stdout);
      return j;
    } catch (e) {
      console.log(e.stack, "adjustWTSSize................");
      return System.getResult2(null, null);
    }
  }
  async findOneByOrderNum(obj, req) {
    console.log("111111111111111111111111111");
    console.log(obj);
    var orderNum = obj.orderNum;
    var order = await this.service.findOneByOrderNum(orderNum);
    return order;
  }
  async orderCancel(obj, req) {
    var orderNum = obj.orderNum;
    var user = req.session.user;
    var app = req.session.app;
    try {
      var result = await this.service.orderCancel(orderNum, user, app);
      if (result != "1") {
        return { code: "-1", msg: "操作失败" };
      }
      return { code: "1", msg: "订单已取消" };;
    } catch (e) {
      return { code: "-1", msg: "操作失败" };
    }
  }
  async findByPayUserId(obj, req) {
    var payUserId = obj.payUserId;
    var orders = await this.service.findByPayUserId(payUserId);
    return orders;
  }
  async orderPay(obj, pobj, req) {
    console.log("orderPay++++++++++++++++++++++++++++++++++++++++");
    console.log(pobj);
    var result = null;
    if (pobj) {
      var order = pobj.order;
      var user = req.session.user;
      var notify_url = "http://boss.gongsibao.com/wx/pay";
      // desc,amount,notify_url,product_id,openid,scene_info,out_trade_no
      var desc = order.itemName;
      var amount = order.totalSum;
      var product_id = order.itemCode;
      var openid = user.openId;
      // var attach = JSON.stringify(user);
      var attach = user.openId + "$$$" + order.orderNum;
      console.log("attach++++++++++++++++++++++++++");
      console.log(attach);
      result = await this.wxSve.createJsUnifiedOrder(desc, amount, notify_url, product_id, openid, attach, null);

    }
    console.log("result_________________________________________________");
    console.log(result);
    return result;
  }
  async createOrderTrade(gobj, qobj, req) {
    //payResult out_trade_no orderNum payUser
    if (!qobj.payResult) {
      var out_trade_no = qobj.out_trade_no;
      var payResult = await this.wxSve.queryWxOrder(out_trade_no);
      qobj["payResult"] = payResult;
    }
    console.log("orderNum=>order if(order status =付款成功");
    console.log(qobj);
    var result = await this.service.createOrderTrade(qobj);
    return result;
    // return {};
  }
  async createOrderTrade2(qobj) {
    //payResult out_trade_no orderNum payUser
    logCtl.error({
      optitle: "createOrderTrade2微信回调测试 非错误",
      op: "createOrderTrade2",
      content: "qobj",
      clientIp: qobj.payUserOpenId
    });
    if (qobj.payUserOpenId) {
      var payUser = await this.userSve.findOne({ openId: qobj.payUserOpenId });
      qobj["payUser"] = payUser;
    }
    console.log(payUser);
    console.log("付款成功付款成功付款成功付款成功付款成功付款成功付款成功付款成功");
    console.log(qobj);
    var result = await this.service.createOrderTrade(qobj);
    console.log(result);
    return result;
    // return qobj;
  }
  async getPaidOrder(obj, req) {
    console.log("getPaidOrdergetPaidOrdergetPaidOrdergetPaidOrdergetPaidOrdergetPaidOrder");
    var orderNum = obj.orderNum;
    console.log(orderNum);
    try {
      var order = await this.service.findOneByOrderNum(orderNum);
      console.log("getPaidOrder++++++++++++++++++++++++++getPaidOrder++++++++++++");
      console.log(order.orderStatus);
      if (order.orderStatus == "4" || order.orderStatus == "32") {
        console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        return order;
      } else {
        return { msg: "fail" };
      }
    } catch (e) {
      return { msg: "err" };
    }

  }
  async orderApproval(obj, obj2, req) {
    console.log("-------------orderApproval--------------------------------");
    console.log(obj2);
    try {
      var user = req.session.user;
      var opOnlyCode = user.onlyCode;
      console.log(opOnlyCode);
      obj2["opOnlyCode"] = opOnlyCode;
      obj2["user"] = user;
      return this.service.orderApproval(obj2);
    } catch (e) {
      logCtl.error({
        optitle: "订单审核异常,orderNum=" + obj2.orderNum,
        op: "controller/impl/orderCtl/orderApproval",
        content: e.stack,
        clientIp: ""
      });
      return {
        code: -200,
        msg: "审核失败"
      };
    }
  }

  //商标自动提报 专用-------start------------------------------
  async createOrder(obj, req) {
    var user = req.session.user;
    var app = req.session.app;
    if (!user || !app) {
      return { code: "-100", msg: "用户信息有误" };
    }
    obj["user"] = user;
    obj["app"] = app;
    var tm = obj.tm || null;
    var apply = obj.apply || null;
    if (tm && tm != "undefined") {
      obj["tm"] = JSON.parse(obj.tm);
    }
    if (tm && tm != "undefined") {
      obj["apply"] = JSON.parse(obj.apply);
    }
    try {
      var result = await this.service.createOrder2(obj);
      return result;
    } catch (e) {
      console.log(e.stack, "error>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

      //日志记录
      logCtl.error({
        optitle: "订单开始提报异常",
        op: "/base/controller/impl/orderCtl/createOrder",
        content: e.stack,
        clientIp: ""
      });
      return { code: "-200", msg: "提交失败" };
    }

  };
  async orderUpdate(obj, req) {
    var user = req.session.user;
    obj["user"] = user;
    try {
      var result = await this.service.orderUpdate(obj);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }
  }

  async getOrderDetailByOrderNum(obj, req) {
    try {
      var result = await this.service.getOrderDetailByOrderNum(obj, req);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }
  }

  async getFqOrderDetailByOrderNum(obj) {
    try {
      var result = await this.service.getFqOrderDetailByOrderNum(obj);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }
  }
  async getSoftwareOrderDetailByOrderNum(obj, req) {
    try {
      var result = await this.service.getSoftwareOrderDetailByOrderNum(obj);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }
  }
  async getWorksOrderDetailByOrderNum(obj, req) {
    try {
      var result = await this.service.getWorksOrderDetailByOrderNum(obj);
      return result;
    } catch (e) {
      return { code: "-3", msg: "error" };
    }
  }
  async updateOrderDetailByOrderNum(qobj, obj, req) {
    console.log(obj);
    var user = req.session.user;
    var app = req.session.app;
    if (!user || !app) {
      return { code: "-100", msg: "用户信息有误" };
    }
    if (obj && obj.tm.orderNum && obj.apply.orderNum && obj.customer.orderNum) {
      try {
        var result = await this.service.updateOrderDetailByOrderNum(obj, user.onlyCode);
        return result;
      } catch (e) {
        console.log(e);
        return { code: "-3", msg: "error" };
      }
    } else {
      return { code: "-4", msg: "orderNum参数为空" };
    }

  }
  async createOrderTrade3(qobj) {
    logCtl.error({
      optitle: "createOrderTrade3微信回调测试 非错误",
      op: "createOrderTrade3",
      content: "qobj",
      clientIp: qobj.payUserOpenId
    });
    if (qobj.payUserOpenId) {
      var payUser = await this.userSve.findOne({ openId: qobj.payUserOpenId });
      qobj["payUser"] = payUser;
    }
    var result = await this.service.createOrderTrade2(qobj);
    console.log(result);
    return result;
  }
  //商标自动提报 专用-------end------------------------------

  //获取最后的商标订单
  async getLastTmOrder(obj, req) {
    var itemCode = obj.itemCode || "";
    var user = req.session.user;;
    if (user && user.onlyCode)
      try {
        var result = await this.service.getLastTmOrder(user.onlyCode, itemCode);
        return result;
      } catch (e) {
        return { code: "-3", msg: "error" };
      }
  }
  //return this.model.findAll({where:{proxyCode:proxyCode},order:[["id","ASC"]]});

  //商标自动提报 专用 内部提报-------start--------------------------------------------------------------------------------------------

  //获取渠道订单信息
  async getChannelOrderByOrderNum(obj, req) {
    var channelOrderNum = obj.channelOrderNum;
    var type = obj.type || "1"; //type:作用于返回参数中的订单产品余额，1：订单产品数-所有已有商标数量（新增时判断）  2：订单产品数-所有本订单号以外商标数量（修改时判断）
    var orderNum = obj.orderNum || "";
    var env = obj.env || "";
    console.log("type:作用于返回参数中的订单产品余额，1：订单产品数-所有已有商标数量（新增时判断）  2：订单产品数-所有本订单号以外商标数量");
    console.log(env);
    var resultdata = { code: 1, msg: "success", data: {} };
    //判断是beehive过来的渠道订单进行处理----sy
    var orderItem = await this.service.dao.findOne({ orderNum: orderNum });
    if (orderItem && orderItem.orderSourceType == "8") {
      resultdata.data = { remainder: 1 ,fqRemainder:1};
      return resultdata;
    }
    // var reqUrl = "http://fq" + env + "-api.gongsibao.com/openapi/order/getInfo";
    var reqUrl = "http://fq" + env + "-api.gongsibao.com/openapi/serviceOrder/getByServiceOrderNo";
    if (channelOrderNum) {
      try {
        var data = {
          "order_no": channelOrderNum
        };
        var rc = System.getObject("util.execClient");
        var rtn = await rc.execPost(data, reqUrl);
        //日志记录
        logCtl.info({
          optitle: "获取fq订单服务号信息------------------------------------------",
          op: "base/web/impl/orderCtl/getChannelOrderByOrderNum",
          content: "请求参数：url=" + reqUrl + "，order_no=" + channelOrderNum + "返回信息：" + JSON.stringify(rtn),
          clientIp: ""
        });
        var result = JSON.parse(rtn.stdout);

        if (result && result.code == 200) {
          var usable_order_no_class_count = null;//有效渠道订单列表
          var already_used_order_no_class_count=[];//已使用渠道订单列表
          if(result.data.order_no_class_count && typeof(result.data.order_no_class_count)=="object" && result.data.order_no_class_count.length>0){
            usable_order_no_class_count = result.data.order_no_class_count.slice(0);
          }
          var tmList = await this.trademarkSve.findByChannelOrderNum(channelOrderNum, type, orderNum);
          var remainder = Number(result.data.oneClassCount);
          var nclThreeCount = Number(result.data.threeClassCount);
          if (tmList) {
            if (tmList.length >= remainder) {
              resultdata.code = -3;
              resultdata.msg = "该渠道服务单号可以创建大类数量为：" + remainder + "，目前已经创建" + tmList.length + "大类，无法在进行创建";
              return resultdata;
            } else {
              remainder = remainder - tmList.length;
            }
            //处理可提报的小项
            var nclThreeCount = Number(result.data.threeClassCount);
            for (let index = 0; index < tmList.length; index++) {
              const element = tmList[index];
              if (element && element.nclSmallCodes) {
                var dbNclList = JSON.parse(element.nclSmallCodes);
                nclThreeCount = nclThreeCount - dbNclList.length;
              }
              //删除已交付订单
              if(usable_order_no_class_count && element && element.channelOrderListInfo){
                for(var i=0;i<usable_order_no_class_count.length;i++){
                  var usable_order = usable_order_no_class_count[i];
                  if(usable_order.order_no==element.channelOrderListInfo){
                    already_used_order_no_class_count.push(usable_order_no_class_count[i]);
                    usable_order_no_class_count.splice(i,1); 
                  }
                }
              }
            }
          }
          // else {
          //   return { code: -4, msg: "获取订单产品" };
          // }
          resultdata.data = result.data;
          resultdata.data["already_used_order_no_class_count"] = already_used_order_no_class_count;//已使用订单列表
          resultdata.data["usable_order_no_class_count"] = usable_order_no_class_count;//有效订单列表
          resultdata.data["remainder"] = remainder;
          resultdata.data["nclThreeCount"] = nclThreeCount;
          resultdata.data["fqRemainder"] = Number(result.data.oneClassCount);
          resultdata.data["fqNclThreeCount"] = Number(result.data.threeClassCount);
          return resultdata;
        } else {
          return { code: -1, msg: "未查到渠道订单信息，渠道服务单号：" + channelOrderNum };
        }

      } catch (e) {
        //日志记录
        logCtl.info({
          optitle: "获取fq订单服务号信息--------------异常--error----------------------------",
          op: "base/web/impl/orderCtl/getChannelOrderByOrderNum",
          content: "请求参数：url=" + reqUrl + "，order_no=" + channelOrderNum + "异常信息：" + e.stack,
          clientIp: ""
        });
        return { code: -1, msg: "查询渠道服务单异常，渠道服务单号：" + channelOrderNum };
      }
    } else {
      return { code: -5, msg: "渠道服务单channelOrderNum为空" };
    }
  }
  async getCreateOrderNum() {
    var createOrderNum = await this.getUidStr(5, 36);//====================订单号生成
    return createOrderNum + "" + Date.now();
  }
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  /**
   * 2019.11.19 修改 get=>post
   */
  async createInsideOrder(pobj, obj, req) {//峰擎内容使用
    var user = req.session.user;
    var app = req.session.app;
    var channelOrderNum = obj.channelOrderNum;
    var env = obj.env || "";
    if (!channelOrderNum) {
      return { code: "-201", msg: "channelOrderNum为空" };
    }
    if (!user || !app) {
      return { code: "-100", msg: "用户信息有误" };
    }
    var channelorder = await this.getChannelOrderByOrderNum({ channelOrderNum: channelOrderNum, env: env }, "");
    if (channelorder.code != 1) {
      return channelorder;
    }
    obj["channelorder"] = channelorder.data;
    obj["user"] = user;
    obj["app"] = app;
    var tm = obj.tm || null;
    var apply = obj.apply || null;
    if (tm && tm != "undefined") {
      if (typeof (obj.tm) == "string") {
        obj["tm"] = JSON.parse(obj.tm);
      } else {
        obj["tm"] = obj.tm;
      }

    }
    if (apply && apply != "undefined") {
      if (typeof (obj.apply) == "string") {
        obj["apply"] = JSON.parse(obj.apply);
      } else {
        obj["apply"] = obj.apply;
      }
      // obj["apply"] = JSON.parse(obj.apply);
    }
    try {
      // obj.channelCode="jd";
      var result = await this.service.createInsideOrder(obj);
      if (result.code == 1) {
        var tmList = await this.trademarkSve.findByChannelOrderNum(channelOrderNum, "1", "");
        if (tmList && tmList.length > 0) {
          for (let index = 0; index < tmList.length; index++) {
            const element = tmList[index];
            if (element && element.tmStatus == "DOCFINISH") {
              if (element && element.tmSourceType == "32") {
                element.reqOnlyCode = await this.getCreateOrderNum() + "_" + user.id;
                var aliResult = await this.trademarkSve.putAliTmStatus(element);
                if (aliResult.code != 1) {
                  if (aliResult.code == -200) {
                    var aliResult2 = await this.trademarkSve.putAliTmStatus(element);
                    if (aliResult2.code != 1) {
                      await this.trademarkSve.updateByWhere({ tmStatus: "REQALIERROR", opRemarkInfo: aliResult2.msg }, { where: { id: element.id } });
                      this.oplogSve.createDb({
                        logLevel: "error",
                        optitle: "推送阿里商标异常--阿里接口错误(需峰擎系统处理)---error",
                        op: "/fqboss/app/base/controller/impl/orderCtl.js/createInsideOrder",
                        content: "请求参数：" + JSON.stringify(element) + "，aliResult2返回结果：" + JSON.stringify(aliResult2),
                        clientIp: ""
                      });
                    }
                  }//请求阿里接口错误，需峰擎那边查找下原因
                }
              }//阿里的商标
              else {
                this.trademarkSve.putStatusById({ tmStatus: "WAITARTIFICIALEXAMINE", id: element.id });
              }//不是阿里的商标，则状态修改成等待人工审核
            }//判断是资料齐全
          }
          this.updateChannelOrderState(channelOrderNum, tmList, env);
        }
        var order = result.order;
        // if (order && order.channelCode && order.channelCode == "1688") {
        //   await this.service.pushChannelAssistTmData(order.orderNum, "1688");//推送数据
        // }
        // if (order && order.channelCode && order.channelCode == "jd") {
        //   await this.service.pushChannelAssistTmData(order.orderNum, "jd");//推送数据
        // }
        if (order && order.channelCode) {
          var judgeRes = this.trademarkSve.dao.judgeChannelCode(order.channelCode);
          if(judgeRes){
            if(order.channelCode=="gsbh5"){
              await this.channelreceiveSve.pushChannelAssistTmData(order.orderNum, order.channelCode,channelorder.data);//推送数据
            }else{
              await this.service.pushChannelAssistTmData(order.orderNum, order.channelCode);//推送数据
            }
            //await this.service.pushChannelAssistTmData(order.orderNum, order.channelCode);//推送数据
          }
          
        }
      }
      return result;
    } catch (e) {
      console.log(e.stack, "error...............订单开始提报异常---峰擎提报..........................");
      //日志记录
      logCtl.error({
        optitle: "订单开始提报异常",
        op: "/base/controller/impl/orderCtl/createInsideOrder",
        content: e.stack,
        clientIp: ""
      });
      return { code: "-200", msg: "提交失败" };
    }

  };
  async updateInsideOrderDetailByOrderNum(qobj, obj, req) {//峰擎内部使用
    console.log(obj);
    var channelOrderNum = obj.channelOrderNum;
    if (!channelOrderNum) {
      return { code: "-201", msg: "channelOrderNum为空" };
    }
    var user = req.session.user;
    var app = req.session.app;
    var env = obj.env || "";
    if (!user || !app) {
      return { code: "-100", msg: "用户信息有误" };
    }
    obj["user"] = user;
    obj["app"] = app;
    if (obj && obj.tm.orderNum && obj.apply.orderNum && obj.customer.orderNum) {
      try {
        var channelorder = await this.getChannelOrderByOrderNum({ channelOrderNum: channelOrderNum, type: "2", orderNum: obj.tm.orderNum, env: env }, "");
        if (channelorder.code != 1) {
          return channelorder;
        }
        obj["channelorder"] = channelorder.data;
        var result = await this.service.updateInsideOrderDetailByOrderNum(obj, user.onlyCode);
        if (result.code == 1) {
          var tmList = await this.trademarkSve.findByChannelOrderNum(channelOrderNum, "1", "");
          if (tmList && tmList.length > 0) {
            for (let index = 0; index < tmList.length; index++) {
              const element = tmList[index];
              if (element && (element.tmStatus == "SUBALITMOK" || element.tmStatus == "DOCFINISH")) {
                if (element && element.tmSourceType == "32") {
                  element.reqOnlyCode = await this.getCreateOrderNum() + "_" + user.id;
                  var aliResult = await this.trademarkSve.putAliTmStatus(element);
                  if (aliResult.code != 1) {
                    if (aliResult.code == -200) {
                      var aliResult2 = await this.trademarkSve.putAliTmStatus(element);
                      if (aliResult2.code != 1) {
                        await this.trademarkSve.updateByWhere({ tmStatus: "REQALIERROR", opRemarkInfo: aliResult2.msg }, { where: { id: element.id } });
                        this.oplogSve.createDb({
                          logLevel: "error",
                          optitle: "推送阿里商标异常--阿里接口错误(需峰擎系统处理)---error",
                          op: "/fqboss/app/base/controller/impl/orderCtl.js/createInsideOrder",
                          content: "请求参数：" + JSON.stringify(element) + "，aliResult2返回结果：" + JSON.stringify(aliResult2),
                          clientIp: ""
                        });
                      }
                    }//请求阿里接口错误，需峰擎那边查找下原因
                  }
                }//阿里的商标
              }//判断是已补全信息(待确认商标)
            }
            this.updateChannelOrderState(channelOrderNum, tmList, env);
          }
          var order = await this.service.dao.findOne({ orderNum: obj.tm.orderNum });
          // if (order && order.channelCode && order.channelCode == "1688") {
          //   await this.service.pushEditChannelAssistTmData(order.orderNum, "1688");//推送修改数据
          // }
          // if (order && order.channelCode && order.channelCode == "jd") {
          //   await this.service.pushEditChannelAssistTmData(order.orderNum, "jd");//推送修改数据
          // }
          if (order && order.channelCode) {
            var judgeRes = this.trademarkSve.dao.judgeChannelCode(order.channelCode);
            if(judgeRes){
              if(order.channelCode=="gsbh5"){
                await this.channelreceiveSve.pushEditChannelAssistTmData(order.orderNum, order.channelCode,channelorder.data);//推送修改数据
              }else{
                await this.service.pushEditChannelAssistTmData(order.orderNum, order.channelCode);//推送修改数据
              }
              // await this.service.pushEditChannelAssistTmData(order.orderNum, order.channelCode);//推送修改数据
            }
            
          }
        }
        return result;
      } catch (e) {
        console.log(e);
        logCtl.error({
          optitle: "修改渠道商标信息异常...........error",
          op: "/base/controller/impl/orderCtl/updateInsideOrderDetailByOrderNum",
          content: e.stack,
          clientIp: ""
        });
        return { code: "-3", msg: "error" };
      }
    } else {
      return { code: "-4", msg: "orderNum参数为空" };
    }
  };

  async updateInsideOrderDetailByOrderNum2(qobj, obj, req) {
    console.log(obj);
    var channelOrderNum = obj.channelOrderNum;
    if (!channelOrderNum) {
      return { code: "-201", msg: "channelOrderNum为空" };
    }
    var user = req.session.user;
    var app = req.session.app;
    var env = obj.env || "";
    if (!user || !app) {
      return { code: "-100", msg: "用户信息有误" };
    }
    obj["user"] = user;
    obj["app"] = app;
    if (obj && obj.tm.orderNum && obj.apply.orderNum && obj.customer.orderNum) {
      try {
        var channelorder = await this.getChannelOrderByOrderNum({ channelOrderNum: channelOrderNum, type: "2", orderNum: obj.tm.orderNum, env: env }, "");
        if (channelorder.code != 1) {
          return channelorder;
        }
        obj["channelorder"] = channelorder.data;
        var result = await this.service.updateInsideOrderDetailByOrderNum2(obj, user.onlyCode);
        if (result.code == 1) {
          var tmList = await this.trademarkSve.findByChannelOrderNum(channelOrderNum, "1", "");
          if (tmList && tmList.length == Number(channelorder.data.oneClassCount)) {
            this.updateChannelOrderState(channelOrderNum, "已完成", env);
          }
        }
        return result;
      } catch (e) {
        console.log(e);
        logCtl.error({
          optitle: "修改渠道商标信息异常...........error",
          op: "/base/controller/impl/orderCtl/updateInsideOrderDetailByOrderNum2",
          content: e.stack,
          clientIp: ""
        });
        return { code: "-3", msg: "error" };
      }
    } else {
      return { code: "-4", msg: "orderNum参数为空" };
    }
  };

  //更新渠道订单状态（峰擎系统内部）
  async updateChannelOrderState(channelOrderNum, tmList, env) {
    try {
      var tm_data = [];
      for (let k = 0; k < tmList.length; k++) {
        const tminfo = tmList[k];
        if (tminfo) {
          tm_data.push({
            tm_name: tminfo.tmName,
            ncl_onecode: tminfo.nclOneCodes
          });
        }
      }
      var reqUrl = "http://fq" + env + "-api.gongsibao.com/openapi/serviceOrder/updateCreateCaseState";
      var rc = System.getObject("util.execClient");
      var rtn = await rc.execPost({ order_no: channelOrderNum, tm_count: tmList.length, tm_data: tm_data }, reqUrl);
      // var rtn = await rc.execPost({ order_no: channelOrderNum }, reqUrl);
      var result = JSON.parse(rtn.stdout);
      if (result && result.code == 200) {
        return { code: 1, msg: "success" };
      } else {
        return { code: -1, msg: "err" };
      }
    } catch (e) {
      logCtl.error({
        optitle: "更新渠道订单状态异常.....峰擎云......error",
        op: "/base/controller/impl/orderCtl/updateChannelOrderState",
        content: e.stack,
        clientIp: ""
      });
    }
    // if (channelOrderNum) {
    //   if (!orderState) {
    //     return { code: -6, msg: "orderState为空" };
    //   }
    //   try {
    //     var reqUrl = "http://fq" + env + "-api.gongsibao.com/openapi/order/getInfo";
    //     //orderState:待办理,办理中,已废弃,已完成
    //     var data = {
    //       "order_no": channelOrderNum,
    //       "order_state": orderState
    //     };
    //     var rc = System.getObject("util.execClient");
    //     var rtn = await rc.execPost(data, reqUrl);
    //     var result = JSON.parse(rtn.stdout);
    //     if (result && result.code == 200) {
    //       var resultdata = result.data;
    //       return { code: 1, msg: "success" };
    //     } else {
    //       return { code: -1, msg: "err" };
    //     }

    //   } catch (error) {
    //     console.log(error);
    //     logCtl.error({
    //       optitle: "修改公司宝渠道订单异常",
    //       op: "base/controller/impl/orderCtl/updateChannelOrderState",
    //       content: error.stack,
    //       clientIp: ""
    //     });
    //     return { code: -1, msg: "err" };
    //   }
    // } else {
    //   return { code: -5, msg: "channelOrderNum为空" };
    // }
  }
  //获取客户档案（根据公司名称，查询公司信息）
  async getCustomerInfoByCompanyName(obj, req) {
    try {
      return this.service.getCustomerInfoByCompanyName(obj);
    } catch (error) {
      return { code: -200, msg: "操作失败" }
    }
  }

  //商标自动提报 专用 内部提报-------end----------------------------------------------------------------------------------------------
}
module.exports = orderCtl;
