const system = require("../../system");
const ServiceBase = require("../sve.base");
class ByTmMonitService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(ByTmMonitService));
    this.bytmresultDao = system.getObject("db.bytmresultDao");
    this.bytmdynamicsDao = system.getObject("db.bytmdynamicsDao");
    this.bytmmonit = system.getObject("api.bytmmonit");
  }
  async  getCompanyMonitCodeInfo(params, userInfo) {
    var aueryBuilder = {
      "monit_type": 1,
      "name": "",
      "name_type": "",
      "ncl_type": ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45"],
      "tm_regist_num": "",
      "applicant_cn": params.company_name,
      "tm_agency": ""
    };
    var monit_code = await this.getUidInfo(3, 36) + "" + Date.now();
    var tempObj = {
      company_id: userInfo.company_id,
      user_id: userInfo.id,
      userName: userInfo.userName,
      nickName: userInfo.nickName,
      code: monit_code,
      monitType: 1,
      name: params.company_name + "，01类、02类、03等45个类别",
      queryBuilder: JSON.stringify(aueryBuilder)
    }
    var tmpItem = await this.dao.model.findOne({
      where: { name: tempObj.name, user_id: userInfo.id, monitType: 1 },
      attributes: ["code", "company_id"], raw: true
    });
    if (tmpItem) {
      return { code: 1, msg: "ok", data: { monit_code: tmpItem.code } }
    }
    await this.create(tempObj);
    return { code: 1, msg: "ok", data: { monit_code: monit_code } }
  }
  async delMonit(params, result) {
    var self = this;
    var user_id = params.user_id || "";
    var code_list = params.code_list || "";
    if (!code_list && code_list.length == 0) {
      result.code = -100;
      result.message = "code_list参数错误";
      return result;
    }
    if (!user_id) {
      result.code = -100;
      result.message = "user_id参数错误";
      return result;
    }
    await this.dao.model.destroy({ where: { user_id: user_id, code: { [this.db.Op.in]: code_list } } });
    return { code: 1, message: "success", data: {} }
  }
  async addMonit(params, userInfo) {
    var self = this;
    var monit_type = Number(params.monit_type || 1);
    params.monit_type = monit_type;
    var tempObj = {
      company_id: userInfo.company_id,
      user_id: userInfo.id,
      userName: userInfo.userName,
      nickName: userInfo.nickName,
      code: await self.getUidInfo(3, 36) + "" + Date.now(),
      monitType: params.monit_type,
      name: self.getNameInfo(params),
      queryBuilder: JSON.stringify(params)
    }
    var tmpItem = await super.findOne({ name: tempObj.name, user_id: userInfo.id });
    if (tmpItem) {
      return { code: -100, message: "监控已经存在，请勿重复添加！", data: {} }
    }
    await this.create(tempObj);
    return { code: 1, message: "success", data: {} }
  }
  getNameInfo(params) {
    var nameStr = "";
    if (params.monit_type == 1) {
      if (!params.name && params.ncl_type.length == 0 && !params.tm_regist_num && !params.applicant_cn) {
        return nameStr;
      }
      var tName = [];
      var nameTypeStr = this.getNameTypeStr(params.name, params.name_type);
      if (nameTypeStr) {
        tName.push(nameTypeStr);
      }
      if (params.tm_regist_num) {
        tName.push(params.tm_regist_num);
      }
      if (params.applicant_cn) {
        tName.push(params.applicant_cn);
      }
      var nclStr = this.getNclStr(params.ncl_type);
      if (nclStr) {
        tName.push(nclStr);
      }
      nameStr = tName.join("，");
    } else if (params.monit_type == 2) {
      if (params.tm_agency == null) {
        return nameStr;
      }
      nameStr = params.tm_agency
    }
    return nameStr;
  }
  getNameTypeStr(name, name_type) {
    var nameType = "";
    if (name) {
      nameType = name;
      switch (name_type) {
        case "1":
          nameType = nameType + "（相同）";
          break;
        case "2":
          nameType = nameType + "（相似）";
          break;
        case "3":
          nameType = nameType + "（相同+相似）";
          break;
        default:
          break;
      }
    }
    return nameType;
  }
  getNclStr(ncl_type) {
    if (!ncl_type || ncl_type.length == 0) {
      return ""
    }
    var tNclList = [];
    for (var i = 0; i < ncl_type.length; i++) {
      var tNcl = ncl_type[i];
      if (tNcl && i < 3) {
        tNclList.push(tNcl);
      }
      if (i == 3) {
        break;
      }
    }
    return ncl_type.length > 3 ? tNclList.join("类、") + "等" + ncl_type.length + "个类别" : tNclList.join("类、") + "类";
  }

  async getMonitList(params, user_id) {
    var monit_type = Number(params.monit_type || -1);
    var currentPage = Number(params.current_page || 1);
    var pageSize = Number(params.page_size || 10);
    if (currentPage < 1) {
      currentPage = 1;
    }
    if (pageSize > 50) {
      pageSize = 50;
    }
    var name = params.name || "";
    var whereObj = { user_id: user_id };
    if (monit_type && monit_type != -1) {
      whereObj.monitType = monit_type;
    }
    if (name && name != "undefined") {
      whereObj.name = { [this.dao.db.Op.like]: "%" + name + "%" };
    }
    var attributesObj = ["code", "name", "monitType", "queryBuilder", "created_at"];
    return await this.getPageList(currentPage, pageSize, whereObj, [["created_at", 'desc']], attributesObj);
  }

  async getMonitAll() {
    var sql = "select * from byc_bytm_monit bm join byc_bytm_result br on bm.code=br.monitCode";
    var allinfos = await this.dao.customQuery(sql);
    var self = this;
    var alluser = [];
    if (allinfos.length > 0) {
      for (var i = 0; i < allinfos.length; i++) {
        var obj = allinfos[i].queryBuilder;
        obj = JSON.parse(obj);
        var oldinfos = allinfos[i].resultData;
        oldinfos = JSON.parse(oldinfos);
        obj["req_type"] = 2;
        obj["total_type"] = allinfos[i].resultType;
        obj["ncl_type"] = null;
        obj["appKey"] = "wxe49ea352795cea4c";
        var infos1 = await self.bytmmonit.getTmMonitList(obj);
        var update_sum1 = 0;
        if (infos1.data.length > 0) {
          update_sum1 = infos1.data.length;
          for (var j = 0; j < infos1.data.length; j++) {
            var tm_num = infos1.data[j].tm_regist_num;
            if (oldinfos.findIndex(f => f.tm_regist_num == tm_num) > 0) {
              var infoindex = oldinfos.findIndex(f => f.tm_regist_num == tm_num);
              oldinfos[infoindex]["status"] = infos1.data[j]["status"];
              oldinfos[infoindex]["is_shadow"] = 1;
              oldinfos[infoindex]["op_time"] = parseInt((new Date()).getTime() / 1000);
            } else {
              var newinfo = {
                apply_year: infos1.data[j]["apply_year"],
                status: infos1.data[j]["status"],
                is_shadow: 1,
                op_time: parseInt((new Date()).getTime() / 1000),
                ncl_one_codes: infos1.data[j]["ncl_one_codes"],
                tm_regist_num: infos1.data[j]["tm_regist_num"],
                process_time: infos1.data[j]["process_time"]
              }
              oldinfos.push(newinfo);
            }
          }
        }
        if (update_sum1 > 0) {
          var oinfo = JSON.stringify(oldinfos);
          var update_info = {
            resultData: oinfo,
            nowNum: update_sum1
          }
          await self.bytmresultDao.model.update(update_info, { where: { id: allinfos[i].id } });
        }
        if (alluser.length == 0 || alluser.findIndex(f => f.monitCode == allinfos[i].monitCode) < 0) {
          allinfos[i]["dynamicsNum"] = update_sum1;
          alluser.push(allinfos[i]);
        } else {
          var alldyindex = alluser.findIndex(f => f.monitCode == allinfos[i].monitCode);
          alluser[alldyindex]["dynamicsNum"] = alluser[alldyindex]["dynamicsNum"] + update_sum1;
        }
      }
      var al = [];
      var version = parseInt((new Date()).getTime() / 1000 / 24 / 3600);
      var delsql = "select id from byc_bytm_dynamics where version='" + version + "'";
      var did = await self.dao.customQuery(delsql);
      var ids = [];
      did.forEach(a => {
        ids.push(a.id);
      });
      await self.bytmdynamicsDao.bulkDelete(ids);
      for (var k = 0; k < alluser.length; k++) {
        if (alluser[k].dynamicsNum > 0) {
          delete alluser[k].id;
          alluser[k]["monitName"] = alluser[k].name;
          alluser[k]["version"] = version;
          al.push(alluser[k]);
        }
        if (al.length > 100) {
          await self.bytmdynamicsDao.model.bulkCreate(al);
          al = [];
        }
      }
      if (al.length > 0) {
        await self.bytmdynamicsDao.model.bulkCreate(al);
      }
    }
  }
}
module.exports = ByTmMonitService;
