package com.qiaoba.common.redis.service.impl;


import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.constant.TenantConstant;
import com.qiaoba.common.base.context.BaseContext;
import com.qiaoba.common.base.entity.BasePage;
import com.qiaoba.common.redis.service.RedisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 自定义Redis接口实现类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/2 0003 下午 17:44
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RedisServiceImpl implements RedisService {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(addTenantPrefix(key), value, time, TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(addTenantPrefix(key), value);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(addTenantPrefix(key));
    }

    @Override
    public Boolean del(String key) {
        return redisTemplate.delete(addTenantPrefix(key));
    }

    @Override
    public void del(Collection<String> keys) {
        List<String> list = keys.stream().map(key -> key = addTenantPrefix(key)).collect(Collectors.toList());
        redisTemplate.delete(list);
    }

    @Override
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(addTenantPrefix(key), TimeUnit.SECONDS);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(addTenantPrefix(key));
    }

    @Override
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(addTenantPrefix(key), delta);
    }

    @Override
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(addTenantPrefix(key), -delta);
    }

    @Override
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(addTenantPrefix(key), hashKey);
    }

    @Override
    public Boolean hSet(String key, String hashKey, Object value, long time) {
        String newKey = addTenantPrefix(key);
        redisTemplate.opsForHash().put(newKey, hashKey, value);
        return expire(newKey, time);
    }

    @Override
    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(addTenantPrefix(key), hashKey, value);
    }

    @Override
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(addTenantPrefix(key));
    }

    @Override
    public Long hSize(String key) {
        return redisTemplate.opsForHash().size(addTenantPrefix(key));
    }

    @Override
    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
        String newKey = addTenantPrefix(key);
        redisTemplate.opsForHash().putAll(newKey, map);
        return expire(newKey, time);
    }

    @Override
    public void hSetAll(String key, Map<String, ?> map) {
        redisTemplate.opsForHash().putAll(addTenantPrefix(key), map);
    }

    @Override
    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(addTenantPrefix(key), hashKey);
    }

    @Override
    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(addTenantPrefix(key), hashKey);
    }

    @Override
    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(addTenantPrefix(key), hashKey, delta);
    }

    @Override
    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(addTenantPrefix(key), hashKey, -delta);
    }

    @Override
    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(addTenantPrefix(key));
    }

    @Override
    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(addTenantPrefix(key), values);
    }

    @Override
    public Long sAdd(String key, long time, Object... values) {
        String newKey = addTenantPrefix(key);
        Long count = redisTemplate.opsForSet().add(newKey, values);
        expire(newKey, time);
        return count;
    }

    @Override
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(addTenantPrefix(key), value);
    }

    @Override
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(addTenantPrefix(key));
    }

    @Override
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(addTenantPrefix(key), values);
    }

    @Override
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(addTenantPrefix(key), start, end);
    }

    @Override
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(addTenantPrefix(key));
    }

    @Override
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(addTenantPrefix(key), index);
    }

    @Override
    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(addTenantPrefix(key), value);
    }

    @Override
    public Long lPush(String key, Object value, long time) {
        String newKey = addTenantPrefix(key);
        Long index = redisTemplate.opsForList().rightPush(newKey, value);
        expire(newKey, time);
        return index;
    }

    @Override
    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(addTenantPrefix(key), values);
    }

    @Override
    public Long lPushAll(String key, Long time, Object... values) {
        String newKey = addTenantPrefix(key);
        Long count = redisTemplate.opsForList().rightPushAll(newKey, values);
        expire(newKey, time);
        return count;
    }

    @Override
    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(addTenantPrefix(key), count, value);
    }

    @Override
    @SuppressWarnings("unchecked")
    public BasePage getPageList(String key, long pageNumber, long pageSize) {
        //获取数据总量
        Long totalCount = redisTemplate.opsForSet().size(key);
        if (Objects.isNull(totalCount)) {
            return new BasePage(new ArrayList(), 0);
        }
        //获取当前要取分页数据的游标位置
        long start = (pageNumber - 1) * pageSize;
        long end = start + pageSize - 1;
        //获取当前页分页数据
        List<Object> list = redisTemplate.opsForList().range(key, start, end);
        return new BasePage(list, totalCount);
    }


    @Override
    public Collection<String> getKeys(String key) {
        return redisTemplate.keys(addTenantPrefix(key));
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getObject(String key, Class<T> clazz) {
        return (T) get(key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> List<T> getObjectList(String key, Class<T> clazz) {
        return (List<T>) get(key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T hGetObject(String key, String hashKey, Class<T> clazz) {
        return (T) hGet(key, hashKey);
    }

    @Override
    public String addTenantPrefix(String key) {
        StringBuilder sb = new StringBuilder();
        sb.append(TenantConstant.TENANT_KEY_PREFIX).append(BaseContext.getTenantId()).append(BaseConstant.COLON_JOIN_STR).append(key);
        log.debug("拼接后的RedisKey: {}", sb.toString());
        return sb.toString();
    }

    @Override
    public String removeTenantPrefix(String key) {
        StringBuilder sb = new StringBuilder();
        sb.append(TenantConstant.TENANT_KEY_PREFIX).append(BaseContext.getTenantId()).append(BaseConstant.COLON_JOIN_STR);
        log.debug("去除拼接后的RedisKey: {}", key.replace(sb.toString(), ""));
        return key.replace(sb.toString(), "");
    }
}
