const system = require("../../system");
const ServiceBase = require("../sve.base")
const settings = require("../../../config/settings")
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
const logCtl = system.getObject("web.oplogCtl");
const fs = require("fs");
var zipper = require("zip-local");
class TmOfficialService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(TmOfficialService));
    this.ossClient = system.getObject("util.ossClient");
    this.trademarkDao = system.getObject("db.trademarkDao");
    this.restClient = system.getObject("util.restClient");
    this.oplogDao = system.getObject("db.oplogDao");
    this.useraddrDao = system.getObject("db.useraddrDao");
    this.mailClient = system.getObject("util.mailClient");
    this.pushmsgWxop = system.getObject("wxop.pushmsgWxop");
  }
  /**
   * 公众号消息推送
   * @param {*} codeList 注册号列表
   * @param {*} officialType 官文类型编码
   */
  async wxMsgSend(codeList,officialType){
    console.log(codeList);
    if(!codeList || codeList.length<1 || !officialType){
      return null;
    }
    var tmList = await this.trademarkDao.model.findAll({
      where:{tmRegistNum: { [this.db.Op.in]: codeList }},
      include:[
        { model: this.db.models.order, as: "order", attributes: ["code","contacts","mobile","email"]},
        { model: this.db.models.company, as: "company", attributes: ["name","domainname"]}
      ],
      attributes: ["tmRegistNum","name","nclOneCodes","order_id","company_id","createuser_id"],
      raw:true
    });
    var orderList=[];
    var mobileList = [];
    var self = this;
    for(var a=0;a<tmList.length;a++){
      var tm = tmList[a];
      if(tm && tm.order_id){
        var index = mobileList.indexOf(tm["order.mobile"]);
        if(index<0){
          mobileList.push(tm["order.mobile"]);
          var o = tm;
          o["count"]=1;
          orderList.push(o);
        }else{
          if(orderList[index]["count"]){
            orderList[index]["count"] = orderList[index]["count"] + 1;
          }else{
            orderList[index]["count"] = 1;
          }
          
        }
      }
    }
    for(var i=0;i<orderList.length;i++){
      var orderItem = orderList[i];
      if(orderItem["order.mobile"] && orderItem["company.name"]){
        var text=null;
        if(officialType == "3"){//商标注册申请受理通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标：“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发受理通知书电子版，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }else{
            text="【知圈圈】尊敬的用户，您的商标：“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发受理通知书电子版，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }
        }else if(officialType == "9"){//商标注册申请初步审定公告通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】恭喜您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的初步审定公告通知书，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          
          }else{
            text="【知圈圈】恭喜您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的初步审定公告通知书，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }
        }else if(officialType == "13"){//电子版商标注册证
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的电子版商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+"。";
          
          }else{
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的电子版商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+"。"; 
          }
          
        }else if(officialType == "12"){//纸质版商标注册证
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅。";
          
          }else{
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅。";
          }
        }else if(officialType == "7" || officialType == "8" ){//商标驳回通知书  商标部分驳回通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】很遗憾通知您，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的驳回通知书，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+" 。"; 
          
          }else{
            text="【知圈圈】很遗憾通知您，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的驳回通知书，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+" 。"; 
          }
        }
        if(text){
          self.pushmsgWxop.pushMsg({
            company_id:orderItem["company_id"],mobile:orderItem["order.mobile"],title:text,itemName:"官文通知",progress:"已完成"
          });
        }
        
      }
    }
  }
  /**
   * 邮箱消息推送
   * @param {*} codeList 注册号列表
   * @param {*} officialType 官文类型编码
   */
  async emailMsgSend(codeList,officialType){
    console.log(codeList);
    if(!codeList || codeList.length<1 || !officialType){
      return null;
    }
    var tmList = await this.trademarkDao.model.findAll({
      where:{tmRegistNum: { [this.db.Op.in]: codeList }},
      include:[
        { model: this.db.models.order, as: "order", attributes: ["code","contacts","mobile","email"]},
        { model: this.db.models.company, as: "company", attributes: ["name","domainname"]}
      ],
      attributes: ["tmRegistNum","name","nclOneCodes","order_id","company_id","createuser_id"],
      raw:true
    });
    var orderList=[];
    var emailList = [];
    var self = this;
    for(var a=0;a<tmList.length;a++){
      var tm = tmList[a];
      if(tm && tm.order_id && tm["order.email"]){
        var index = emailList.indexOf(tm["order.email"]);
        if(index<0){
          emailList.push(tm["order.email"]);
          var o = tm;
          o["count"]=1;
          orderList.push(o);
        }else{
          if(orderList[index]["count"]){
            orderList[index]["count"] = orderList[index]["count"] + 1;
          }else{
            orderList[index]["count"] = 1;
          }
          
        }
      }
    }
    for(var i=0;i<orderList.length;i++){
      var orderItem = orderList[i];
      if(orderItem["order.email"] && orderItem["order.email"].indexOf("@")>=0 && orderItem["company.name"]){
        var text=null;
        if(officialType == "3"){//商标注册申请受理通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标：“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发受理通知书电子版，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }else{
            text="【知圈圈】尊敬的用户，您的商标：“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发受理通知书电子版，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }
        }else if(officialType == "9"){//商标注册申请初步审定公告通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】恭喜您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的初步审定公告通知书，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          
          }else{
            text="【知圈圈】恭喜您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的初步审定公告通知书，详情请查看官网。『"+orderItem['company.domainname']+"』"+orderItem['company.name'];
          }
        }else if(officialType == "13"){//电子版商标注册证
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的电子版商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+"。";
          
          }else{
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的电子版商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+"。"; 
          }
          
        }else if(officialType == "12"){//纸质版商标注册证
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅。";
          
          }else{
            text="【知圈圈】尊敬的用户，您的商标“"+orderItem.name+"”第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的商标注册证，请您登录『"+orderItem['company.domainname']+"』进行查阅。";
          }
        }else if(officialType == "7" || officialType == "8" ){//商标驳回通知书  商标部分驳回通知书
          if(orderItem.count && orderItem.count>1){
            text="【知圈圈】很遗憾通知您，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"等"+orderItem.count+"件官文，已经收到官方下发的驳回通知书，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+" 。"; 
          
          }else{
            text="【知圈圈】很遗憾通知您，您的商标“"+orderItem.name+"” 第"+orderItem.nclOneCodes+"类，申请号"+orderItem.tmRegistNum+"，已经收到官方下发的驳回通知书，请您登录『"+orderItem['company.domainname']+"』进行查阅，订单"+orderItem['order.code']+" 。"; 
          }
        }
        if(text){
          self.mailClient.sendMsg(orderItem["order.email"], "官文通知", null, text, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom 
        }
      }
    }
  }
  async setReturnReceip(user, obj, officialType) {
    var official_type = uiconfig.config.pdict.official_type;
    var official_type_name = official_type[officialType];
    var self = this;
    const updateFailed = [];//存放失败数据
    var msgList=[];//消息推送列表
    for (let i = 0; i < obj.length; i++) {
      var objItem = obj[i];
      var reg_code = await self.disposeFileName(objItem.name, officialType, official_type_name);
      if (!reg_code) {
        updateFailed.push(objItem.name);
        continue;
      }
      var tm = await self.trademarkDao.model.findOne({
        where: { tmRegistNum: reg_code },
        attributes: ["id", "name", "nclOneCodes"]
      });
      if (!tm) {
        updateFailed.push(objItem.name);
        continue;
      }
      var flowWhere = { where: { trademark_id: tm.id, officialType: officialType } };
      var flowCount = await this.dao.findCount(flowWhere);
      var guidStr = await self.getUidInfo(6, 60);
      await this.db.transaction(t => {
        let updateUserPromises = []
        var params = {
          createuser_id: user.id,
          officialType: officialType,
          officialFileName: official_type_name + "_" + reg_code + "_" + tm.name + "_" + tm.nclOneCodes + ".pdf",
          officialFileUrl: objItem.url,
          trademark_id: tm.id,
          company_id: user.company_id,
          tmRegistNum: reg_code,
        };
        var param = { officialType: officialType };
        updateUserPromises.push(
          self.trademarkDao.updateByWhere(param, { where: { tmRegistNum: reg_code } }, t)
        );
        if (flowCount > 0) {
          updateUserPromises.push(
            self.updateByWhere(params, flowWhere, t)
          );
        } else {
          updateUserPromises.push(
            self.dao.create(params, t)
          );
        }
        return Promise.all(updateUserPromises)
      }).then(async function (result) {
        msgList.push(reg_code);
        console.log(msgList);
      }).catch(function (err) {
        console.log(err)
        updateFailed.push(obj[i].name);
      });

    }
    this.wxMsgSend(msgList,officialType);
    this.emailMsgSend(msgList,officialType);
    return { code: "1", msg: "ok", failed: updateFailed };
  }
  async disposeFileName(fileName, officialType, official_type_name) {
    if (officialType == "1") {
      if (fileName.indexOf("TMZC") < 0) {
        return "";
      }
      return fileName.substring(4, fileName.length).split('.')[0];
    }//商标注册申请书
    if (officialType == "12") {
      return fileName.split('.')[0];;
    }//纸质版商标注册证
    if (officialType == "13") {
      if (fileName.indexOf("商标注册证") < 0) {
        return "";
      }
    }//电子版商标注册证
    else if (officialType == "9") {
      if (fileName.indexOf("初步审定公告通知书") < 0) {
        return "";
      }
    }//初步审定公告通知书
    else if (fileName.indexOf(official_type_name) < 0) {
      return "";
    }
    var fileNameList = fileName.split('_');
    if (fileNameList.length != 3) {
      return "";
    }
    return fileNameList[1];
  }

  async batchDownload(user, selectedRows) {
    var self = this;
    try {
      var guidStr = await self.getUidInfo(6, 60);
      var filePath = '/tmp/download_' + user.id + "_" + user.company_id + guidStr;
      if (!fs.existsSync(filePath)) {
        fs.mkdirSync(filePath);
      }
      for (let index = 0; index < selectedRows.length; index++) {
        const element = selectedRows[index];
        if (element) {
          await self.opDownFileInfo(element.officialFileUrl, element.officialFileName, filePath);
        }
      }
      var saveZipFileName = "download" + "_" + (new Date()).Format("yyyyMMddhhmmss") + "_" + user.id + "_" + user.company_id + "_" + guidStr + ".zip";
      var saveZipFilePath = filePath + "/" + saveZipFileName;
      await zipper.sync.zip(filePath).compress().save(saveZipFilePath);
      //上传 saveFilePath的文件 到ossClient
      var rtn = await this.ossClient.upfile(saveZipFileName, saveZipFilePath);
      //删除本地文件
      self.deleteall(filePath)//将文件夹传入即可

      self.oplogDao.create({
        company_id: user.company_id,
        user_id: user.id,
        op: filePath,//操作的服务器的文件目录
        opTitle: "用户批量下载文件操作",
        logLevel: "info",
        content: (rtn && rtn.url && rtn.name) ? rtn.url : saveZipFilePath,//要上传到oss山的zip压缩包，成功为oss文件路径，失败为服务器文件路径
        opLogType: "officialDownload",//操作类型,0其他，1线上支付接口回调，2平台转账，3文件批量下载
        opLogStatus: (rtn && rtn.url && rtn.name) ? 1 : 0,//操作状态，0失败，1成功
      });
      if (rtn && rtn.url && rtn.name) {
        return { code: 1, url: rtn.url }
      } else {
        //日志记录
        logCtl.error({
          optitle: "批量下载文件上传zip文件到oss异常：error",
          op: "/igirl-web/app/base/service/impl/tmofficialSve.js/batchDownload",
          content: "请求参数：filePath=" + filePath + "，saveZipFilePath=" + saveZipFilePath + "，上传返回的值：" + JSON.stringify(rtn),
          clientIp: ""
        });
        return { code: -110, msg: "操作zip文件异常" }
      }
    } catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "通过restClient批量下载操作异常error",
        op: "/igirl-web/app/base/service/impl/tmofficialSve.js/batchDownload",
        content: "请求参数：filePath=" + filePath + "，异常信息error：" + e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "批量下载文件异常" }
    }
  }
  async opDownFileInfo(docUrl, fileName, filePath) {  //从oss下载到本地
    /*docUrl下载链接，全路径，如：https://XXXXXX.pdf?XXXXX */
    try {
      var saveFilePath = filePath + "/" + fileName;//fileName为xxx.pdf
      // 下载文件到指定的路径
      var tmpp = await this.restClient.execDownload("'" + docUrl + "'", saveFilePath);
      return { code: 1 }
    } catch (e) {
      // console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "通过restClient将文件url下载操作异常error",
        op: "/igirl-web/app/base/service/impl/tmofficialSve.js/opDownFileInfo",
        content: "请求参数：docUrl=" + docUrl + "，fileName=" + fileName + "，异常信息error：" + e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "下载文件异常" }
    }
  }
  async deleteall(path) {
    var files = [];
    if (fs.existsSync(path)) {
      files = fs.readdirSync(path);
      files.forEach(function (file, index) {
        var curPath = path + "/" + file;
        if (fs.statSync(curPath).isDirectory()) { // recurse
          deleteall(curPath);
        } else { // delete file
          fs.unlinkSync(curPath);
        }
      });
      fs.rmdirSync(path);
    }
  }

  /**
   * 官文列表检索
   * @param officialMailType:"官文邮寄类型",
   * @param officialType:"官文类型",
   * @param queryinput:"输入框输入值",
   * @param swDate:["2019-07-03T16:00:00.000Z", "2019-08-07T16:00:00.000Z"],收文时间
   * @param xdDate:["2019-07-03T16:00:00.000Z", "2019-08-07T16:00:00.000Z"] 下单时间
   */
  async findAllOfficial(obj){
    var user = obj.user;
    if(!user){
      return {code:-100,msg:"用户数据错误"};
    }
    var sql = "SELECT tmofficial.officialFileUrl, tmofficial.id as tmofficial_id,tmofficial.tmRegistNum,tmofficial.province as tmofficial_province,tmofficial.city as tmofficial_city,tmofficial.area as tmofficial_area,"+
    "tmofficial.recipients,tmofficial.mobile as recipients_mobile,tmofficial.email as recipients_email,tmofficial.address as recipients_address,"+
    "tmofficial.officialTypeName,tmofficial.officialType, tmofficial.created_at as tmofficial_created_at,"+
    "tmofficial.officialMailType, tmofficial.officialMailTypeName,"+
    "tm.nclOneCodes, tm.name as tm_name, tm.id as tm_id,"+
    "tm.created_at as tm_created_at, biz_order.id as order_id,biz_order.code as order_code,"+
    "biz_order.sveItemName, biz_order.created_at as order_created_at,"+
    "biz_order.createuser_id as order_createuser_id,biz_order.mobile as order_mobile, "+
    "customerinfo.id as customerinfo_id, customerinfo.name as customerinfo_name "+
    "FROM `biz_tmofficial` AS tmofficial "+
    "LEFT JOIN (SELECT id, order_id, nclOneCodes,name, created_at FROM biz_trademark WHERE deleted_at IS NULL ) AS tm ON tmofficial.trademark_id = tm.id "+
    "LEFT JOIN (SELECT id, code, customerinfo_id, sveItemName, created_at, mobile,createuser_id, company_id  FROM biz_order WHERE deleted_at IS NULL ";
    
    sql = sql +") as biz_order ON biz_order.id = tm.order_id "+
    "LEFT JOIN (SELECT id, name FROM biz_customerinfo ) AS customerinfo ON customerinfo.id = biz_order.customerinfo_id  "+
    "WHERE tmofficial.deleted_at is null and tmofficial.deleted_at IS NULL and biz_order.id is not null and tmofficial.id is not null and tm.id is not null "+
    " AND tmofficial.company_id ="+user.company_id;
    if(user.mobile ){
      sql = sql +" and (biz_order.createuser_id="+user.id+" or biz_order.mobile="+user.mobile+" ) ";
    }else{
      sql = sql +" and biz_order.createuser_id="+user.id ;
    }
    // " AND (tmofficial.createuser_id ="+user.id+
    // " OR biz_order.mobile ="+ user.mobile +
    // " ) ";
    if(obj.officialMailType){//官文邮寄类型
      sql = sql + " AND tmofficial.officialMailType="+obj.officialMailType;
    }
    if(obj.officialType){//官文类型
      sql = sql + " AND tmofficial.officialType="+obj.officialType;
    }
    if(obj.queryinput){//输入框输入值 申请号/订单号/申请人名称
      sql = sql + " AND (tmofficial.tmRegistNum = '"+obj.queryinput+
      "' OR biz_order.code='"+obj.queryinput+
      "' OR customerinfo.name like '%"+obj.queryinput+"%') ";
    }
    if(obj.swDate && obj.swDate.length==2){//收文时间
      sql = sql + " AND (tmofficial.created_at BETWEEN '"+obj.swDate[0]+"' AND '"+obj.swDate[1]+"')";
    }
    if(obj.xdDate && obj.xdDate.length==2){//下单时间
      sql = sql + " AND (biz_order.created_at BETWEEN '"+obj.xdDate[0]+"' AND '"+obj.xdDate[1]+"')";
    }
    console.log("sql:"+sql);
    var tmpResult = await this.dao.customQuery(sql);
    return {code:1,data:tmpResult};
  }
  /**
   * 官文邮寄申请
   * @param official_ids 官文id列表
   * @param addr_obj:{
   *  recipients: "",//收件人
      mobile: "",//手机号
      email: "",//邮箱   
      province:"",//省名称
      city: "",//市名称
      area: "",//申请区域-存储省市的编码
      address: "",//地址 
     }
   */
  async tmOfficialPostApply(obj){
    var user = obj.user;
    if(!user){
      return {code:-100,msg:"用户数据错误"};
    }
    var official_ids = obj.official_ids;
    var addr_obj = obj.addr_obj;
    if(!official_ids || official_ids.length<1){
      return {code:-101,msg:"official_ids参数错误"};
    }
    // var officials=await this.dao.model.findAll({
    //   where:{id:{[this.db.Op.in]:official_ids}},
    //   raw:true
    // });
    var ids = official_ids.join(",");
    var sql = "SELECT tmofficial.id as tmofficial_id,tmofficial.createuser_id,tmofficial.tmRegistNum,"+
    "tmofficial.officialTypeName,tmofficial.officialType,"+
    "tmofficial.officialMailType, tmofficial.officialMailTypeName,"+
    "tm.name as tm_name, tm.id as tm_id,"+
    "biz_order.id as order_id,biz_order.mobile "+
    "FROM `biz_tmofficial` AS tmofficial "+
    "LEFT JOIN (SELECT id, order_id, name FROM biz_trademark  ) AS tm ON tmofficial.trademark_id = tm.id "+
    "LEFT JOIN (SELECT id, code, mobile FROM biz_order ";
    sql = sql +") as biz_order ON biz_order.id = tm.order_id "+
    "WHERE tmofficial.deleted_at is null "+
    " AND tmofficial.id  in ("+ids+")";
    var officials = await await this.dao.customQuery(sql);
    console.log(officials);
    if(!officials || officials.length<1){
      return {code:-102,msg:"未知官文"};
    }
    for(var i=0;i<officials.length;i++){
      var official = officials[i];
      if(official.officialType!="12"){
        return {code:-103,msg:"只能邮寄纸质的商标注册证官文"};
      }
      if(official.createuser_id!=user.id && official.mobile != user.mobile){
        return {code:-104,msg:"只能邮寄自己的官文"};
      }
    }
    if(!addr_obj){
      return {code:-105,msg:"addr_obj参数错误"};
    }
    // var addr = await this.useraddrDao.model.findOne({
    //   where:{id:addr_id,company_id:user.company_id,createuser_id:user.id},
    //   raw:true
    // });
    // if(!addr){
    //   return {code:-106,msg:"未知地址"};
    // }
    if(!addr_obj.recipients){
      return {code:-106,msg:"recipients参数错误"};
    }
    if(!addr_obj.mobile){
      return {code:-107,msg:"mobile参数错误"};
    }
    if(!addr_obj.address){
      return {code:-108,msg:"address参数错误"};
    }
    // if(!addr_obj.province){
    //   return {code:-109,msg:"province参数错误"};
    // }
    // if(!addr_obj.city){
    //   return {code:-110,msg:"city参数错误"};
    // }
    // if(!addr_obj.area){
    //   return {code:-111,msg:"area参数错误"};
    // }
    var updateObj={
      officialMailType:"2",//官文邮寄类型:"1": "待申请", "2": "待邮寄", "3": "已邮寄"
      recipients: addr_obj.recipients,//收件人
      mobile: addr_obj.mobile,//手机号
      email: addr_obj.email,//邮箱   
      province:addr_obj.province,//省名称
      city: addr_obj.city,//市名称
      area: addr_obj.area,//申请区域-存储省市的编码
      address: addr_obj.address,//地址
    };
    await this.dao.model.update(updateObj,{where:{
      id: { [this.db.Op.in]: official_ids }
    }});
    return {code:1,msg:"success"};
  }
}
module.exports = TmOfficialService;
// var task = new TmOfficialService();
// var a = new Date().getTime();
// var obj={
//   officialMailType:"1",officialType:"1",queryinput:"公司",
//   swDate:["2019-07-03T16:00:00.000Z", "2019-08-07T16:00:00.000Z"],
//   xdDate:["2019-07-03T16:00:00.000Z", "2019-08-07T16:00:00.000Z"]
// };
// task.findAllOfficial(obj).then(d=>{
//   console.log("ddddddddddddddddddddd");
//   console.log(d);
//   console.log(new Date().getTime()-a);
// })

