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

import cn.hutool.core.collection.CollUtil;
import com.bonus.canteen.core.cook.dto.CookRecipeDTO;
import com.bonus.canteen.core.cook.service.ICookRecipeService;
import com.bonus.canteen.core.cook.vo.CookRecipeDateVO;
import com.bonus.canteen.core.cook.vo.CookRecipeDetailVO;
import com.bonus.canteen.core.cook.vo.CookRecipeDishesVO;
import com.bonus.canteen.core.cook.vo.CookRecipeVO;
import com.bonus.canteen.core.order.domain.CookDishCheckDTO;
import com.bonus.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.*;

@Component
public class MenuModule {
    @Autowired
    private ICookRecipeService cookRecipeService;

    public Map<Long, List<CookRecipeDishesVO>> getMenuRecipeDish(CookDishCheckDTO cookDishCheckDTO) {
        CookRecipeDTO menurecipe = new CookRecipeDTO();
        menurecipe.setApplyDate(LocalDate.parse(cookDishCheckDTO.getApplyDate()));
        menurecipe.setCanteenId(cookDishCheckDTO.getCanteenId());
        menurecipe.setStallId(cookDishCheckDTO.getStallId());
        menurecipe.setKey(cookDishCheckDTO.getApplyType());
        Map<Long, List<CookRecipeDishesVO>> mealTimeTypeMap = new HashMap<>();
        List<CookRecipeVO> menuRecipeList = cookRecipeService.selectCookRecipeList4Current(menurecipe);
        if (CollUtil.isNotEmpty(menuRecipeList) && menuRecipeList.size() == 1) {
            List<CookRecipeDateVO> recipeDateList = menuRecipeList.get(0).getRecipeDateList();
            if(CollUtil.isNotEmpty(recipeDateList) && recipeDateList.size() == 1) {
                List<CookRecipeDetailVO> cookRecipeDetail = recipeDateList.get(0).getDetailList();
                if(CollUtil.isNotEmpty(cookRecipeDetail)) {
                    Long mealType = null;
                    List<CookRecipeDishesVO> dishsIdList = new ArrayList<>();
                    for (CookRecipeDetailVO cookRecipeDetailVO : cookRecipeDetail) {
                        mealType = cookRecipeDetailVO.getMealtimeType();
                        if(CollUtil.isNotEmpty(cookRecipeDetailVO.getDishesList())) {
                            dishsIdList.addAll(cookRecipeDetailVO.getDishesList());
                        }
                    }
                    if(Objects.nonNull(mealType)) {
                        mealTimeTypeMap.put(mealType, dishsIdList);
                    }
                }else {
                    throw new ServiceException("菜谱信息异常");
                }
            }else {
                throw new ServiceException("菜谱信息异常");
            }
        }else {
            throw new ServiceException("菜谱信息异常");
        }
        return mealTimeTypeMap;
    }
}
