package com.jianshui.queue.utils;

import com.alibaba.fastjson.JSONObject;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.utils.RedisUtil;
import com.jianshui.queue.dto.RedisQueueMessage;
import redis.clients.jedis.Jedis;

/**
 * @Description redis队列的工具类，用法：RedisQueueUtil.build().setData(incomeCallback).onQueue(queueName).dispatch();
 * @Author 巩权林
 * @Date 2021-11-25 11:28
 **/
public class RedisQueueUtil {

    public static Builder build() {
        return new Builder();
    }

    // 根据消息，重新投递队列
    public static Builder reBuild(RedisQueueMessage msg) {
        Builder myBuilder = new Builder();
        return myBuilder.onQueue(msg.getQueueName()).retry(msg.getRetry()).setData(msg.getData());
    }

    public static class Builder {

        private String queueName;

        private Object data;

        private Integer retry = 0;

        public Builder() {

        }

        public Builder(Object data) {
            this.data = data;
        }

        public Builder onQueue(String queueName) {
            this.queueName = queueName;
            return this;
        }

        public Builder retry(int retry) {
            this.retry = retry;
            return this;
        }

        public Builder setData(Object data) {
            this.data = data;
            return this;
        }

        // 分发一把
        public AjaxResult dispatch() {
            return push(this.queueName, this.data, this.retry);
        }

        // 分发一把
        public AjaxResult dispatch(Object myData) {
            this.data = myData;
            return dispatch();
        }

        /**
         * 推送消息进队列
         *
         * @param queueName
         * @param data
         * @return
         */
        public static AjaxResult push(String queueName, Object data, Integer retry) {
            if (queueName == null) {
                return AjaxResult.error("队列名称不能为空！");
            }
            Jedis jedis = RedisUtil.getJedis();
            if (jedis == null) {
                return AjaxResult.error("获取Jedis失败！");
            }
            if (retry == null) {
                retry = 0;
            }

            // 构造请求体
            RedisQueueMessage msg = new RedisQueueMessage(data, retry);
            msg.setQueueName(queueName);

            jedis.lpush(queueName, JSONObject.toJSONString(msg));
            jedis.close();
            return AjaxResult.success();
        }

    }
}
