var System = require("../../system");
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
var xlsx = require('node-xlsx');
var fs = require("fs");
class TrademarkCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(TrademarkCtl));
    this.fqtmsearchApi = System.getObject("api.fqtmsearch");
    this.orderSve = System.getObject("service.orderSve");
    this.tmflowSve = System.getObject("service.tmflowSve");
    this.uploadCtl = System.getObject("web.uploadCtl");
    this.tm_submit_status = {
        "WAITARTIFICIALEXAMINE": "等待人工审核",
        "1": "商标注册申请书",
        "2": "补证通知",
        "3": "已受理",
        "4": "不予受理",
        "5": "同日申请补送证据",
        "6": "同日申请协商",
        "7": "全部驳回",
        "8": "部分驳回",
        "9": "初步审定公告",
        "10": "商家异议",
        "11": "裁定通知",
        "12": "已下发纸质注册证",
        "13": "已下发注册证",
        "14": "同日申请抽签",
        "15": "申请审查意见",
        "FILELIST": "交文清单",
        "ENVLOPE": "信封正反面",
        "NOTAPPROVAL": "不予核准",
        "APPROVAL": "核准通知",
        "READY": "资料准备",
        "DOCFINISH": "资料齐全",
        "AWAITCHECK": "等待审核",
        "WAITCOMMIT": "待提交",
        "COMMITED": "人工已提交",
        "ROBOT": "已提交",
        "ROBOTPAY": "已提交(待校验)",
        "RECVCOMMIT": "已收提交",
        "FILLEXCEPTION": "填报异常",
        "DISCARDED": "废弃",
        "ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)",
        "REQALIERROR": "阿里接口错误(需峰擎系统处理)",
        "SUBALITM": "已提交阿里(待补全信息)",
        "SUBALITMOK": "已补全信息(待确认商标)",
        "SUBALIPAY": "已提交阿里(待支付)",
        "WAITALIREVIEW": "待阿里审核(已支付)",
        "ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)",
        "ALIAUDITYES": "阿里审核通过",
        "ALIPAYREFUND": "已失败退款(阿里)",
        "ALIPAPERS2": "需要补正(阿里)",
        "ALIPAPERS4": "已补正(阿里)",
        "ALIPAPERS5": "超时未补正(阿里)",
        "ALIPAPERS6": "补正已递交(阿里)",
        //1688
        "WAITCONFIRM":"等待客户确认",
        "CONFIRMFAIL":"方案不通过"
    };
  }
  async getOrderDetail(obj, req) {
    try {
      //获取提报h_trade_mark订单商标明细、h_tmapplier_info商标申请用户信息、h_tmcustomer_info商标订单联系人信息两个表信息
      var orderNum = obj.orderNum;
      var tmStatus = obj.tmStatus;
      if (orderNum == null || orderNum == "") {
        return { code: -100, msg: "订单号不能为空", data: null }
      }
      if (tmStatus == null || tmStatus == "") {
        return { code: -110, msg: "处理类型不能为空", data: null }
      }
      var result = await this.service.getOrderDetail(orderNum, tmStatus);
      return { code: 1, msg: "ok", data: result }
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "TrademarkCtl->getOrderDetail方法请求出错:",
        op: "base/controller/impl/trademarkCtl/getOrderDetail",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "操作异常", data: null }
    }
  }
  async findByOrderNum(obj, req) {
    var orderNum = obj.orderNum;
    return this.service.findByOrderNum(orderNum);
  }
  async findByPayUserId(obj, req) {
    var payUserId = obj.payUserId;
    return this.service.findByPayUserId(payUserId);
  }
  async findTmFlowByProxyCode(obj, req) {
    var proxyCode = obj.proxyCode;
    return this.service.findTmFlowByProxyCode(proxyCode);
  }
  async findBigDataTmByCompanyName(obj, req) {
    var appkey = req.session.app.appid;
    var data = {
      "appKey": appkey,
      "applicantCn": obj.cname,
      "pageSize": obj.ps,
      "currentPage": obj.cp
    }
    var result = { rows: [], count: 0 };
    var sources = [];
    var that = this;
    var tms = await this.fqtmsearchApi.tmSearch(data);
    return tms;
  }
  async findBigDataTmByPayUserId(obj, req) {
    var appkey = req.session.app.appid;
    var payUserId = obj.payUserId;
    var result = [];
    var data = {
      "appKey": appkey,
      "applicantCn": "",
      "pageSize": 10000,
      "currentPage": 1
    };
    var appliers = await this.orderSve.getApplierByPayUserId(payUserId);
    for (var i = 0; i < appliers.length; i++) {
      data.applicantCn = appliers[i].applyName;
      var that = this;
      var tms = await this.fqtmsearchApi.tmSearch(data);
      if (tms.status == 0 && tms.data.length > 0) {
        result = result.concat(tms.data);
      }
    }
    return result;
  }
  async putStatusById(queryobj, pobj, req) {
    try {
      var remarkinfo = pobj.remarkinfo || "";
      remarkinfo = remarkinfo ? "，原因：" + remarkinfo : "";
      var user = req.session.user;
      var app = req.session.app;
      var env = pobj.env || "";
      if (user == null || user == "") {
        return { code: -100, msg: "用户登录状态有误", data: null }
      }
      if (app == null || app == "") {
        return { code: -110, msg: "用户登录状态app有误", data: null }
      }
      var item = await this.service.getItemById(pobj.id, null);
      if (!item) {
        return { code: -120, msg: "没有相关商标信息", data: null }
      }
      if (item.tmStatus != "WAITARTIFICIALEXAMINE") {
        return { code: -130, msg: "请查看代理号为" + item.proxyCode + "的状态是否是等待人工提交", data: null }
      }
      if (!pobj.status) {
        return { code: -120, msg: "status参数信息不能为空", data: null }
      }
      if (pobj.status != "WAITCOMMIT" && pobj.status != "FILLEXCEPTION" && pobj.status != "WAITARTIFICIALEXAMINE") {
        return { code: -130, msg: "status参数信息有误", data: null }
      }
      var result = null;
      var judgeRes = this.service.dao.judgeTmSourceType(item.tmSourceType);
      if (judgeRes || item.tmSourceType == "16" || pobj.status == "FILLEXCEPTION" || pobj.status == "WAITARTIFICIALEXAMINE") {
        var params = { remarkInfo: "操作用户id=" + user.id, opRemarkInfo: remarkinfo, tmStatus: pobj.status, id: pobj.id }
        result = await this.service.putStatusById(params);
      }//fq
      else if (item.tmSourceType == "32") {
        result = await this.service.putAliTmStatus(item);
      }//阿里的商标，则直接推送到阿里---状态：已提交阿里(待支付)
      // if (item.tmSourceType == "64") {
      if (judgeRes) {
        if(item.tmSourceType=="1024" || item.tmSourceType=="2048" ){//center-channel
          var pushObj={
            orderNo:item.channelOrderNum,
            tbCode:item.proxyCode,
            tmStatus:pobj.status,
            opNotes:remarkinfo,
            tmStatusName:this.tm_submit_status[pobj.status]
          }
          if(item.submitTime){
            pushObj["submitTime"]=item.submitTime;
          }
          this.service.channelreceiveDao.updateChannelTmStatus(pushObj);
        }else{
          var pushObj={
            proxyCode:item.proxyCode,
            channelCode:judgeRes,
            tmStatus:pobj.status,
            opNotes:remarkinfo,
            channelOrderNum:item.channelOrderNum
          }
          if(item.submitTime){
            pushObj["submitTime"]=item.submitTime;
          }
          this.service.updateChannelTmStatus(pushObj);
        }
      }//1688的商标，则直接推送到channel
      // if (item.tmSourceType == "128") {
      //   var pushObj={
      //     proxyCode:item.proxyCode,
      //     channelCode:"jd",
      //     tmStatus:pobj.status,
      //     opNotes:remarkinfo,
      //     channelOrderNum:item.channelOrderNum
      //   }
      //   if(item.submitTime){
      //     pushObj["submitTime"]=item.submitTime;
      //   }
      //   await this.service.updateChannelTmStatus(pushObj);
      // }//jd的商标，则直接推送到channel
      if (result && result.code == 1) {
        this.sendDDMsg(pobj.status, remarkinfo, item);
      }
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "商标修改状态异常",
        op: "base/controller/impl/trademarkCtl.js/putStatusById",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1 }
    }
  }
  async aliDataClose(queryobj, pobj, req) {//数据关闭到阿里
    var user = req.session.user;
    if (user == null || user == "") {
      return { code: -100, msg: "用户登录状态有误", data: null }
    }
    try {
      var opI = 0;
      var list = await this.service.getListByIds(pobj.ids);
      if (!list || list.length == 0) {
        return { code: -120, msg: "没有相关商标信息", data: null }
      }
      for (let index = 0; index < list.length; index++) {
        var element = list[index];
        //"DOCFINISH": "资料齐全",
        //"SUBALITM": "已提交阿里(待补全信息)",
        // "ALIPAYREFUND": "已失败退款(阿里)",
        //"ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)",
        //"ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)",
        //"REQALIERROR": "阿里接口错误(需峰擎系统处理)",
        //"SUBALITMOK": "已补全信息(待确认商标)",
        if (element && element.tmSourceType == "32" && element.businessId &&
          ["DOCFINISH", "SUBALITM", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "REQALIERROR", "SUBALITMOK"].indexOf(element.tmStatus) >= 0) {
          await this.service.closeAliTmStatus(element);
          opI++;
        }
      }
      if (opI > 0) {
        return { code: 1, msg: "阿里数据关闭成功" };
      }
      return { code: -140, msg: "没有查询到要关闭的数据信息" };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "阿里数据关闭异常",
        op: "base/controller/impl/trademarkCtl.js/aliDataClose",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "阿里数据关闭异常" };
    }
  }
  async aliDataSync(queryobj, pobj, req) {//数据同步到阿里
    var user = req.session.user;
    if (user == null || user == "") {
      return { code: -100, msg: "用户登录状态有误", data: null }
    }
    try {
      var opI = 0;
      var list = await this.service.getListByIds(pobj.ids);
      if (!list || list.length == 0) {
        return { code: -120, msg: "没有相关商标信息", data: null }
      }
      var channelOrderNumList = [];
      for (let index = 0; index < list.length; index++) {
        var element = list[index];
        //"DOCFINISH": "资料齐全",
        //"SUBALITM": "已提交阿里(待补全信息)",
        // "ALIPAYREFUND": "已失败退款(阿里)",-----------------------------
        //"ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)",--------------
        //"ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)",
        //"REQALIERROR": "阿里接口错误(需峰擎系统处理)",
        if (element && element.tmSourceType == "32" &&
          ["DOCFINISH", "SUBALITM", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "REQALIERROR"].indexOf(element.tmStatus) >= 0) {
          if (element.tmStatus == "ALIPAYREFUND" || element.tmStatus == "ALIAUDITNOT") {
            var opResult = await this.service.putTmAndAddTm("DISCARDED", element);
            if (opResult.code == 1 && opResult.data) {
              element = opResult.data;
            }
          }
          await this.service.putAliTmStatus(element);
          opI++;
        }//阿里的商标，则直接推送到阿里---状态：已提交阿里(待支付)
        if (channelOrderNumList.indexOf(element.channelOrderNum) < 0) {
          channelOrderNumList.push(element.channelOrderNum);
        }
      }
      var failureOrderNum = [];
      for (let j = 0; j < channelOrderNumList.length; j++) {
        const channelOrderNum = channelOrderNumList[j];
        if (channelOrderNum) {
          var channelorder = await this.getChannelOrderByOrderNumAliDataSync({ channelOrderNum: channelOrderNum, env: pobj.env }, "");
          if (channelorder.code != 1) {
            return { code: -130, msg: "渠道服务单对应的信息为空" };
          }
          var tmList = await this.service.findListByChannelOrderNum(channelOrderNum, channelorder.data.needId);
          if (tmList && tmList.length) {
            //SUBALITMOK--已补全信息(待确认商标)
            var tmplist = tmList.filter(item => item.tmStatus == "SUBALITMOK");
            if (tmplist && tmplist.length == Number(channelorder.data.oneClassCount)) {
              var tmIdList = [];
              for (let i = 0; i < tmplist.length; i++) {
                const tmpItem = tmplist[i];
                if (tmpItem) {
                  tmIdList.push(tmpItem.id);
                }
              }
              await this.service.opAliVerifyTm(channelOrderNum, channelorder.data.needId, "SUBALIPAY", tmIdList);
              opI++;
            }
          }
          else {
            failureOrderNum.push(channelOrderNum);
          }
        }
      }
      if (failureOrderNum.length > 0) {
        return { code: -140, msg: "阿里数据同步部分失败，失败服务单号为：" + failureOrderNum.join(",") };
      }
      if (opI > 0) {
        return { code: 1, msg: "阿里数据同步成功" };
      }
      return { code: -150, msg: "没有查询到要同步的数据信息" };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "阿里数据同步异常",
        op: "base/controller/impl/trademarkCtl.js/aliDataSync",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "阿里数据同步异常" };
    }
  }
  async getChannelOrderByOrderNumAliDataSync(obj, req) {
    var resultdata = { code: 1, msg: "ok", data: null }
    var channelOrderNum = obj.channelOrderNum;
    var type = obj.type || "1"; //type:作用于返回参数中的订单产品余额，1：订单产品数-所有已有商标数量（新增时判断）  2：订单产品数-所有本订单号以外商标数量（修改时判断）
    var orderNum = obj.orderNum || "";
    var env = obj.env || "";
    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/trademarkCtl/getChannelOrderByOrderNumAliDataSync",
          content: "请求参数：url=" + reqUrl + "，order_no=" + channelOrderNum + "返回信息：" + JSON.stringify(rtn),
          clientIp: ""
        });
        var result = JSON.parse(rtn.stdout);

        if (result && result.code == 200) {
          resultdata.data = result.data;
          return resultdata;
        } else {
          return { code: -100, msg: "未查到渠道订单信息，渠道服务单号：" + channelOrderNum };
        }
      } catch (e) {
        //日志记录
        logCtl.info({
          optitle: "获取fq订单服务号信息--------------异常--error----------------------------",
          op: "base/web/impl/trademarkCtl/getChannelOrderByOrderNumAliDataSync",
          content: "请求参数：url=" + reqUrl + "，order_no=" + channelOrderNum + "异常信息：" + e.stack,
          clientIp: ""
        });
        resultdata.code = -200;
        resultdata.msg = "查询渠道服务单异常，渠道服务单号：" + channelOrderNum;
        return resultdata;
      }
    } else {
      resultdata.code = -120;
      resultdata.msg = "渠道服务单channelOrderNum为空";
      return resultdata;
    }
  }

  async sendDDMsg(status, remarkinfo, item) {
    if (item && item.tmSourceType == "16" && item.channelOrderNum && status == "FILLEXCEPTION") {//填报异常
      var msg = "商标申请，代理号：" + item.proxyCode + "\n申请人：" + item.applyName + "\n商标名称：" + "\n人工审核不予通过，不予通过原因：" + remarkinfo;
      var obj = {
        content: msg,
        send_msg: "",
        is_send: -1,
        order_no: item.channelOrderNum
      };
      this.tmflowSve.notifyDingTalkMsg(obj);
    }
  }
  async changeStatus(queryobj, pobj, req) {
    try {
      var tmStatus = pobj.tmStatus || "";
      if (!tmStatus) {
        return { code: -100, msg: "状态传递有误", data: null }
      }
      var user = req.session.user;
      var app = req.session.app;
      var env = pobj.env || "";
      if (user == null || user == "") {
        return { code: -110, msg: "用户登录状态有误", data: null }
      }
      if (app == null || app == "") {
        return { code: -120, msg: "用户登录状态app有误", data: null }
      }
      var params = { remarkInfo: "操作用户id=" + user.id, tmStatus: tmStatus }
      var sqlWheres = { where: { id: { [this.service.dao.db.Op.in]: pobj.ids } } };
      var r = await this.service.updateByWhere(params, sqlWheres);
      var tms = await this.service.dao.model.findAll({
        where:{id:{ [this.service.dao.db.Op.in]: pobj.ids }},
        raw:true
      });
      // for(var i=0;i<tms.length;i++){
      //   var tm = tms[i];
      //   if (tm.tmSourceType == "64") {
      //     var pushObj={
      //       proxyCode:tm.proxyCode,
      //       channelCode:"1688",
      //       tmStatus:tmStatus,
      //       opNotes:"操作用户id=" + user.id,
      //       channelOrderNum:tm.channelOrderNum
      //     }
      //     if(tm.submitTime){
      //       pushObj["submitTime"]=tm.submitTime;
      //     }
      //     await this.service.updateChannelTmStatus(pushObj);
      //   }
      // }
      return { code: 1, msg: "修改成功" };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "商标修改状态异常",
        op: "base/controller/impl/orderCtl/changeStatus",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1 }
    }
  }
  async exportXlsx(pobj, obj, req) {
    console.log("---------------------exportXlsx--------------------------------------------");
    var ids = obj.ids;
    if (!ids || ids.length < 1) {
      return { code: -1, msg: "ids参数错误" };
    }
    var dataList = await this.service.dao.model.findAll({
      where: {
        id: {
          [this.service.dao.db.Op.in]: ids,
        }
      }, raw: true
    });
    console.log(dataList);
    if (!dataList) {
      return { code: -2, msg: "商标数据为空" };
    }
    try {
      var data = [];
      var arr = [["序号", "案件文号", "案件类型", "商标名称", "类别", "类别个数", "申请人名称", "申请日", "法律状态", "注册号", "代理人"]];
      for (var i = 0; i < dataList.length; i++) {
        var value = dataList[i];
        var a = [];
        a.push(i + 1);
        a.push(value.proxyCode);
        a.push(value.tmFormTypeName);
        a.push(value.tmName);
        a.push(value.nclOneCodes);
        a.push("1");
        a.push(value.applyName);
        a.push(value.created_at);
        a.push(value.tmStatusName);
        a.push(value.tmRegistNum);
        a.push("张飞龙");
        arr.push(a);
      }
      console.log(arr);
      var buffer = xlsx.build([
        {
          name: 'sheet1',
          data: arr
        }
      ]);
      var uid = await this.getUidStr(8, 62);
      var fileName = "tmexport_" + uid + new Date().getTime().toString();
      //将文件内容插入新的文件中
      var a = await fs.writeFileSync('/tmp/' + fileName + '.xlsx', buffer, { 'flag': 'w' });
      var wresult = { path: '/tmp/' + fileName + '.xlsx', name: fileName + '.xlsx' };
      var r = await this.uploadCtl.upfile(wresult.name, wresult.name);
      fs.unlink(wresult.path, e => {
        console.log("fail");
      });
      console.log(r.url);
      return { code: 1, data: r };
    } catch (error) {
      return { code: -200, msg: "操作失败", data: error };
    }

  }
  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('');
  }
  async getLastTradeMark(obj, req) {
    var user = req.session.user;
    if (user) {
      try {
        var order = await this.orderSve.dao.model.findOne({ where: { user_id: user.id }, "order": [["id", "DESC"]], raw: true });
        console.log(order);
        if (order && order.orderNum) {
          var tms = await this.service.dao.model.findAll({ where: { orderNum: order.orderNum }, raw: true });
          return { code: 1, data: tms };
        } else {
          return { code: -101, msg: "订单数据为空" };
        }

      } catch (error) {
        return { code: -100, data: error, msg: "操作失败" };
      }
    } else {
      return { code: -101, msg: "用户数据为空" };
    }
  }
  //商标业务员转移
  async tmtransfer(pobj, obj, req) {
    var user = req.session.user;
    if (user) {
      obj["user"] = user;
      try {
        var result = await this.service.tmtransfer(obj);
        return result;
      } catch (error) {
        return { code: -200, msg: "操作失败" };
      }
    } else {
      return { code: -100, msg: "未知的用户" };
    }
  }
  //根据渠道订单号查询尼斯数据
  async getHistoryNclByChannelOrderNum(obj, req) {
    var user = req.session.user;
    if (user) {
      obj["user"] = user;
      try {
        var result = await this.service.getHistoryNclByChannelOrderNum(obj);
        return result
      } catch (error) {
        var err = error.stack;
        return { code: -200, msg: "操作失败", err: err };
      }

    } else {
      return { code: -100, msg: "当前用户不存在，请重新登录" };
    }
  }
  //查询阿里商标状态 用于补证
  async queryAliTmStatus(obj) {
    var rc = System.getObject("util.aliyunClient");
    try {
      if (!obj.methodType) {
        return { code: -1, message: "methodType不能为空", data: null };
      }
      if(obj.body && typeof(obj.body)=="string"){
        obj.body = JSON.parse(obj.body);
      }
      var submitTm = await rc.post(obj.methodType, obj.body);
      return { code: 200, message: "ok", data: submitTm };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "查询阿里商标状态异常---error",
        op: "base/api/impl/tmsub/queryAliTmStatus",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, message: "err", data: e.stack };
    }
  }
}
module.exports = TrademarkCtl;
// var task = new TrademarkCtl();
// task.getLastTradeMark({},{}).then(function(d){
//   console.log("dddddddddddddddd");
//   console.log(d);
// })
