const system = require("../../system");
const ServiceBase = require("../sve.base")
const settings = require("../../../config/settings")
const logCtl = system.getObject("web.oplogCtl");
class TradeMarkService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(TradeMarkService));
    this.orderDao = system.getObject("db.orderDao");
    this.companyDao = system.getObject("db.companyDao");
    this.tmstuffDao = system.getObject("db.tmstuffDao");
    this.trademarkDao = system.getObject("db.trademarkDao");
    this.orderflowDao = system.getObject("db.orderflowDao");
    this.expensevoucherDao = system.getObject("db.expensevoucherDao");//费用单
    this.moneyjourneyDao = system.getObject("db.moneyjourneyDao");//账单
    this.receiptvoucherDao = system.getObject("db.receiptvoucherDao");//收款单
    this.moneyaccountDao = system.getObject("db.moneyaccountDao");
    this.oplogDao = system.getObject("db.oplogDao");
    this.pushmsgWxop = system.getObject("wxop.pushmsgWxop");
    this.mailClient = system.getObject("util.mailClient");
  }
  //获取提包的缓存key
  async getTbCacheKey(key) {
    return "tbKey_" + key;
  }
  async getTbCacheKeyKeyAllotData(key) {
    return "tbKeyAllotData_" + key;
  }

  //处理官费提交----------------------------------------------------------------------------开始
  async disposePublicExpense() {
    var sql = "SELECT a.id AS orderId,a.company_id,a.createuser_id,a.`code` AS orderNum,b.nclPublicExpense,a.subType FROM biz_order AS a," +
      " (SELECT sourceOrderNo, SUM(nclPublicExpense) AS nclPublicExpense FROM `biz_trademark`" +
      " WHERE `deleted_at` IS NULL AND `tmRegistNum` IS NOT NULL AND payPublicExpense=0 GROUP BY `sourceOrderNo`) AS b" +
      " WHERE a.`code` = b.sourceOrderNo";
    var tmList = await this.dao.customQuery(sql);
    if (!tmList || tmList.length == 0) {
      return { code: -100, msg: "暂无要处理商标官费" }
    }
    var expensevoucherList = [];//费用
    var moneyjourneyList = [];//账单      
    var opMoneyList = [];
    var opTmSourceOrderNoList = [];
    var self = this;
    for (let index = 0; index < tmList.length; index++) {
      const element = tmList[index];
      if (element) {
        await self.assembleOpArray(self, expensevoucherList, moneyjourneyList, opMoneyList, opTmSourceOrderNoList, element);
        if (expensevoucherList.length == 500 && moneyjourneyList.length == 500) {
          this.db.transaction(async function (t) {
            await self.execDbOp(self, expensevoucherList, moneyjourneyList, opMoneyList, opTmSourceOrderNoList, t);
          });
          expensevoucherList = [];
          moneyjourneyList = [];
          opMoneyList = [];
        }
      }
    }
    this.db.transaction(async function (t) {
      await self.execDbOp(self, expensevoucherList, moneyjourneyList, opMoneyList, opTmSourceOrderNoList, t);
    });
  }

  async assembleOpArray(self, expensevoucherList, moneyjourneyList, opMoneyList, opTmSourceOrderNoList, element) {
    var receiptvoucherItem = await self.receiptvoucherDao.model.findOne({
      where: { sourceOrderNo: element.orderNum, sourceType: "order", payFlowType: 1 },
      attributes: ["id", "totalSum"],
      include: [
        {
          model: self.moneyaccountDao.db.models.moneyaccount,
          attributes: ["id", "accountType", "code", "name", "balance", "company_id"],
          raw: true
        }
      ]
    });
    if (!receiptvoucherItem || !receiptvoucherItem.moneyaccount) {
      //日志记录
      await self.oplogDao.create({
        company_id: element.company_id,
        user_id: element.createuser_id,
        sourceOrderNo: orderItem.orderNum,
        op: "/service/impl/utilscloudSve.js/assembleOpArray",
        opTitle: nowTimeStr + "系统官费扣除组装错误=>error",
        logLevel: "info",
        content: !receiptvoucherItem ? (orderItem.orderNum + "的订单号对应的收款单信息为空，") : (orderItem.orderNum + "的订单号对应收款单的公司资金帐户信息为空，") + "无法进行官费扣除",
        opLogType: "publicExpense",
        opLogStatus: "fail",
      });
      return;
    }
    var isCheckMoney = 0;//验证余额是否够用
    if (Number(receiptvoucherItem.moneyaccount.balance) < Number(element.nclPublicExpense) || Number(receiptvoucherItem.totalSum) < Number(element.nclPublicExpense)) {
      isCheckMoney = 1;
    }
    //处理帐户
    var tmpfindIndex = opMoneyList.length > 0 ? opMoneyList.findIndex(f => f.id == receiptvoucherItem.moneyaccount.id) : -1;
    var tmpBalance = Number(receiptvoucherItem.moneyaccount.balance) - Number(element.nclPublicExpense);
    if (tmpBalance < 0) {
      isCheckMoney = 1;
    } else {
      receiptvoucherItem.moneyaccount.balance = tmpBalance.toFixed(2);
      if (tmpfindIndex < 0) {
        opMoneyList.push({
          id: receiptvoucherItem.moneyaccount.id,
          balance: tmpBalance.toFixed(2)
        });
      } else {
        opMoneyList[tmpfindIndex].balance = tmpBalance.toFixed(2);
      }
    }
    if (isCheckMoney > 0) {
      //日志记录
      await self.oplogDao.create({
        company_id: element.company_id,
        user_id: element.createuser_id,
        sourceOrderNo: orderItem.orderNum,
        op: "/service/impl/utilscloudSve.js/assembleOpArray",
        opTitle: nowTimeStr + "系统官费扣除错误，对应的帐户余额不足=>error",
        logLevel: "info",
        content: "下单订单收款总额：" + receiptvoucherItem.totalSum +
          "，帐户余额：" + receiptvoucherItem.moneyaccount.balance +
          "，将要扣除的官费额度：" + element.nclPublicExpense +
          "，帐户信息：" + JSON.stringify(receiptvoucherItem),
        opLogType: "publicExpense",
        opLogStatus: "fail",
      });
      return;
    }
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    var gfCode = await self.getBusUid("gf");
    expensevoucherList.push({
      company_id: receiptvoucherItem.moneyaccount.company_id,//公司id
      createuser_id: element.createuser_id,
      code: gfCode,
      sourceType: "trademark",
      sourceOrderNo: element.orderNum,
      expenseType: "gf",
      totalSum: element.nclPublicExpense,
      auditStatus: "tg",
      notes: nowTimeStr + "：系统官费扣除",
      moneyaccount_id: receiptvoucherItem.moneyaccount.id
    });

    moneyjourneyList.push({
      company_id: receiptvoucherItem.moneyaccount.company_id,//公司id
      createuser_id: element.createuser_id,//第三方公司订单创建者
      code: gfCode,
      accountType: receiptvoucherItem.moneyaccount.accountType,
      directionType: "zc",//凭单类型,"sr": "收","zc": "支"
      voucherDate: new Date(),
      recvAmount: element.nclPublicExpense,
      sourceType: "expensevoucher",
      sourceOrderNo: element.orderNum,
      auditStatus: "tg",
      notes: nowTimeStr + "：系统官费扣除",
      moneyaccount_id: receiptvoucherItem.moneyaccount.id
    });
    opTmSourceOrderNoList.push(element.orderNum);
  }

  async execDbOp(self, expensevoucherList, moneyjourneyList, opMoneyList, opTmSourceOrderNoList, t) {
    if (expensevoucherList.length > 0) {
      await self.expensevoucherDao.bulkCreate(expensevoucherList, t);
    }
    if (moneyjourneyList.length > 0) {
      await self.moneyjourneyDao.bulkCreate(moneyjourneyList, t);
    }
    if (opMoneyList.length > 0) {
      // await self.moneyaccountDao.bulkCreate(opMoneyList, { updateOnDuplicate: ["id"] }, t);
      for (let j = 0; j < opMoneyList.length; j++) {
        const tItem = opMoneyList[j];
        if (tItem) {
          await self.moneyaccountDao.updateByWhere({ balance: tItem.balance }, { where: { id: tItem.id } }, t);
        }
      }
    }
    if (opTmSourceOrderNoList.length > 0) {
      await self.updateByWhere({ payPublicExpense: 1 }, { where: { sourceOrderNo: { [self.dao.db.Op.in]: opTmSourceOrderNoList }, payPublicExpense: 0 } }, t);
    }
  }

  //处理官费提交----------------------------------------------------------------------------结束

  //获取提报数据缓存处理----------------------------------------------------------------------开始
  async getAutoSubList(code_list, code_item) {
    //通过数据key获取数据
    var datakey = await this.getTbCacheKey(code_item.code);
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(datakey);
    if (tbDataList && tbDataList != "undefined" && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      if (tmpResult.length == 0) {
        await this.cacheManager["TmSubCache"].delCache(datakey);
      } else {
        return { code: 200, message: "获取数据成功！", data: tmpResult };
      }
    }
    // 组合查询要提报的订单数据条件
    // orderStatus   //订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"   
    // orderFlowStatus: {//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成" 
    // orderPayStatus: {//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    // sveItemType:服务项目类型:"ip": "商标", "ic": "版权", "pa": "专利", "iso": "海外业务", "common": "增值服务", "icbc": "工商注册","zscq": "知识产权", "cwfw": "财务服务", "hyzz": "行业资质", "gqzr": "股权转让", "xzsp": "行政审批"
    //sveItemCode=zzsbzc（自主商标注册）、dlrfzzc（dlrfzzc）

    var sqlWhere = {
      [this.db.Op.and]: [{ company_id: code_item.company.id }, { orderStatus: "5" }, { orderFlowStatus: "3" },
      { orderPayStatus: "yfk" }, { sveItemType: "ip" }, { subType: "self" }],
      [this.db.Op.or]: [{ sveItemCode: "zzsbzc" }, { sveItemCode: "dlrfzzc" }]
    };
    //公司ID为1为平台进行提报
    if (code_item.company.id == 1) {
      sqlWhere = {
        [this.db.Op.and]: [{ orderStatus: "5" }, { orderFlowStatus: "3" }, { orderPayStatus: "yfk" }, { sveItemType: "ip" }, { subType: "platform" }],
        [this.db.Op.or]: [{ sveItemCode: "zzsbzc" }, { sveItemCode: "dlrfzzc" }]
      };
    }
    //通过缓存中key的分页数据获取提报数据
    var allotKeyData = await this.getTbCacheKeyKeyAllotData(code_item.code);
    var allotDataOne = await this.cacheManager["TmSubCache"].getTmSubListByCache(allotKeyData);
    if (allotDataOne && allotDataOne.length > 0) {
      var tmpAllotDataOne = JSON.parse(allotDataOne);
      return await this.getTmSubData(datakey, tmpAllotDataOne.pageSize, tmpAllotDataOne.from, sqlWhere, code_item);
    }
    //设置多key的分页缓存数据
    var ttReult = await this.setAllotKey(code_list, code_item, sqlWhere);
    if (ttReult.code != 1) {
      return ttReult;
    }
    //通过缓存中key的分页数据获取提报数据
    var allotDataTwo = await this.cacheManager["TmSubCache"].getTmSubListByCache(allotKeyData);
    if (allotDataTwo && allotDataTwo.length > 0) {
      var tmpAllotDataTwo = JSON.parse(allotDataTwo);
      return await this.getTmSubData(datakey, tmpAllotDataTwo.pageSize, tmpAllotDataTwo.from, sqlWhere, code_item);
    }
    return { code: -204, message: "key分页数据有误", data: [] };
  }
  //设置多key的分页缓存数据-本类中getAutoSubList方法用
  async setAllotKey(code_list, code_item, sqlWhere) {
    //keyTotal=key总数 //currentKey=当前key（第几个）//keyCode=key码
    var dataCount = await this.orderDao.findCount(sqlWhere);
    if (dataCount == 0) {
      return { code: 200, message: "目前没有待提报的商标数据", data: [] };
    }
    var sameCompanyCodeList = code_list.filter(f => f.company_id == code_item.company.id);
    var keyTotal = sameCompanyCodeList.length;
    //分配每个key的分页数据信息
    var tPageSize = keyTotal == 1 ? Number(dataCount) : Number(dataCount / keyTotal);
    if (tPageSize > 300) {
      tPageSize = 300;
    }
    for (var i = 0; i < keyTotal; i++) {
      var tmpCodeItem = code_list[i];
      var tmpAllotKeyData = await this.getTbCacheKeyKeyAllotData(tmpCodeItem.code);
      var allotResult = { pageSize: parseInt(tPageSize), from: i + 1 };
      //删除已经存在的key
      await this.cacheManager["TmSubCache"].delCache(tmpAllotKeyData);
      //设置缓存
      var allotStr = JSON.stringify(allotResult);
      await this.cacheManager["TmSubCache"].setTmSubList(tmpAllotKeyData, allotStr);
    }
    return { code: 1, message: "ok!", data: [] };
  }
  //获取提报数据缓存处理----------------------------------------------------------------------结束

  //组装提报数据-----------------------------------------------------------------------------开始
  async getTmSubData(datakey, pageSize, from, sqlWhere, code_item) { //获取提报商标数据-供本类中getAutoSubList方法用
    var sqlOrderby = [["created_at", 'desc']];
    var attributesObj = ["id", "code", "name", "contacts", "mobile", "email", "tel", "fax", "zipCode", "notes"];
    var includeObj = [{
      model: this.dao.db.models.customerinfo, attributes: ["id", "code", "name", "applyAddr", "customerType", "businessLicensePic",
        "identityCardPic", "identityCardNo"]
    }];
    var orderList = await this.orderDao.getPageList(from, pageSize, sqlWhere, sqlOrderby, attributesObj, includeObj);
    var result = { code: 200, message: "获取数据成功！", data: [] };
    try {
      for (let i = 0; i < orderList.rows.length; i++) {
        var tmpItem = await orderList.rows[i];
        if (tmpItem && tmpItem.customerinfo) {
          await this.setTbItem(tmpItem, result.data, code_item);
        }
      }
      if (result.data && result.data.length == 0) {
        result.data = await this.getErrorCountSubData(from, pageSize, sqlOrderby, attributesObj, includeObj, code_item);
      }
      if (!result.data || result.data.length == 0) {

        return { code: 200, message: "目前没有待提报的商标数据!!", data: [] };
      }
    } catch (e) {
      console.log(e.stack, "获取提报订单组装数据据异常error：");
      //日志记录
      logCtl.error({
        optitle: "获取提报订单组装数据异常error",
        op: "service/impl/trademarkSve.js/getTmSubData",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "getTmSubData组装数据异常"
      result.data = [];
      return result;
    }
    //设置缓存
    var stringStr = JSON.stringify(result.data);
    await this.cacheManager["TmSubCache"].setTmSubList(datakey, stringStr);
    return result;
  }
  async getErrorCountSubData(from, pageSize, sqlOrderby, attributesObj, includeObj, code_item) {//获取提报异常商标数据-供本类中getTmSubData方法用
    //获取提报错误的数据再次提报
    var sqlWhere = {
      [this.db.Op.and]: [{ company_id: code_item.company.id }, { orderStatus: "6" },
      { orderPayStatus: "yfk" }, { sveItemType: "ip" }, { subType: "self" }],
      [this.db.Op.or]: [{ sveItemCode: "zzsbzc" }, { sveItemCode: "dlrfzzc" }]
    };
    //公司ID为1为平台进行提报
    if (code_item.company.id == 1) {
      sqlWhere = {
        [this.db.Op.and]: [{ orderStatus: "6" }, { orderPayStatus: "yfk" }, { sveItemType: "ip" }, { subType: "platform" }],
        [this.db.Op.or]: [{ sveItemCode: "zzsbzc" }, { sveItemCode: "dlrfzzc" }]
      };
    }
    var orderList = await this.orderDao.getPageList(from, pageSize, sqlWhere, sqlOrderby, attributesObj, includeObj);
    var subData = [];
    for (let i = 0; i < orderList.rows.length; i++) {
      var tmpItem = await orderList.rows[i];
      if (tmpItem && tmpItem.customerinfo) {
        await this.setTbItem(tmpItem, subData, code_item);
      }
    }
    return subData;
  }
  async setTbItem(obj, resultData, code_item) {  //获取提报数据-供本类中getAutoSubList方法用
    var self = this;
    var tmList = await self.dao.model.findAll({
      where: { sourceOrderNo: obj.code, tbErrorCount: { [self.db.Op.ne]: [0] } },
      attributes: ["id", "tmType", "tmFormType", "nclOneCodes", "nclSmallCodes", "code", "name"]
    });
    if (!tmList || tmList.length == 0) {
      return;
    }
    var tmstuffList = await self.tmstuffDao.model.findAll({
      where: { code: obj.code },
      attributes: ["id", "stuffType", "stuffUrl"]
    });
    if (!tmstuffList || tmstuffList.length == 0) {
      return;
    }
    // "csty": "彩色图样", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
    var ty = tmstuffList.filter(f => f.stuffType == "ty");
    var tyItem = ty && ty.length > 0 ? ty[0] : null;

    var csty = tmstuffList.filter(f => f.stuffType == "csty");
    var cstyItem = csty && csty.length > 0 ? csty[0] : null;

    var gzwts = tmstuffList.filter(f => f.stuffType == "gzwts");
    var gzwtsItem = gzwts && gzwts.length > 0 ? gzwts[0] : null;

    var sywj = tmstuffList.filter(f => f.stuffType == "sywj");
    var sywjItem = sywj && sywj.length > 0 ? sywj[0] : null;

    var smwj = tmstuffList.filter(f => f.stuffType == "smwj");
    var smwjItem = smwj && smwj.length > 0 ? smwj[0] : null;

    for (let index = 0; index < tmList.length; index++) {
      const element = tmList[index];
      if (!element) {
        continue;
      }
      var params = {
        "status": "",
        "errorCount": 0,
        //申请人手机号--订单联系人
        "mobile": obj.mobile == null ? "" : obj.mobile,//用于后边的盯盯通知或微信通知,目前暂时没有用到
        "msg": "",
        //--代理号
        "corpTrademarkId": element.code,
        "step1": null,
        "step2": null,
        "step3": null,
        "step4": null,
        "step5": null,
        "step6": null,
        "step7": null
      };
      params.step1 = {
        "appTypeId": obj.customerinfo.customerType == 'ent' ? "法人或其它组织" : "自然人",
        "appGjdq": "中国大陆"
      };

      params.step2 = {
        //代理号
        "agentFilenum": element.code,
        //代理人=XXX公司（提报key中已写死）+XXX公司的负责人，所以这个为XXX公司的负责人
        "agentPerson": code_item.company.agentPerson,//
        //盖章后的代理委托书
        "agentBookPath": gzwtsItem == null || !gzwtsItem.stuffUrl ? "" : gzwtsItem.stuffUrl,
        "agentBookName": gzwtsItem == null || !gzwtsItem.stuffUrl ? "" : gzwtsItem.stuffUrl.substring(gzwtsItem.stuffUrl.lastIndexOf('/') + 1),
        //申请人信用代码
        "certCode": obj.customerinfo.code || "",
        //申请人名称
        "appCnName": obj.customerinfo.name || "",
        //申请人地址
        "appCnAddr": obj.customerinfo.applyAddr || "",
        //申请人联系人
        "appContactPerson": code_item.company.contact,
        //申请人联系人电话
        "appContactTel": code_item.company.contactmobile,
        //申请人联系人邮编
        "appContactZip": obj.zipCode,
        //申请人联系人传真
        "appContactFax": obj.fax || "",
        //申请人营业执照附件
        "certFilePath": obj.customerinfo.businessLicensePic || "",
        "certFileName": !obj.customerinfo.businessLicensePic ? "" : obj.customerinfo.businessLicensePic.substring(obj.customerinfo.businessLicensePic.lastIndexOf('/') + 1),
        //自然人—>证件名称--身份证,护照，其他====>目前只有身份证
        "appCertificateId": obj.customerinfo.customerType != 'person' ? "" : "身份证",
        //自然人—>证件号
        "appCertificateNum": obj.customerinfo.customerType != 'person' ? "" : obj.customerinfo.identityCardNo || "",
        //自然人--->证件文件路径
        "appCertFilePath": obj.customerinfo.customerType != 'person' ? "" : obj.customerinfo.identityCardPic || "",
        "appCertFileName": obj.customerinfo.customerType != 'person' ? "" : !obj.customerinfo.identityCardPic ? "" : obj.customerinfo.identityCardPic.substring(obj.customerinfo.identityCardPic.lastIndexOf('/') + 1),
      };
      //商标类型形式：1立体、2声音、3文字、4图形、5文字及图形、6颜色组合、7彩色
      params.step3 = {
        //商标类型：tmType1=一般，tmType2=集体，tmType3=证明，用默认tmType1
        "tmType": "tmType1",
        //是否三维标志-商标类型为立体
        "ifSolidTm": element.tmFormType == '1' ? "ifSolidTm" : "ifSolidTm1",
        //是否颜色组合
        "colourSign": element.tmFormType == '6' ? "colourSign2" : "colourSign1",
        //声音商标
        "tmFormType": element.tmFormType == '2' ? "true" : "false",
        //声音文件的全URL
        "tmFormTypeFilePath": element.tmFormType != '2' ? "" : sywjItem == null || !sywjItem.stuffUrl ? "" : sywjItem.stuffUrl,
        "tmFormTypeFileName": element.tmFormType != '2' ? "" : sywjItem == null || !sywjItem.stuffUrl ? "" : sywjItem.stuffUrl.substring(sywjItem.stuffUrl.lastIndexOf('/') + 1),
        //商标说明-商标名称
        "tmDesignDeclare": element.name
      };

      params.step4 = {
        //否共同申请，默认否，ifShareTm1=否，ifShareTm=是，用默认ifShareTm1
        "ifShareTm": "ifShareTm1"
      };

      params.step5 = {
        //优先权声明，priorityType1=无，priorityType2=在先优先权，priorityType3展会优先权，用默认priorityType1
        "priorityType": "priorityType1"
      };

      params.step6 = await this.setNewNclData(element.nclOneCodes, element.nclSmallCodes);

      params.step7 = {
        //图样URL
        "picPath": element.tmFormType != '7' ?
          tyItem == null || !tyItem.stuffUrl ? "" : tyItem.stuffUrl :
          cstyItem == null || !cstyItem.stuffUrl ? "" : cstyItem.stuffUrl,
        "picName": element.tmFormType != '7' ?
          tyItem == null || !tyItem.stuffUrl ? "" : tyItem.stuffUrl.substring(tyItem.stuffUrl.lastIndexOf('/') + 1) :
          cstyItem == null || !cstyItem.stuffUrl ? "" : cstyItem.stuffUrl.substring(cstyItem.stuffUrl.lastIndexOf('/') + 1),
        //黑白稿，这个表示填报页面的黑白按钮是否启用,,true是黑白商标，false彩色商标---->商标类型为7彩色则为false，则blackPath、blackName两个有值
        "isBlack": element.tmFormType != '7' ? "true" : "false",
        "blackPath": element.tmFormType != '7' ? "" : tyItem == null || !tyItem.stuffUrl ? "" : tyItem.stuffUrl,
        "blackName": element.tmFormType != '7' ? "" : tyItem == null || !tyItem.stuffUrl ? "" : tyItem.stuffUrl.substring(tyItem.stuffUrl.lastIndexOf('/') + 1),
        //是否肖像商标
        "isPersonPhoto": "false",
        //肖像商标url
        "personPhotoPath": "",
        "personPhotoName": "",
        //说明文件url
        "commentPath": smwjItem == null || !smwjItem.stuffUrl ? "" : smwjItem.stuffUrl,
        "commentName": smwjItem == null || !smwjItem.stuffUrl ? "" : smwjItem.stuffUrl.substring(smwjItem.stuffUrl.lastIndexOf('/') + 1),
      };
      resultData.push(params);
    }
  }
  //设置尼斯大类及二类-本类中getAutoSubList方法用
  async setNewNclData(tmpNclOneCodes, tmpNclSmallCodes) {
    var nclParams = {
      "goods": []
    };
    var nclInfo = JSON.parse(tmpNclSmallCodes);
    if (nclInfo.length <= 0) {
      return nclParams;
    }
    var hash = {};
    const newArr = nclInfo.reduceRight((item, next) => {
      hash[next.pcode] ? '' : hash[next.pcode] = true && item.push(next);
      return item
    }, []);
    //去重后的数据二级类
    for (let i = 0; i < newArr.length; i++) {
      var tItem = newArr[i];
      if (tItem != null) {
        var tParams = {
          "classes": tmpNclOneCodes,
          "group": tItem.pcode,
          "nameList": await this.setNclThree(tItem.pcode, nclInfo)
        };
        nclParams.goods.push(tParams);
      }
    }
    return nclParams;
  }

  //设置尼斯小类-本类中getAutoSubList方法用
  async setNclThree(pcode, nclthreeList) {
    var newArr = nclthreeList.filter(function (item) {
      return item.pcode == pcode;
    })
    var rtnArr = [];
    if (newArr.length <= 0) {
      return rtnArr;
    }
    for (let i = 0; i < newArr.length; i++) {
      var tNewItem = newArr[i];
      if (tNewItem != null) {
        rtnArr.push(tNewItem.name);
      }
    }
    return rtnArr;
  }
  //组装提报数据-----------------------------------------------------------------------------结束

  async setUpdateErrorCount(proxyCode, errorCount, code) {//更缓存中新提报错误次数-api用--暂时不用此方法
    var key = await this.getTbCacheKey(code);
    //处理缓存
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(key);
    if (tbDataList && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      if (tmpResult && tmpResult.length > 0) {
        tmpResult.filter(function (ele) {
          if (ele.corpTrademarkId == proxyCode) {
            ele.errorCount = errorCount;
          }
        });
        //设置缓存
        var stringStr = JSON.stringify(tmpResult);
        await this.cacheManager["TmSubCache"].setTmSubList(key, stringStr);
      }
    }
    return { code: 200, message: "操作成功", data: null };
  }

  async updateTmCache(proxyCode, code) {//更新商标缓存信息-api用
    var key = await this.getTbCacheKey(code);
    var errorCount = 0;
    //处理缓存
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(key);
    if (tbDataList && tbDataList != "" && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      if (tmpResult && tmpResult.length > 0) {
        //移除整个缓存
        if (tmpResult.length == 1) {
          var allotKeyData = await this.getTbCacheKeyKeyAllotData(code);
          this.cacheManager["TmSubCache"].delCache(key);
          this.cacheManager["TmSubCache"].delCache(allotKeyData);
        }
        else {
          //移除单个数据
          tmpResult.splice(tmpResult.findIndex(v => v.corpTrademarkId === proxyCode), 1);
          //设置缓存
          var stringStr = JSON.stringify(tmpResult);
          await this.cacheManager["TmSubCache"].setTmSubList(key, stringStr);
        }
      }
    }
    return { code: 200, message: "操作成功", data: null };
    // return await this.subPutDb(proxyCode, stateCode, "ROBOT", "7", "4", "6", "2", errorMsg, "");
  }
  async setUpdateState(proxyCode, errorCount, stateCode, code, errorMsg) {//更新商标状态-api用
    // var key = await this.getTbCacheKey(code);
    // var errorCount = 0;
    // //处理缓存
    // var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(key);
    // if (tbDataList && tbDataList != "" && tbDataList.length > 0) {
    //   var tmpResult = JSON.parse(tbDataList);
    //   if (tmpResult && tmpResult.length > 0) {
    //     //移除整个缓存
    //     if (tmpResult.length == 1) {
    //       var allotKeyData = await this.getTbCacheKeyKeyAllotData(code);
    //       this.cacheManager["TmSubCache"].delCache(key);
    //       this.cacheManager["TmSubCache"].delCache(allotKeyData);
    //     }
    //     else {
    //       //移除单个数据
    //       tmpResult.splice(tmpResult.findIndex(v => v.corpTrademarkId === proxyCode), 1);
    //       //设置缓存
    //       var stringStr = JSON.stringify(tmpResult);
    //       await this.cacheManager["TmSubCache"].setTmSubList(key, stringStr);
    //     }
    //   }
    // }
    return await this.subPutDb(proxyCode, stateCode, "ROBOT", "7", "4", "6", "2", errorMsg, "");
  }
  async setUpdateTradeMarkCode(proxyCode, regCode, stateCode) {  //更新商标注册号和状态-api用
    return await this.subPutDb(proxyCode, stateCode, "RECVCOMMIT", "7", "5", "6", "2", "", regCode);
  }
  // orderStatus   //订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "递交异常", "7": "已完成"  , "8": "部分递交异常" 
  // orderFlowStatus: {//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成" 
  // orderPayStatus: {//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"

  async subPutDb(proxyCode, stateCode, putStateCode, orderStatus, orderFlowStatus, errorOrderStatus, errorOrderFlowStatus, errorMsg, regCode) {
    var self = this;
    var dbResult = 0;
    var subErrorMsg = null;
    var tmItem = await self.trademarkDao.model.findOne({
      where: { code: proxyCode },
      attributes: ["id", "order_id", "sourceOrderNo", "nclOneCodes", "name", "tbErrorCount"],
      include: [
        { model: self.orderDao.db.models.order, attributes: ["id", "code", "mobile", "email", "orderStatus", "orderFlowStatus", "company_id", "createuser_id"] }
      ]
    });
    if (!tmItem || !tmItem.order) {
      return { code: -1, message: "提报号对应的信息错误！", data: null };
    }
    if (stateCode != putStateCode) {
      subErrorMsg = errorMsg;
      dbResult = dbResult + 1;
    }
    var tmParams = { submitTime: new Date(), subErrorMsg: "", tbErrorCount: 0 };
    if (stateCode == putStateCode && dbResult == 0) {
      //机器人把数据正常提交到商标局
      await this.orderDao.db.transaction(async function (t) {
        let updateUserPromises = [];
        if (regCode) {
          tmParams["tmRegistNum"] = regCode;
        }
        updateUserPromises.push(
          self.dao.updateByWhere(tmParams, { where: { code: proxyCode } }, t)
        );
        // orderStatus: {//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"  
        // orderFlowStatus: {//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成" 
        if (tmItem.order.orderStatus != orderStatus || tmItem.order.orderFlowStatus != orderFlowStatus) {
          updateUserPromises.push(
            self.orderDao.updateByWhere({ orderStatus: orderStatus, orderFlowStatus: orderFlowStatus }, { where: { id: tmItem.order.id } }, t)
          );
        }
        var opmsg = "第" + tmItem.nclOneCodes + "类商标" + (regCode ? "已下回执，编号为" + regCode : "已递交官方");
        var flowCount = await self.orderflowDao.findCount({ where: { sourceOrderNo: tmItem.order.code, opContent: opmsg } });
        if (flowCount == 0) {
          //商标流程增加
          updateUserPromises.push(
            //订单流程log
            await self.orderflowDao.create({
              company_id: tmItem.order.company_id,
              createuser_id: tmItem.order.createuser_id,
              sourceOrderNo: tmItem.order.code,
              opContent: opmsg,
            }, t)
          );
        }
        Promise.all(updateUserPromises);
      }).then(function (result) {
        //"success"
        //进度消息通知
        self.sendProgressMsg(tmItem, regCode);

      }).catch(function (err) {
        // console.log(err)
        subErrorMsg = err.stack;
        dbResult = dbResult + 1;
      })
    }
    if (dbResult > 0) {
      //处理非异常状态
      await this.dao.db.transaction(async function (t) {
        if (subErrorMsg) {
          if (subErrorMsg.length > 3980) {
            subErrorMsg = subErrorMsg.substring(0, 3980);
          }
          self.dao.updateByWhere({ submitTime: new Date(), subErrorMsg: subErrorMsg, tbErrorCount: 1 }, { where: { code: proxyCode } }, t);
        }
        if (tmItem.order.orderStatus != errorOrderStatus && tmItem.order.orderFlowStatus != errorOrderFlowStatus) {
          self.orderDao.updateByWhere({ orderStatus: errorOrderStatus, orderFlowStatus: errorOrderFlowStatus }, { where: { id: tmItem.order.id } }, t);
        }
        var opmsg = "第" + tmItem.nclOneCodes + "类商标" + (regCode ? "更新回执异常，要更新的申请号为" + regCode : "递交官方异常（请仔细核对交官材料）");
        var flowCount = await self.orderflowDao.findCount({ where: { sourceOrderNo: tmItem.order.code, opContent: opmsg } });
        if (flowCount == 0) {
          //订单流程log
          await self.orderflowDao.create({
            company_id: tmItem.order.company_id,
            createuser_id: tmItem.order.createuser_id,
            sourceOrderNo: tmItem.order.code,
            opContent: opmsg,
          }, t);
        }
      })
      return { code: -1, message: "update failure", data: null };
    }
    return { code: 200, message: "操作成功", data: null };
  }
  //发送进度消息（邮箱、公众号）
  async sendProgressMsg(tmItem, regCode) {
    if (tmItem && regCode && tmItem.name) {
      var self = this;
      var order = tmItem.order;
      var company = await this.companyDao.model.findOne({
        where: { id: order.company_id },
        attributes: ["id", "name", "domainname"],
        raw: true
      });
      if (order && order.company_id && company && company.name && company.domainname) {
        if (order.email) {
          var text = "【知圈圈】尊敬的用户，您的商标：" + tmItem.name + "已经提交商标局，申请号为：" + regCode + "，详情请查看官网 。 『" + company.domainname + "』" + company.name;
          self.mailClient.sendMsg(order.email, "进度通知", null, text, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom 
        }
        if (order.mobile) {
          var text = "【知圈圈】尊敬的用户，您的商标：" + tmItem.name + "已经提交商标局，申请号为：" + regCode + "，详情请查看官网 。 『" + company.domainname + "』" + company.name;
          self.pushmsgWxop.pushMsg({
            company_id: order.company_id, mobile: order.mobile, title: text, itemName: "进度通知", progress: "已完成"
          });
        }
      }

    }
  }
}
module.exports = TradeMarkService;
// var task = new TradeMarkService();
// task.setUpdateTradeMarkCode("TM2019081517512VN1PB", "22222222", "RECVCOMMIT").then(d=>{
//   console.log(d);
// })
