package com.ruoyi.wx.web.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.RecycleEnum;
import com.ruoyi.framework.recovery.domain.RecStall;
import com.ruoyi.framework.recovery.domain.RecStallCategory;
import com.ruoyi.framework.recovery.mapper.RecStallCategoryMapper;
import com.ruoyi.framework.recovery.mapper.RecStallMapper;
import com.ruoyi.wx.web.domain.dto.RecycleDto;
import com.ruoyi.wx.web.domain.vo.RecycleVo;
import com.ruoyi.wx.web.service.IWxRecycleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WxRecycleServiceImpl implements IWxRecycleService {
    @Autowired
    private RecStallCategoryMapper stallCategoryMapper;

    @Autowired
    private RecStallMapper stallMapper;

    @Override
    public AjaxResult getIndex() {
        return AjaxResult.success(stallCategoryMapper.selectRecStallCategoryList(new RecStallCategory()));
    }

    @Override
    public List<RecycleVo> getInfoList(Long id) {
        RecStall recStall = new RecStall();
        recStall.setCategoryId(id);
        // 查询所有内容
        List<RecStall> recStalls = stallMapper.selectRecStallListByCategoryId(recStall);
        // 查询最小城市Id
        Map<Integer, Map> minCityMap = stallMapper.selectMinCityId();
        Map<Integer, List<RecStall>> stallMap = recStalls.stream().collect(Collectors.groupingBy(RecStall::getTradeType));
        Map<Integer, List<RecStall>> filteredStallMap = new HashMap<>();
        stallMap.forEach((key, value) -> {
            if (key != 1) {
                Long minCityId = (Long) minCityMap.get(key).get("cityId");
                List<RecStall> result = value.stream().filter(vo -> vo.getCityId().equals(String.valueOf(minCityId))).toList();
                filteredStallMap.put(key, result);
            }
            filteredStallMap.put(key, value);
        });
        List<RecycleVo> list = new ArrayList<>();
        filteredStallMap.forEach((key, value) -> {
            RecycleVo recycleVo = new RecycleVo();
            recycleVo.setTradeType(key);
            recycleVo.setTradeName(RecycleEnum.getValueByCode(key));
            recycleVo.setRecStallList(value);
            list.add(recycleVo);
        });
        return list;
    }

    @Override
    public List<RecStall> getCityRecycle(RecycleDto recycleDto) {
        RecStall recStall = new RecStall();
        recStall.setCategoryId(recycleDto.getCategoryId());
        recStall.setCityId(recycleDto.getCityId());
        recStall.setTradeType(recycleDto.getTradeType());
        return stallMapper.selectRecStallListByCategoryId(recStall);
    }
}
