var System = require("../../system");
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");

class bytmmonitCtl {
  constructor() {
    this.cacheManager = System.getObject("db.cacheManager");
    this.bytmmonitSve = System.getObject("service.bytmmonitSve");
    this.bytmresultSve = System.getObject("service.bytmresultSve");
    this.bytmdynamicsSve = System.getObject("service.bytmdynamicsSve");
    this.wxSve = System.getObject("service.wxSve");
    this.bytmmonit = System.getObject("api.bytmmonit");
    this.gsbicsearch = System.getObject("api.gsbicsearch");
    this.redisClient = System.getObject("util.redisClient");
    this.appKey = "wx76a324c5d201d1a4";
    this.notifyAppKey = "wx4c91e81bbb6039cd";
  }
  universalTimeConvertShortDate(time) {
    if (time == null) {
      return "";
    }
    var d = new Date(time);
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
  }
  async addMonit(queryobj, qobj, req) {
    try {
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        return tResult;
      }
      return await this.bytmmonitSve.addMonit(qobj, tResult.user);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "添加标眼查商标监控Error:",
        op: "base/controller/impl/bytmmonitCtl/addMonit",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: null }
    }
  }
  async getMonitList(queryobj, qobj, req) {
    try {
      var resultData = {
        code: 1,
        total_count: 0,
        message: "success",
        data: []
      };
      var self = this;
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        return tResult;
      }
      var list = await this.bytmmonitSve.getMonitList(qobj, tResult.user.id);
      var tData = [];
      if (list && list.rows.length) {
        resultData.total_count = list.count;
        for (var i = 0; i < list.rows.length; i++) {
          var item = list.rows[i];
          if (item) {
            var queryData = JSON.parse(item.queryBuilder);
            var tmpObj = {
              monit_type_name: item.monitType == 1 ? "商标监控" : "代理机构监控",
              code: item.code,
              name: item.name,
              created_at: self.universalTimeConvertShortDate(item.created_at),
              tm_agency: queryData ? queryData.tm_agency : ""
            }
            tData.push(tmpObj);
          }
        }
      }
      resultData.data = tData;
      return resultData;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "获取标眼查商标监控列表Error",
        op: "base/controller/impl/bytmmonitCtl/getMonitList",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: null }
    }
  }
  //获取监控列表
  async getMonitListDetails(queryobj, qobj, req) {
    try {
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        return { code: -101, message: "用户信息有误", data: [] }
      }
      var tCode = qobj.code || "";
      if (!tCode || tCode == "undefined") {
        return { code: -102, message: "code参数有误", data: [] }
      }
      var item = await this.bytmmonitSve.dao.model.findOne({ where: { code: tCode } });
      if (!item || item == null) {
        return { code: -103, message: "code参数有误", data: [] }
      }
      if (item.queryBuilder == null || item.queryBuilder == "" || item.queryBuilder == "undefined") {
        return { code: -104, message: "code参数有误", data: [] }
      }
      var query = JSON.parse(item.queryBuilder);
      //处理查询的返回数据
      var total_type = Number(qobj.total_type || "-1");

      //": 10,
      query.page_size = qobj.page_size;
      //": 1,
      query.current_page = qobj.current_page;
      //请求类型,默认为1则请求商标es，2为请求商标动态监控es
      query.req_type = 1;
      query.appKey = this.appKey;
      //申请日期,-1为全部否则为选择对应的年份
      query.apply_year = qobj.apply_year;
      //":"-1",==法律状态,-1为全部,1:申请中；2:已初审；3:已注册；4:已无效  5-其他
      query.status = qobj.status;
      //":"01",	==申请日期,-1为全部否则为选择对应的大类
      query.ncl_one_codes = qobj.ncl_one_codes;
      //":"-1",==统计类型,-1为全部，1为可无效、2为可撤三、3可续展、4可宽展、5可异议
      query.total_type = qobj.total_type;
      //构建新条件
      query.monit_name = item.name;
      //构建是否是ddl查询
      query.ddl_query = qobj.ddl_query || -1;
      console.log("构建新条件...................................");
      console.log(query);

      //从数据库中查询数据
      var dbResult = await this.bytmresultSve.getTmMonitQueryByDb(tCode, total_type, query);
      if (dbResult.code == 1 && dbResult.data.length > 0) {
        return dbResult;
      }
      query.isVerify = -1;
      var result = await this.bytmmonit.getTmMonitList(query);
      // console.log("构建新条件................result...................");
      // console.log(result);
      //查询的数据保存到数据库
      this.queryDataSaveDb(tCode, item.queryBuilder, total_type, result, query);
      return result;

    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "获取标眼查商标监控列表Error",
        op: "base/controller/impl/bytmmonitCtl/getMonitListDetails",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: [] }
    }
  }
  //查询的数据保存到数据库--供getMonitListDetails方法使用
  async queryDataSaveDb(tCode, queryBuilder, total_type, result, query) {
    if (total_type && total_type != "undefined" && total_type != -1 && result.code == 1 && query.current_page == 1
      && query.apply_year == -1 && query.status == -1 && query.ncl_one_codes == "-1") {
      var queryAll = JSON.parse(queryBuilder);
      //请求类型,默认为1则请求商标es，2为请求商标动态监控es
      queryAll.req_type = 1;
      queryAll.appKey = this.appKey;
      //申请日期,-1为全部否则为选择对应的年份
      queryAll.apply_year = -1;
      //":"-1",==法律状态,-1为全部,1:申请中；2:已初审；3:已注册；4:已无效  5-其他
      queryAll.status = -1;
      //":"01",	==申请日期,-1为全部否则为选择对应的大类
      queryAll.ncl_one_codes = "-1";
      //":"-1",==统计类型,-1为全部，1为可无效、2为可撤三、3可续展、4可宽展、5可异议
      queryAll.total_type = total_type;
      queryAll.page_size = 500;
      var allListLength = 0;
      var addAllList = [];
      for (let index = 0; index < 2; index++) {
        queryAll.current_page = index + 1;
        queryAll.isVerify = -1;
        var resultPP = await this.bytmmonit.getShortTmMonitList(queryAll);
        // console.log(resultPP, "resultPP...........");
        if (resultPP.code == 1 && resultPP.data.length > 0) {
          allListLength = Array.prototype.push.apply(addAllList, resultPP.data);
        }
      }
      // console.log(allListLength,"_____________allListLength");

      if (allListLength > 0) {
        //添加返回值到DB
        this.bytmresultSve.addItem(tCode, total_type, addAllList);
      }
    }
  }

  async getCompanyInfo(queryobj, qobj, req) {
    var result = {
      code: 1,
      message: "success",
      data: null
    };
    try {
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        result.code = -101;
        result.message = "用户信息有误";
        return result;
      }
      var tCompanyName = qobj.company_name || "";
      if (!tCompanyName || tCompanyName == "undefined") {
        result.code = -102;
        result.message = "company_name参数有误";
        return result;
      }
      var query = { isVerify: -1, companyName: tCompanyName };
      var tResult = await this.gsbicsearch.companyonesearch(query);
      if (tResult.status == 0 && tResult.data.list.length > 0) {
        result.data = tResult.data.list[0];
      }
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "获取标眼查商标监控工商信息Error",
        op: "base/controller/impl/bytmmonitCtl/getCompanyInfo",
        content: e.stack,
        clientIp: req.clientIp
      });
      result.code = -200;
      result.message = "操作异常";
      return result;
    }
  }
  async getCompanyInfoNoUser(queryobj, qobj, req) {
    var result = {
      code: 1,
      message: "success",
      data: null
    };
    try {
      var tCompanyName = qobj.company_name || "";
      if (!tCompanyName || tCompanyName == "undefined") {
        result.code = -102;
        result.message = "company_name参数有误";
        return result;
      }
      var query = { isVerify: -1, companyName: tCompanyName };
      var tResult = await this.gsbicsearch.companyonesearch(query);
      console.log("------------------------------");
      console.log(tResult);
      if (tResult.status == 0 && tResult.data.list.length > 0) {
        result.data = tResult.data.list[0];
      }
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "获取标眼查商标监控工商信息Error",
        op: "base/controller/impl/bytmmonitCtl/getCompanyInfo",
        content: e.stack,
        clientIp: req.clientIp
      });
      result.code = -200;
      result.message = "操作异常";
      return result;
    }
  }
  async delMonit(queryobj, qobj, req) {
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    try {
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        result.code = -101;
        result.message = "用户信息有误";
        return result;
      }
      qobj.user_id = tResult.user.id;
      return await this.bytmmonitSve.delMonit(qobj, result);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "删除标眼查商标监控Error:",
        op: "base/controller/impl/bytmmonitCtl/delMonit",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: null }
    }
  }
  async delMonitDynamics(queryobj, qobj, req) {
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    try {
      var tResult = await this.isCheckUser(req);
      if (tResult.code != 1) {
        result.code = -101;
        result.message = "用户信息有误";
        return result;
      }
      qobj.user_id = tResult.user.id;
      return await this.bytmdynamicsSve.delMonitDynamics(qobj, result);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "删除标眼查商标监控动态Error:",
        op: "base/controller/impl/bytmmonitCtl/delMonitDynamics",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: null }
    }
  }
  async isCheckUser(req) {
    var result = {
      code: 1,
      message: "success",
      user: {},
    };
    var userInfo = req.session.user;
    if (userInfo == null || userInfo == "undefined") {
      result.code = -101;
      result.message = "用户登录异常";
      return result;
    }
    result.user = userInfo;
    return result;
  }
  //获取动态数量
  async getDynamicsCount(queryobj, qobj, req) {
    var tResult = await this.isCheckUser(req);
    if (tResult.code != 1) {
      return tResult;
    }
    var dysum = await this.bytmdynamicsSve.userSumByuserId(tResult.user.id);
    if (isNaN(dysum)) {
      dysum = 0;
    }
    var result = {
      code: 1,
      message: "success",
      data: { count: dysum }
    };
    if (tResult.user.notifyOpenId && tResult.user.notifyOpenId.length > 10) {
      result.is_show_notify = 1;
    } else {
      result.is_show_notify = 0;
    }
    return result;
  }
  //获取动态列表
  async getDynamicsList(queryobj, qobj, req) {
    var self = this;
    var user = req.session.user;
    var result = null;
    if (user == null) {
      result = {
        code: -200,
        message: "user is null",
        data: null
      };
    } else {
      var o = {
        pageInfo: { pageNo: qobj.current_page, pageSize: qobj.page_size },
        search: { user_id: user.id },
        orderInfo: [["created_at", 'desc']]
      }
      var dysum = await this.bytmdynamicsSve.findAndCountAll(o);
      result = {
        code: 1,
        total_count: dysum.results.count,
        message: "success",
        data: []
      };
      if (dysum.results.count > 0) {
        var info = dysum.results.rows;
        for (let i = 0; i < info.length; i++) {
          result.data.push({
            id: info[i].id,
            code: info[i].monitCode,
            name: info[i].monitName,
            num: info[i].dynamicsNum,
            created_at: self.formateTime(info[i].created_at)
          });
        }
      }
      this.bytmdynamicsSve.putReadByUserId(user.id);
    }
    return result;
  }
  formateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  }
  //代理机构监控列表
  async getMonitAgencyList(queryobj, qobj, req) {
    var agency_name = qobj.agency_name || "";
    var total_type = Number(qobj.total_type || "-1");
    var obj = {
      appKey: "wxe49ea352795cea4c",
      companyName: agency_name,
      type: total_type,
      isVerify: -1
    }
    var monitAgencyDataStr = await this.cacheManager["TmMonitAgencyQueryCache"].getListByCache(agency_name, total_type);
    if (monitAgencyDataStr && monitAgencyDataStr.length > 20) {
      var monitAgencyData = JSON.parse(monitAgencyDataStr);
      return { code: 1, msg: "操作成功", data: { list: monitAgencyData } };
    }
    //从es中查询
    var result = await this.bytmmonit.agencygetsearch(obj);
    if (result.code == 1 && result.data && result.data.list.length > 0) {
      var setMonitAgencyDataStr = JSON.stringify(result.data.list);
      this.cacheManager["TmMonitAgencyQueryCache"].setList(agency_name, total_type, setMonitAgencyDataStr);
    }
    return result;
  }

  async getAgencynfoByLikeName(oo, o, req) {
    var data = {
      isVerify: -1,
      pagesize: 5,
      page: 0,
      companyName: o.likestr,
    };
    var company = await this.gsbicsearch.agencynameonesearch(data);
    var names = [];
    company.data.list.forEach(a => {
      var source = {
        company_name: a._source.company_name
      }
      names.push(source);
    });
    if (company.status == 0 && company.data.totalSize > 0) {
      return { data: names };
    } else {
      return {};
    }

  }

  //代理机构监控列表
  async getMonitAgencyListSum(queryobj, qobj, req) {
    var obj = {
      appKey: "wxe49ea352795cea4c",
      companyName: qobj.agency_name,
      type: qobj.total_type,
      isVerify: -1
    }
    var result = await this.bytmmonit.agencygetsumsearch(obj)
    return result;
  }

  async notifyQrcode(queryobj, qobj, req) {
    var tResult = await this.isCheckUser(req);
    if (tResult.code != 1) {
      return tResult;
    }

    var key = "by_notify_" + tResult.user.id
    var qrcode = await this.redisClient.get(key);

    if (!qrcode) {
      qrcode = await this.wxSve.makeQrWithScene(this.notifyAppKey, tResult.user.id);
      this.redisClient.set(key, qrcode);
    }

    return { code: 1, data: qrcode };
  }
  async getCompanyMonitCode(queryobj, qobj, req) {
    try {
      var user = req.session.user;
      if (!user) {
        return { code: -100, msg: "用户没有登录" };
      }
      return await this.bytmmonitSve.getCompanyMonitCodeInfo(qobj, user);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "根据公司名称获取监控code异常Error:",
        op: "/igirl-web/app/base/controller/impl/bytmmonitCtl.js/getCompanyMonitCode",
        content: e.stack,
        clientIp: req.clientIp
      });
      return { code: -200, message: "操作异常", data: null }
    }
  }
}
module.exports = bytmmonitCtl;
