package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.vo.IdAndNameVO;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.manager.weathermanager.WeatherConstant;
import org.dromara.manager.weathermanager.WeatherManager;
import org.dromara.project.constant.BusProjectConstant;
import org.dromara.project.domain.BusContractor;
import org.dromara.project.domain.BusProject;
import org.dromara.project.domain.BusProjectFile;
import org.dromara.project.domain.BusUserProjectRelevancy;
import org.dromara.project.domain.dto.project.BusProjectCreateReq;
import org.dromara.project.domain.dto.project.BusProjectQueryReq;
import org.dromara.project.domain.dto.project.BusProjectUpdateReq;
import org.dromara.project.domain.vo.project.BusProjectContractorListVo;
import org.dromara.project.domain.vo.project.BusProjectSafetyDayVo;
import org.dromara.project.domain.vo.project.BusProjectVo;
import org.dromara.project.domain.vo.project.BusProjectWeatherVo;
import org.dromara.project.mapper.BusProjectMapper;
import org.dromara.project.service.IBusContractorService;
import org.dromara.project.service.IBusProjectFileService;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusUserProjectRelevancyService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 项目Service业务层处理
 *
 * @author lcj
 * @date 2025-03-04
 */
@Service
public class BusProjectServiceImpl extends ServiceImpl<BusProjectMapper, BusProject>
    implements IBusProjectService {

    @Lazy
    @Resource
    private IBusUserProjectRelevancyService userProjectRelevancyService;

    @Lazy
    @Resource
    private IBusContractorService contractorService;

    @Lazy
    @Resource
    private IBusProjectFileService projectFileService;

    @Resource
    private WeatherManager weatherManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final Cache<String, String> WEATHER_CACHE =
        Caffeine.newBuilder().initialCapacity(1024)
            .maximumSize(10000L)
            // 缓存 60 分钟移除
            .expireAfterWrite(60L, TimeUnit.MINUTES)
            .build();

    /**
     * 查询项目
     *
     * @param id 主键
     * @return 项目
     */
    @Override
    public BusProjectVo queryById(Long id) {
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(project);
    }

    /**
     * 分页查询项目列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 项目分页列表
     */
    @Override
    public TableDataInfo<BusProjectVo> queryPageList(BusProjectQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusProject> result = this.page(pageQuery.build(), this.buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的项目列表
     *
     * @param req 查询条件
     * @return 项目列表
     */
    @Override
    public List<BusProjectVo> queryList(BusProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = this.buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 查询当前登录用户项目列表以及项目列表下的分包公司列表
     *
     * @return 项目列表以及项目列表下的分包公司列表
     */
    @Override
    public List<BusProjectContractorListVo> queryProjectContractorList() {
        Long userId = LoginHelper.getUserId();
        // 获取当前登录用户的项目列表
        LambdaQueryWrapper<BusUserProjectRelevancy> userProjectRelevancyLqw = Wrappers.lambdaQuery(BusUserProjectRelevancy.class)
            .select(BusUserProjectRelevancy::getProjectId)
            .eq(BusUserProjectRelevancy::getUserId, userId);
        List<Long> projectIdList = userProjectRelevancyService.listObjs(userProjectRelevancyLqw, obj -> (Long) obj);
        List<BusProject> projectList = this.listByIds(projectIdList);
        // 获取项目列表下的分包公司列表
        LambdaQueryWrapper<BusContractor> lqw = new LambdaQueryWrapper<>();
        lqw.in(BusContractor::getProjectId, projectIdList);
        Map<Long, List<BusContractor>> projectIdContractorList = contractorService.list(lqw).stream()
            .collect(Collectors.groupingBy(BusContractor::getProjectId));
        // 获取封装
        return projectList.stream().map(project -> {
            BusProjectContractorListVo projectContractorListResp = new BusProjectContractorListVo();
            // 添加项目信息
            projectContractorListResp.setId(project.getId());
            projectContractorListResp.setProjectName(project.getProjectName());
            // 获取分包公司列表
            List<BusContractor> contractorList = projectIdContractorList.get(project.getId());
            if (CollUtil.isEmpty(contractorList)) {
                throw new ServiceException("项目：" + project.getProjectName() + "下无分包单位，请创建后再进行操作", HttpStatus.BAD_REQUEST);
            }
            List<IdAndNameVO> idAndNameVOS = contractorList.stream()
                .map(contractor -> IdAndNameVO.build(contractor.getId(), contractor.getName())).toList();
            projectContractorListResp.setContractorList(idAndNameVOS);
            return projectContractorListResp;
        }).toList();
    }

    /**
     * 新增项目
     *
     * @param req 项目
     * @return 新项目 id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertByBo(BusProjectCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        String playCardStart = req.getPlayCardStart();
        String playCardEnd = req.getPlayCardEnd();
        String punchRange = playCardStart + "," + playCardEnd;
        project.setPunchRange(punchRange);
        // 数据校验
        validEntityBeforeSave(project, true);
        Long count = this.lambdaQuery().eq(BusProject::getProjectName, req.getProjectName()).count();
        if (count > 0) {
            throw new ServiceException("项目名称已存在", HttpStatus.BAD_REQUEST);
        }
        // 写入数据库
        boolean save = this.save(project);
        if (!save) {
            throw new ServiceException("新增项目失败，数据库异常", HttpStatus.ERROR);
        }
        Long projectId = project.getId();
        Long userId = LoginHelper.getUserId();
        // 同步保存用户与项目关联
        Set<Long> userIdList = new HashSet<>(List.of(userId, SystemConstants.SUPER_ADMIN_ID));
        List<BusUserProjectRelevancy> userProjectRelevancyList = userIdList.stream().map(id -> {
            BusUserProjectRelevancy userProjectRelevancy = new BusUserProjectRelevancy();
            userProjectRelevancy.setUserId(id);
            userProjectRelevancy.setProjectId(projectId);
            return userProjectRelevancy;
        }).toList();
        boolean saveRelevancy = userProjectRelevancyService.saveBatch(userProjectRelevancyList);
        if (!saveRelevancy) {
            throw new ServiceException("新增用户与项目关联失败，数据库异常", HttpStatus.ERROR);
        }
        // 返回新写入的数据 projectId
        return projectId;
    }

    /**
     * 修改项目
     *
     * @param req 项目
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BusProjectUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusProject project = new BusProject();
        BeanUtils.copyProperties(req, project);
        String playCardStart = req.getPlayCardStart();
        String playCardEnd = req.getPlayCardEnd();
        if (StringUtils.isNotBlank(playCardStart) && StringUtils.isNotBlank(playCardEnd)) {
            String punchRange = playCardStart + "," + playCardEnd;
            project.setPunchRange(punchRange);
        }
        // 数据校验
        validEntityBeforeSave(project, false);
        // 权限校验
        Long userId = LoginHelper.getUserId();
        validAuth(project.getId(), userId);
        // 判断是否存在
        BusProject oldProject = this.getById(project.getId());
        if (oldProject == null) {
            throw new ServiceException("修改项目失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 判断名称是否重复
        if (req.getProjectName() != null && !req.getProjectName().equals(oldProject.getProjectName())) {
            Long count = this.lambdaQuery().eq(BusProject::getProjectName, req.getProjectName()).count();
            if (count > 0) {
                throw new ServiceException("项目名称重复", HttpStatus.BAD_REQUEST);
            }
        }
        // 操作数据库
        return this.updateById(project);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusProject entity, Boolean create) {
        // TODO 做一些数据校验,如唯一约束
        String projectName = entity.getProjectName();
        String principalPhone = entity.getPrincipalPhone();
        // 新增项目参数验证
        if (create) {
            if (StringUtils.isBlank(projectName)) {
                throw new ServiceException("项目名称不能为空", HttpStatus.BAD_REQUEST);
            }
            if (StringUtils.isBlank(principalPhone)) {
                throw new ServiceException("负责人电话不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (StringUtils.isNotBlank(principalPhone) && !PhoneUtil.isPhone(principalPhone)) {
            throw new ServiceException("负责人手机号格式不正确", HttpStatus.BAD_REQUEST);
        }
    }

    /**
     * 校验并批量删除项目信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
            this.validAuth(ids, userId);
        }
        // 删除项目
        boolean removeProjectList = this.removeBatchByIds(ids);
        if (!removeProjectList) {
            throw new ServiceException("删除项目失败，数据库异常", HttpStatus.ERROR);
        }
        // 删除用户与项目关联表
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("project_id", ids);
        boolean removeRelevancyList = userProjectRelevancyService.remove(queryWrapper);
        if (!removeRelevancyList) {
            throw new ServiceException("删除项目与用户关联失败，数据库异常", HttpStatus.ERROR);
        }
        return true;
    }

    /**
     * 获取项目视图对象
     *
     * @param project 项目对象
     * @return 项目视图对象
     */
    @Override
    public BusProjectVo getVo(BusProject project) {
        if (project == null) {
            return null;
        }
        // 对象转封装类
        BusProjectVo projectVo = new BusProjectVo();
        BeanUtils.copyProperties(project, projectVo);
        String punchRange = project.getPunchRange();
        if (StringUtils.isNotBlank(punchRange)) {
            String[] split = punchRange.split(",");
            projectVo.setPlayCardStart(split[0]);
            projectVo.setPlayCardEnd(split[1]);
        }
        // 关联设计id
        BusProjectFile projectFile = projectFileService.lambdaQuery()
            .eq(BusProjectFile::getProjectId, project.getId())
            .one();
        if (projectFile != null) {
            projectVo.setDesignId(projectFile.getId());
        }
        return projectVo;
    }

    /**
     * 获取项目查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusProject> buildQueryWrapper(BusProjectQueryReq req) {
        LambdaQueryWrapper<BusProject> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String projectName = req.getProjectName();
        String shortName = req.getShortName();
        Long pId = req.getPId();
        String status = req.getStatus();
        String remark = req.getRemark();
        String projectType = req.getProjectType();
        String projectCategory = req.getProjectCategory();
        String projectSite = req.getProjectSite();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String actual = req.getActual();
        String plan = req.getPlan();
        String onStreamTime = req.getOnStreamTime();
        String punchRange = req.getPunchRange();
        Long designTotal = req.getDesignTotal();
        String showHidden = req.getShowHidden();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(projectName), BusProject::getProjectName, projectName);
        lqw.like(StringUtils.isNotBlank(shortName), BusProject::getShortName, shortName);
        lqw.like(StringUtils.isNotBlank(remark), BusProject::getRemark, remark);
        lqw.like(StringUtils.isNotBlank(projectSite), BusProject::getProjectSite, projectSite);
        lqw.like(StringUtils.isNotBlank(principal), BusProject::getPrincipal, principal);
        lqw.like(StringUtils.isNotBlank(principalPhone), BusProject::getPrincipalPhone, principalPhone);
        lqw.like(StringUtils.isNotBlank(actual), BusProject::getActual, actual);
        lqw.like(StringUtils.isNotBlank(plan), BusProject::getPlan, plan);
        lqw.like(StringUtils.isNotBlank(onStreamTime), BusProject::getOnStreamTime, onStreamTime);
        lqw.like(StringUtils.isNotBlank(punchRange), BusProject::getPunchRange, punchRange);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(pId), BusProject::getPId, pId);
        lqw.eq(ObjectUtils.isNotEmpty(status), BusProject::getStatus, status);
        lqw.eq(ObjectUtils.isNotEmpty(id), BusProject::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectType), BusProject::getProjectType, projectType);
        lqw.eq(ObjectUtils.isNotEmpty(projectCategory), BusProject::getProjectCategory, projectCategory);
        lqw.eq(ObjectUtils.isNotEmpty(designTotal), BusProject::getDesignTotal, designTotal);
        lqw.eq(ObjectUtils.isNotEmpty(showHidden), BusProject::getShowHidden, showHidden);
        lqw.orderByAsc(BusProject::getSort);
        return lqw;
    }


    @Override
    public Page<BusProjectVo> getVoPage(Page<BusProject> projectPage) {
        List<BusProject> projectList = projectPage.getRecords();
        Page<BusProjectVo> projectVoPage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());
        if (CollUtil.isEmpty(projectList)) {
            return projectVoPage;
        }
        // 获取项目文件id
        Set<Long> projectIdList = projectList.stream().map(BusProject::getId).collect(Collectors.toSet());
        Map<Long, List<BusProjectFile>> projectFileMap = projectFileService.lambdaQuery()
            .in(BusProjectFile::getProjectId, projectIdList).list()
            .stream().collect(Collectors.groupingBy(BusProjectFile::getProjectId));
        // 对象列表 => 封装对象列表
        List<BusProjectVo> projectVoList = projectList.stream().map(project -> {
            // 对象转封装类
            BusProjectVo projectVo = new BusProjectVo();
            BeanUtils.copyProperties(project, projectVo);
            String punchRange = project.getPunchRange();
            if (StringUtils.isNotBlank(punchRange)) {
                String[] split = punchRange.split(",");
                projectVo.setPlayCardStart(split[0]);
                projectVo.setPlayCardEnd(split[1]);
            }
            // 关联设计id
            List<BusProjectFile> projectFileList = projectFileMap.get(project.getId());
            if (CollUtil.isNotEmpty(projectFileList)) {
                projectVo.setDesignId(projectFileList.getFirst().getId());
            }
            return projectVo;
        }).toList();
        projectVoPage.setRecords(projectVoList);
        return projectVoPage;
    }

    /**
     * 校验用户是否拥有操作项目的权限
     *
     * @param projectId 项目对象
     * @param userId    需要鉴权的用户id
     */
    @Override
    public void validAuth(Long projectId, Long userId) {
        QueryWrapper<BusUserProjectRelevancy> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        queryWrapper.eq("user_id", userId);
        if (userProjectRelevancyService.count(queryWrapper) <= 0) {
            throw new ServiceException("当前用户无该项目权限操作", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 校验用户是否拥有操作项目的权限
     *
     * @param projectIdList 项目id列表
     * @param userId        需要鉴权的用户id
     */
    @Override
    public void validAuth(Collection<Long> projectIdList, Long userId) {
        // 查询关联表，返回和用户关联的项目ID列表
        Set<Long> collect = userProjectRelevancyService.listObjs(
            new LambdaQueryWrapper<BusUserProjectRelevancy>()
                .select(BusUserProjectRelevancy::getProjectId)
                .in(BusUserProjectRelevancy::getProjectId, projectIdList)
                .eq(BusUserProjectRelevancy::getUserId, userId)
                .groupBy(BusUserProjectRelevancy::getProjectId)
        ).stream().map(obj -> (Long) obj).collect(Collectors.toSet());
        // 找出没有关联数据的项目ID
        List<Long> invalidIds = projectIdList.stream()
            .filter(id -> !collect.contains(id))
            .toList();
        if (!invalidIds.isEmpty()) {
            throw new ServiceException("操作失败，项目编号为：" + invalidIds + "，没有操作权限", HttpStatus.FORBIDDEN);
        }
    }

    /**
     * 获取天气信息
     *
     * @param id 项目id
     * @return 天气信息列表
     */
    @Override
    public List<BusProjectWeatherVo> getWeather(Long id) {
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("项目不存在");
        }
        // 构建缓存 key
        String cacheKey = String.format("%s:%s", BusProjectConstant.PROJECT_WEATHER_LIST_VO_REDIS_KEY_PREFIX, id);
        // 查询本地缓存（caffeine）
        String cachedValue = WEATHER_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            // 如果缓存命中，返回结果
            return JSONUtil.toList(cachedValue, BusProjectWeatherVo.class);
        }
        // 查询分布式缓存（Redis）
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        cachedValue = valueOps.get(cacheKey);
        if (cachedValue != null) {
            // 如果命中Redis，存入本地缓存并返回结果
            WEATHER_CACHE.put(cacheKey, cachedValue);
            return JSONUtil.toList(cachedValue, BusProjectWeatherVo.class);
        }
        // 获取当天及之后的天气信息
        String lng = project.getLng();
        String lat = project.getLat();
        if (StringUtils.isAnyBlank(lng, lat)) {
            throw new ServiceException("项目坐标信息为空");
        }
        String weatherStr = weatherManager.getWeather(lng, lat, WeatherConstant.THREE_DAYS_WEATHER_PATH);
        // 解析为 JSONObject
        JSONObject weatherJson = JSONUtil.parseObj(weatherStr);
        // 获取 daily 数组
        JSONArray dailyArray = weatherJson.getJSONArray(WeatherConstant.DAILY);
        // 循环遍历，封装项目天气信息
        List<BusProjectWeatherVo> weatherList = new ArrayList<>();
        for (int i = 0; i < dailyArray.size(); i++) {
            JSONObject day = dailyArray.getJSONObject(i);
            BusProjectWeatherVo weatherVo = new BusProjectWeatherVo();
            // 获取星期
            String dateStr = day.getStr(WeatherConstant.FX_DATE);
            DateTime date = DateUtil.parse(dateStr, "yyyy-MM-dd");
            String week = DateUtil.format(date, "EEE");
            // 获取天气图标
            String textDay = day.getStr(WeatherConstant.TEXT_DAY);
            String textNight = day.getStr(WeatherConstant.TEXT_NIGHT);
            Map<String, List<String>> weatherStatusMap = WeatherConstant.getWeatherStatusMap();
            String dayStatus = getWeatherCategory(textDay, weatherStatusMap);
            String nightStatus = getWeatherCategory(textNight, weatherStatusMap);
            // 封装数据
            weatherVo.setDate(dateStr);
            weatherVo.setWeek(week);
            weatherVo.setTempMax(day.getStr(WeatherConstant.TEMP_MAX));
            weatherVo.setTempMin(day.getStr(WeatherConstant.TEMP_MIN));
            weatherVo.setSunRise(day.getStr(WeatherConstant.SUN_RISE));
            weatherVo.setSunSet(day.getStr(WeatherConstant.SUN_SET));
            weatherVo.setDayStatus(textDay);
            weatherVo.setNightStatus(textNight);
            weatherVo.setDayIcon(dayStatus);
            weatherVo.setNightIcon(nightStatus);
            weatherList.add(weatherVo);
        }
        // 更新缓存
        String cacheValue = JSONUtil.toJsonStr(weatherList);
        // 更新本地缓存
        WEATHER_CACHE.put(cacheKey, cacheValue);
        // 更新 Redis 缓存，设置 5 - 10 分钟随机过期，防止雪崩
        int cacheExpireTime = 60 * 60 + RandomUtil.randomInt(0, 300);
        valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
        // 返回结果
        return weatherList;
    }

    /**
     * 获取项目安全天数
     *
     * @param id 项目id
     * @return 安全天数
     */
    @Override
    public BusProjectSafetyDayVo getSafetyDay(Long id) {
        // 构建缓存 key
        String cacheKey = String.format("%s:%s", BusProjectConstant.PROJECT_SAFETY_DAYS_REDIS_KEY_PREFIX, id);
        // 查询分布式缓存（Redis）
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        String cachedValue = valueOps.get(cacheKey);
        if (cachedValue != null) {
            // 如果命中Redis，返回结果
            return JSONUtil.toBean(cachedValue, BusProjectSafetyDayVo.class);
        }
        BusProject project = this.getById(id);
        if (project == null) {
            throw new ServiceException("项目信息不存在", HttpStatus.NOT_FOUND);
        }
        int days = DateUtils.differentDaysByMillisecond(project.getCreateTime(), new Date());
        BusProjectSafetyDayVo safetyDayVo = new BusProjectSafetyDayVo();
        safetyDayVo.setSafetyDay(days);
        // 更新缓存
        String cacheValue = JSONUtil.toJsonStr(safetyDayVo);
        // 更新 Redis 缓存
        int cacheExpireTime = 12;
        valueOps.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.HOURS);
        // 返回结果
        return safetyDayVo;
    }

    /**
     * 根据天气图标获取天气类别
     *
     * @param icon 天气图标
     * @param map  天气图标与天气类别的映射关系
     * @return 天气类别
     */
    public static String getWeatherCategory(String icon, Map<String, List<String>> map) {
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            if (entry.getValue().contains(icon)) {
                return entry.getKey();
            }
        }
        return "cloudy";
    }

}
