package com.bonus.canteen.core.order.module;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.bonus.canteen.core.menu.domain.MenuRecipe;
import com.bonus.canteen.core.menu.enums.MenuRecipeSortEnum;
import com.bonus.canteen.core.menu.service.IMenuRecipeService;
import com.bonus.canteen.core.menu.vo.MenuRecipeDetailsVO;
import com.bonus.canteen.core.menu.vo.MenuRecipeDishesVO;
import com.bonus.canteen.core.menu.vo.MenuRecipeMealtimeTypeVO;
import com.bonus.canteen.core.menu.vo.MenuRecipeVO;
import com.bonus.canteen.core.order.domain.MenuDishCheckDTO;
import com.bonus.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class MenuModule {
    @Autowired
    private IMenuRecipeService menuRecipeService;

    public Map<Integer, List<MenuRecipeDishesVO>> getMenuRecipeDish(MenuDishCheckDTO menuDishCheckDTO) {
        MenuRecipe menuRecipe = new MenuRecipe();
        menuRecipe.setApplyDate(menuDishCheckDTO.getApplyDate());
        menuRecipe.setCanteenId(menuDishCheckDTO.getCanteenId());
        menuRecipe.setStallId(menuDishCheckDTO.getStallId());
        menuRecipe.setKey(menuDishCheckDTO.getApplyType());
        Map<Integer, List<MenuRecipeDishesVO>> mealTimeTypeMap = new HashMap<>();
        List<MenuRecipeVO> menuRecipeList = menuRecipeService.selectMenuRecipeList(menuRecipe);
        if (CollUtil.isNotEmpty(menuRecipeList) && menuRecipeList.size() == 1) {
            List<MenuRecipeDetailsVO> menuRecipeDetailsVOList = menuRecipeList.get(0).getDetail();
            if(CollUtil.isNotEmpty(menuRecipeDetailsVOList) && menuRecipeDetailsVOList.size() == 1) {
                List<MenuRecipeMealtimeTypeVO> menuRecipeMealtimeTypeVOS = menuRecipeDetailsVOList.get(0).getDetails();
                if(CollUtil.isNotEmpty(menuRecipeMealtimeTypeVOS)) {
                    Integer mealType = null;
                    List<MenuRecipeDishesVO> dishsIdList = new ArrayList<>();
                    for (MenuRecipeMealtimeTypeVO menuRecipeMealtimeTypeVO : menuRecipeMealtimeTypeVOS) {
                        mealType = menuRecipeMealtimeTypeVO.getMealtimeType();
                        if(CollUtil.isNotEmpty(menuRecipeMealtimeTypeVO.getDishesList())) {
                            dishsIdList.addAll(menuRecipeMealtimeTypeVO.getDishesList());
                        }
                    }
                    if(Objects.nonNull(mealType)) {
                        mealTimeTypeMap.put(mealType, dishsIdList);
                    }
                }else {
                    throw new ServiceException("菜谱信息异常");
                }
            }else {
                throw new ServiceException("菜谱信息异常");
            }
        }else {
            throw new ServiceException("菜谱信息异常");
        }
        return mealTimeTypeMap;
    }
}
