package com.bonus.canteen.core.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.bonus.canteen.core.cook.enums.CookRecipeSortEnum;
import com.bonus.canteen.core.cook.vo.CookRecipeDishesVO;
import com.bonus.canteen.core.order.domain.CookDishCheckDTO;
import com.bonus.canteen.core.order.domain.OrderCart;
import com.bonus.canteen.core.order.domain.param.OrderCartQueryParam;
import com.bonus.canteen.core.order.domain.vo.OrderCartVO;
import com.bonus.canteen.core.order.mapper.OrderCartMapper;
import com.bonus.canteen.core.order.module.MenuModule;
import com.bonus.canteen.core.order.service.IOrderCartService;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 订单购物车Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-14
 */
@Service
public class OrderCartServiceImpl implements IOrderCartService
{
    private static final Logger log = LoggerFactory.getLogger(OrderCartServiceImpl.class);

    @Autowired
    private OrderCartMapper orderCartMapper;
    @Autowired
    private MenuModule menuModule;

    /**
     * 查询订单购物车
     * 
     * @param cartId 订单购物车主键
     * @return 订单购物车
     */
    @Override
    public OrderCart selectOrderCartByCartId(Long cartId)
    {
        return orderCartMapper.selectOrderCartByShoppingCartId(cartId);
    }

    /**
     * 查询订单购物车列表
     * 
     * @param orderCartQueryParam 订单购物车
     * @return 订单购物车
     */
    @Override
    public List<OrderCartVO> selectOrderCartList(OrderCartQueryParam orderCartQueryParam) {
        OrderCart orderCartQuery = new OrderCart();
        orderCartQuery.setCanteenId(orderCartQueryParam.getCanteenId());
        orderCartQuery.setStallId(orderCartQueryParam.getStallId());
        orderCartQuery.setOrderType(orderCartQueryParam.getOrderType());
        orderCartQuery.setUserId(orderCartQueryParam.getUserId());
        List<OrderCart> orderCartList = orderCartMapper.selectOrderCartList(orderCartQuery);
        if (CollUtil.isEmpty(orderCartList)) {
            return new ArrayList<>();
        }

        CookDishCheckDTO cookDishCheckDTO = new CookDishCheckDTO();
        cookDishCheckDTO.setCanteenId(orderCartQueryParam.getCanteenId());
        cookDishCheckDTO.setStallId(orderCartQueryParam.getStallId());
        cookDishCheckDTO.setApplyType(CookRecipeSortEnum.MOBILE_RESERVE.getKey());

        Map<String, List<OrderCart>> groupedByOrderDate = orderCartList.stream()
                .collect(Collectors.groupingBy(cart -> DateUtil.format(cart.getOrderDate(), "yyyy-MM-dd")));

        List<OrderCartVO> orderCartVOList = new ArrayList<>();

        for (Map.Entry<String, List<OrderCart>> entry : groupedByOrderDate.entrySet()) {
            String orderDateStr = entry.getKey();
            List<OrderCart> carts = entry.getValue();
            String filteredOrderDate = orderCartQueryParam.getMenuDateList().stream().filter(orderDate -> orderDate.equals(orderDateStr))
                    .findFirst().orElse(null);

            cookDishCheckDTO.setApplyDate(orderDateStr);
            Map<Long, List<CookRecipeDishesVO>> cookRecipeDishMap = new HashMap<>();
            try{
                cookRecipeDishMap = menuModule.getMenuRecipeDish(cookDishCheckDTO);
            }catch (Exception ex) {
                log.info("菜单数据获取失败：" + ex.getMessage());
            }

            for (OrderCart shoppingCart : carts) {
                OrderCartVO shoppingCartVO = convertToOrderCartVO(shoppingCart, cookRecipeDishMap);
                if(filteredOrderDate == null) {
                    shoppingCartVO.setIsValid(0);
                }
                orderCartVOList.add(shoppingCartVO);
            }
        }

        return orderCartVOList;
    }

    private OrderCartVO convertToOrderCartVO(OrderCart shoppingCart,
                                             Map<Long, List<CookRecipeDishesVO>> cookRecipeDishMap) {
        OrderCartVO shoppingCartVO = new OrderCartVO();
        BeanUtils.copyProperties(shoppingCart, shoppingCartVO);
        shoppingCartVO.setIsValid(0);

        List<CookRecipeDishesVO> cookRecipeDishes = cookRecipeDishMap.get(shoppingCart.getMealtimeType().longValue());
        if (CollUtil.isNotEmpty(cookRecipeDishes)) {
            for (CookRecipeDishesVO cookRecipeDishesVO : cookRecipeDishes) {
                if (shoppingCart.getGoodsId().equals(cookRecipeDishesVO.getDishesId())) {
                    shoppingCartVO.setIsValid(1);
                    break;
                }
            }
        }

        return shoppingCartVO;
    }


    /**
     * 新增订单购物车
     * 
     * @param orderCart 订单购物车
     * @return 结果
     */
    @Override
    public int insertOrderCart(OrderCart orderCart)
    {
        if(Objects.nonNull(orderCart.getCartId())) {
            return updateOrderCart(orderCart);
        }else {
            orderCart.setCreateBy(SecurityUtils.getUsername());
            orderCart.setUpdateBy(SecurityUtils.getUsername());
            return orderCartMapper.insertOrderCart(orderCart);
        }
    }

    /**
     * 修改订单购物车
     * 
     * @param orderCart 订单购物车
     * @return 结果
     */
    @Override
    public int updateOrderCart(OrderCart orderCart)
    {
        orderCart.setUpdateTime(DateUtils.getNowDate());
        orderCart.setUpdateTime(DateUtils.getNowDate());
        return orderCartMapper.updateOrderCart(orderCart);
    }

    /**
     * 批量删除订单购物车
     * 
     * @param cartIds 需要删除的订单购物车主键
     * @return 结果
     */
    @Override
    public int deleteOrderCartByCartIds(List<Long> cartIds)
    {
        return orderCartMapper.deleteOrderCartByShoppingCartIds(cartIds);
    }

    /**
     * 删除订单购物车信息
     * 
     * @param cartId 订单购物车主键
     * @return 结果
     */
    @Override
    public int deleteOrderCartByCartId(Long cartId)
    {
        return orderCartMapper.deleteOrderCartByShoppingCartId(cartId);
    }
}
