package com.ruoyi.ibs.custmap.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.custmap.domain.dto.CustMapFavoriteDTO;
import com.ruoyi.ibs.custmap.domain.entity.CustMapFavorite;
import com.ruoyi.ibs.custmap.domain.vo.CustMapVO;
import com.ruoyi.ibs.custmap.domain.vo.FavoriteCountVO;
import com.ruoyi.ibs.custmap.domain.vo.FavoriteVO;
import com.ruoyi.ibs.custmap.mapper.CustMapFavoriteMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2025/5/23
 **/
@Service
public class CustMapFavoriteService {

    @Resource
    private CustMapFavoriteMapper custMapFavoriteMapper;

    public String updateFavorite(Long radarId){
        LambdaQueryWrapper<CustMapFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustMapFavorite::getUserName, SecurityUtils.getUsername())
                .eq(CustMapFavorite::getRadarId, radarId);
        CustMapFavorite custMapFavorite = custMapFavoriteMapper.selectOne(queryWrapper);
        if (Objects.isNull(custMapFavorite)){
            CustMapFavorite custMapFavoriteVO = new CustMapFavorite();
            custMapFavoriteVO.setUserName(SecurityUtils.getUsername());
            custMapFavoriteVO.setRadarId(radarId);
            custMapFavoriteMapper.insert(custMapFavoriteVO);
            return "添加收藏成功";
        }
        custMapFavoriteMapper.deleteById(custMapFavorite);
        return "移除收藏成功";
    }

    public FavoriteVO getFavoriteCountByUser(){
        FavoriteVO favoriteVO = new FavoriteVO();
        Long countTotal = 0L;
        List<FavoriteCountVO> cityWktList = custMapFavoriteMapper.getCityWktList();
        List<FavoriteCountVO> favoriteCountVOS = custMapFavoriteMapper.countFavoriteCustMap(SecurityUtils.getUsername());
        for (FavoriteCountVO favoriteCityVO : cityWktList) {
            FavoriteCountVO favoriteCountVO = favoriteCountVOS.stream()
                    .filter(item -> Objects.nonNull(item.getCity()) && item.getCity().equals(favoriteCityVO.getCity()))
                    .findFirst().orElse(null);
            if (Objects.nonNull(favoriteCountVO)){
                favoriteCityVO.setCountFavorite(favoriteCountVO.getCountFavorite());
                countTotal += favoriteCountVO.getCountFavorite();
            }
        }
        favoriteVO.setFavoriteList(cityWktList);
        favoriteVO.setFavoriteTotal(countTotal);
        return favoriteVO;
    }

    public List<CustMapVO> selectCustListByFavorite(CustMapFavoriteDTO custMapFavoriteDTO){
        custMapFavoriteDTO.setUserName(SecurityUtils.getUsername());
        return custMapFavoriteMapper.getFavoriteCustList(custMapFavoriteDTO);
    }




}
