package com.skr.mdm.handle;

import cn.hutool.core.util.IdUtil;
import com.skr.mdm.dao.AuCompanyDao;
import com.skr.mdm.entity.AuCompanyDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.RedisGetKeyUtil;
import com.skr.mdm.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 下载计数器
 * @author nfq
 * @date 2023-01-17 16:18
 */
@Component
@Slf4j
public class DownloadCounterHandler {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AuCompanyDao companyDao;

    /**
     * 自增
     * @param companyId
     * @param equipmentId
     */
    public synchronized ResponseResult increment(Integer companyId, Integer equipmentId) {
        log.info("设备：{} 请求下载", equipmentId);
        if (redisUtils.get(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId)) == null) {
            log.info("下载计数器未初始化");
            return ResponseResult.failure("下载计数器未初始化");
        }
        int maxDownloadCount = Integer.parseInt(redisUtils.get(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId)).toString());
        Set<String> keys = redisUtils.scanKeys(RedisGetKeyUtil.DOWNLOAD_TOKEN_KEY + companyId);
        if (keys.size() >= maxDownloadCount) {
            log.warn("下载请求超出最大下载数限制 当前下载数:{} 最大下载数{}", keys.size(), maxDownloadCount);
            return ResponseResult.failure("下载队列已满，请稍后再试！");
        }
        String snowflakeId = IdUtil.getSnowflakeNextIdStr();
        redisUtils.set(RedisGetKeyUtil.getUserDownloadKey(companyId, equipmentId, snowflakeId), System.currentTimeMillis(), 60 * 60);
        log.info("设备：{} 请求下载成功accessToken：{}", equipmentId, snowflakeId);
        return ResponseResult.success(snowflakeId);
    }

    /**
     * 计数器自减
     * @param companyId
     * @param equipmentId
     * @return
     */

    public synchronized boolean decrease(Integer companyId, Integer equipmentId, String accessToken) {
        try {
            log.info("设备：{} 下载完成 accessToken:{}", equipmentId, accessToken);
            if (redisUtils.hasKey(RedisGetKeyUtil.getUserDownloadKey(companyId, equipmentId, accessToken))) {
                redisUtils.del(RedisGetKeyUtil.getUserDownloadKey(companyId, equipmentId, accessToken));
                return true;
            }
            log.warn("设备：{} accessToken已过期:{}", equipmentId, accessToken);
            return true;
        } catch (Exception e) {
            log.error("下载计数器自减异常：" + equipmentId, e);
        }
        return false;
    }

    /**
     * 初始化公司下载计数器
     * @param companyId
     */
    public synchronized void initCompanyDownloadCounter(Integer companyId) {
        // 如果下载计数器缓存过期或没有初始化的情况，进行初始化
        if (!redisUtils.hasKey(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId))) {
            AuCompanyDO companyDO = companyDao.selectById(companyId);
            if (companyDO.getMaxDownloadNum() == 0) {
                companyDO.setMaxDownloadNum(10);
            }
            redisUtils.set(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId), companyDO.getMaxDownloadNum(), 60 * 60 * 24);
            log.info("公司下载计数器初始化 公司ID：{} 最大下载数：{}", companyId, companyDO.getMaxDownloadNum());
        }
    }

    /**
     * 设置最大下载数
     * @param companyId
     * @param downLoadCount
     */
    public void update(Integer companyId, Integer downLoadCount) {
        if (redisUtils.hasKey(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId))) {
            redisUtils.set(RedisGetKeyUtil.getCompanyDownloadCounterKey(companyId), downLoadCount, 60 * 60 * 24);
            log.info("设置redis公司下载计数器 公司：{} maxDownloadCount：{}", companyId, downLoadCount);
            return;
        }
        log.info("redis公司下载计数器不存在，等待初始化：{}", companyId);
    }
}
