package com.ruoyi.ibs.custmap.service;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ibs.custmap.domain.dto.CustMapSearchDTO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author 吴凯程
 * @Date 2025/6/23
 **/
@Service
public class CustMapSearchService {

    private static final String CUST_MAP_SEARCH_KEY = "CUST_MAP_SEARCH_";
    @Resource
    private RedisCache redisCache;

    public String saveCustMapSearchTemplate(CustMapSearchDTO custMapSearchDTO) {
        String filePattern = CUST_MAP_SEARCH_KEY + SecurityUtils.getUsername() + "*";
        Collection<String> fileKeys = redisCache.keys(filePattern);
        if (StringUtils.isEmpty(custMapSearchDTO.getTemplateId()) && fileKeys.size() > 4 && !fileKeys.contains(CUST_MAP_SEARCH_KEY)) {
            throw new ServiceException("最多只能保存5个模板");
        }
        if (Objects.isNull(custMapSearchDTO.getTemplateId())) {
            custMapSearchDTO.setTemplateId(IdUtils.fastSimpleUUID());
        }
        String key = CUST_MAP_SEARCH_KEY + SecurityUtils.getUsername() + '_' + custMapSearchDTO.getTemplateId();
        custMapSearchDTO.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        custMapSearchDTO.setCreateTime(new Date());
        redisCache.setCacheObject(key, custMapSearchDTO);
        return "我的模板" + custMapSearchDTO.getTemplateName() + " 保存成功";
    }

    public List<CustMapSearchDTO> getCustMapSearchTemplate() {
        List<CustMapSearchDTO> collect = new ArrayList<>();
        // 根据通知的键和当前用户的用户名生成一个模式字符串，用于匹配通知的键
        String filePattern = CUST_MAP_SEARCH_KEY + SecurityUtils.getUsername()  + "*";
        // 从Redis缓存中获取匹配该模式的所有键
        Collection<String> fileKeys = redisCache.keys(filePattern);
        // 检查获取到的键集合是否为空，如果不为空，则进行进一步处理
        if (fileKeys != null && fileKeys.size() > 0) {
            // 使用流操作处理键集合，将每个键对应的值（通知对象）映射出来，并按读取状态排序
            for (String key : fileKeys) {
                // 从Redis缓存中获取键对应的值（通知对象）
                CustMapSearchDTO custMapSearchDTO = redisCache.getCacheObject(key);
                // 返回通知对象
                collect.add(custMapSearchDTO);
            }
        }
        return collect;
    }

    public String deleteCustMapSearchTemplate(String templateId) {
        String key = CUST_MAP_SEARCH_KEY + SecurityUtils.getUsername() + '_' + templateId;
        if (!redisCache.hasKey(key)) {
            throw new ServiceException("模板不存在");
        }
        redisCache.deleteObject(key);
        return "删除成功";
    }

}
