daily-check-in.js 2.54 KB
/**
 * Created by qiujun on 2019/5/7.
 */
const _ = require('lodash');
const aes = require('../../../utils/aes');
const PARENT_TABLE_NAME = 'dailysignin';
const TABLE_NAME = PARENT_TABLE_NAME + ':activity'; // 签到活动表

class ActDailyCheckInModel extends global.yoho.BaseModel {
  constructor(ctx) {
    super(ctx);
    this.redis = global.yoho.redis;
    this.client = this.redis.client;
  }

  // 获取签到活动列表
  async activityList() {
    let length = await this.client.llenAsync(TABLE_NAME);

    return this.client.lrangeAsync(TABLE_NAME, 0, length - 1).then(acts => {
      let finalResult = [];

      acts.filter(act => act).map(act => {
        finalResult.unshift(JSON.parse(act)); // 向前插入,使数组倒序
      });
      return finalResult;

    });
  }

  // 创建签到活动
  async createActivity(data) {
    let length = await this.client.llenAsync(TABLE_NAME);

    data.id = length + 1;
    data.encryptedId = aes.encryptUid(length + 1);
    return this.client.rpushAsync(TABLE_NAME, JSON.stringify(data));
  }

  /**
   * 获取活动信息
   * @param actId
   * @returns {Promise.<void>}
   */
  async actInfo(actId) {
    let idx = parseInt(aes.decryptUid(actId), 10) - 1;

    if (idx) {
      return this.client.lrangeAsync(TABLE_NAME, idx, idx).then(act => {
        return JSON.parse(act[0] || {});
      });
    } else {
      return {
        code: 201,
        message: '无活动信息'
      };
    }
  }

  /**
   * 删除活动
   * @param id
   * @returns {Promise.<*>}
   */
  async actDelete(id) {
    id = parseInt(aes.decryptUid(id), 10);
    return this.client.lsetAsync(TABLE_NAME, id - 1, '');
  }

  /**
   * 获取中奖信息
   * @param id
   * @returns {Promise.<void>}
   */
  async getWinnerList(id) {
    if (id) {
      let actId = parseInt(aes.decryptUid(id), 10);

      let prizeListKey = `${PARENT_TABLE_NAME}:${actId}:prizelist`;
      let result = await this.client.zrevrangeAsync(prizeListKey, 0, -1);
      let finalResult = [];

      for (let i = 0; i < result.length; i++) {
        let ret = {};
        let prize = JSON.parse(result[i]);

        let uid = prize.uid;
        let userInfoKey = `${PARENT_TABLE_NAME}:${actId}:user:${uid}:info`;
        let userInfo = await this.client.zrangeAsync(userInfoKey, 0, 0);


        if (userInfo && userInfo.length > 0) {
          let phone = JSON.parse(userInfo[0]).phone;

          Object.assign(ret, prize, {phone: phone});
          finalResult.push(ret);
        }
      }

      return finalResult;
    }
  }

}

module.exports = ActDailyCheckInModel;