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.*;
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.time.LocalDate;
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.selectOrderCartByCartId(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<>();
        }
        List<OrderCartVO> orderCartVOList = new ArrayList<>();
        for (OrderCart orderCart : orderCartList) {
            boolean filteredOrderDate = orderCartQueryParam.getMenuDateList().stream()
                    .anyMatch(menuDate -> LocalDate.parse(menuDate).equals(orderCart.getOrderDate()));
            OrderCartVO orderCartVO = new OrderCartVO();
            BeanUtils.copyProperties(orderCart, orderCartVO);
            orderCartVO.setIsValid(0);
            orderCartVOList.add(orderCartVO);
            if(!filteredOrderDate) {
                continue;
            }
            CookDishCheckDTO cookDishCheckDTO = new CookDishCheckDTO();
            cookDishCheckDTO.setApplyDate(orderCart.getOrderDate());
            cookDishCheckDTO.setCanteenId(orderCart.getCanteenId());
            cookDishCheckDTO.setStallId(orderCart.getStallId());
            cookDishCheckDTO.setApplyType(CookRecipeSortEnum.MOBILE_RESERVE.getKey());
            AllocRecipeStallVO allocRecipeStallVO = null;
            try{
                allocRecipeStallVO = menuModule.getMenuRecipeDish(cookDishCheckDTO);
            }catch (Exception ex) {
                log.error("菜单数据获取失败：{}", ex.getMessage(), ex);
                continue;
            }

            if(Objects.isNull(allocRecipeStallVO) || Objects.isNull(allocRecipeStallVO.getDetail())
                || CollUtil.isEmpty(allocRecipeStallVO.getDetail().getDetailList())) {
                continue;
            }
            if(!allocRecipeStallVO.getRecipeId().equals(orderCart.getRecipeId())) {
                continue;
            }
            List<CookRecipeDetailVO> cookRecipeDishList = allocRecipeStallVO.getDetail().getDetailList();
            outerLoop:
            for(CookRecipeDetailVO cookRecipeDish :cookRecipeDishList) {
                if(cookRecipeDish.getMealtimeType().equals(orderCart.getMealtimeType().longValue())) {
                    if(CollUtil.isNotEmpty(cookRecipeDish.getDishesList())) {
                        for (CookRecipeDishesVO cookRecipeDishesVO : cookRecipeDish.getDishesList()) {
                            if(cookRecipeDishesVO.getDishesId().equals(orderCart.getGoodsId())) {
                                orderCartVO.setIsValid(1);
                                break outerLoop;
                            }
                        }
                    }
                }
            }
        }
        return orderCartVOList;
    }

    /**
     * 新增订单购物车
     * 
     * @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.deleteOrderCartByCartIds(cartIds);
    }

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