const system = require("../system");
// const redis = require("redis");
const settings = require("../../config/settings");
// const bluebird = require("bluebird");
// bluebird.promisifyAll(redis);
const redisClient = system.getObject("util.redisClient");

// const logCtl=system.getObject("web.oplogCtl");
class DownContractClient {
  constructor() {
    this.DOWNLOAD_KEY = "bpo:contract:download";
    this.KEY = "DOWN_LOAD_CONTRACT_KEY";
    this.sve = {
      e: system.getObject("service.econtractSve"),
      dk: system.getObject("service.dkcontractSve"),
      ent: system.getObject("service.entcontractSve"),
    }
  }

  async donloadContract() {
    // 定时器执行服务，这个简单加锁就够用
    let v = await redisClient.get(this.KEY);
    if (v) {
      return;
    }
    try {
      await redisClient.setWithEx(this.KEY, 123, 60 * 5);
      await this.doDownLoad();
      redisClient.delete(this.KEY);
    } catch (e) {
      console.log(e);
      redisClient.delete(this.KEY);
    }
  }

  async doDownLoad() {
    let len = await redisClient.llen(this.DOWNLOAD_KEY) || 0;
    if (!len) {
      redisClient.delete(this.KEY);
      return;
    }
    for (let i = 0; i < len; i++) {
      let item = await redisClient.rpop(this.DOWNLOAD_KEY);
      console.log(item);
      item = JSON.parse(item);
      try {
        await this.sve[item.sve].downloadContract(item.id);
      } catch (e) {
        console.log(e);
      }
      console.log(item);
    }
  }
}

module.exports = DownContractClient;
