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

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.alloc.domain.*;
import com.bonus.canteen.core.alloc.mapper.AllocStallMapper;
import com.bonus.canteen.core.alloc.service.IAllocCanteenService;
import com.bonus.canteen.core.menu.domain.MenuRecipe;
import com.bonus.canteen.core.menu.dto.AppletReserveRecipeDTO;
import com.bonus.canteen.core.menu.mapper.MenuRecipeMapper;
import com.bonus.canteen.core.menu.service.IMenuAppRecipeService;
import com.bonus.canteen.core.menu.vo.AppletReserveRecipeDishesVO;
import com.bonus.canteen.core.menu.vo.AppletReserveRecipeTypeVO;
import com.bonus.canteen.core.menu.vo.AppletReserveRecipeVO;
import com.bonus.canteen.core.utils.BnsConstants;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.menu.mapper.MenuAppRecipeMapper;
import com.bonus.canteen.core.menu.domain.MenuAppRecipe;

/**
 * 移动端菜谱绑定关系Service业务层处理
 *
 * @author xsheng
 * @date 2025-04-03
 */
@Service
@Slf4j
public class MenuAppRecipeServiceImpl implements IMenuAppRecipeService {
    @Autowired
    private MenuAppRecipeMapper menuAppRecipeMapper;
    @Autowired
    AllocStallMapper allocStallMapper;
    @Autowired
    IAllocCanteenService allocCanteenService;

    /**
     * 查询移动端菜谱绑定关系
     *
     * @param id 移动端菜谱绑定关系主键
     * @return 移动端菜谱绑定关系
     */
    @Override
    public MenuAppRecipe selectMenuAppRecipeById(Long id) {
        return menuAppRecipeMapper.selectMenuAppRecipeById(id);
    }

    /**
     * 查询移动端菜谱绑定关系列表
     *
     * @param menuAppRecipe 移动端菜谱绑定关系
     * @return 移动端菜谱绑定关系
     */
    @Override
    public List<MenuAppRecipe> selectMenuAppRecipeList(MenuAppRecipe menuAppRecipe) {
        return menuAppRecipeMapper.selectMenuAppRecipeList(menuAppRecipe);
    }

    /**
     * 新增移动端菜谱绑定关系
     *
     * @param menuAppRecipe 移动端菜谱绑定关系
     * @return 结果
     */
    @Override
    public int insertMenuAppRecipe(MenuAppRecipe menuAppRecipe) {
        menuAppRecipe.setCreateTime(LocalDateTime.now());
        try {
            return menuAppRecipeMapper.insertMenuAppRecipe(menuAppRecipe);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 修改移动端菜谱绑定关系
     *
     * @param menuAppRecipe 移动端菜谱绑定关系
     * @return 结果
     */
    @Override
    public int updateMenuAppRecipe(MenuAppRecipe menuAppRecipe) {
        menuAppRecipe.setUpdateTime(LocalDateTime.now());
        try {
            return menuAppRecipeMapper.updateMenuAppRecipe(menuAppRecipe);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量删除移动端菜谱绑定关系
     *
     * @param ids 需要删除的移动端菜谱绑定关系主键
     * @return 结果
     */
    @Override
    public int deleteMenuAppRecipeByIds(Long[] ids) {
        return menuAppRecipeMapper.deleteMenuAppRecipeByIds(ids);
    }

    /**
     * 删除移动端菜谱绑定关系信息
     *
     * @param id 移动端菜谱绑定关系主键
     * @return 结果
     */
    @Override
    public int deleteMenuAppRecipeById(Long id) {
        return menuAppRecipeMapper.deleteMenuAppRecipeById(id);
    }

    @Override
    public List<AppletReserveCanteenVO> getReserveMealCanteenList() {
        List<AppletReserveCanteenVO> resultList = this.menuAppRecipeMapper.selectReserveMealCanteenList();
        if (ObjectUtil.isEmpty(resultList)) {
            return resultList;
        } else {
            //this.allocCanteenService.checkAndDelReserveCanteen(resultList);
            List<Long> stallIdList = (List)resultList.stream().flatMap((canteen) -> {
                return canteen.getStallList().stream().map(AppletReserveStallVO::getStallId);
            }).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(stallIdList)) {
                List<MenuStallSaleModel> stallMonthSalesList = this.menuAppRecipeMapper.selectMonthSalesStall(stallIdList);
                Map<Long, Integer> stallSaleMap = (Map)stallMonthSalesList.stream().collect(Collectors.toMap(MenuStallSaleModel::getStallId, MenuStallSaleModel::getMonthlySales));
                resultList.forEach((canteen) -> {
                    List<AppletReserveStallVO> stallList = canteen.getStallList();
                    if (ObjectUtil.isNotEmpty(stallList)) {
                        stallList.forEach((stall) -> {
                            stall.setMonthlySales((Integer)stallSaleMap.get(stall.getStallId()));
                        });
                    }
                });
            }
            return resultList;
        }
    }

    @Override
    public List<LocalDate> listReserveDate(AllocMobileCanteenQueryDTO queryDTO) {
        return this.listMatchData(queryDTO.getReserveLimitDayNum(), queryDTO.getIfAllowReserveToday());
    }

    private List<LocalDate> listMatchData(Integer reserveLimitDayNum, String ifAllowReserveToday) {
        log.info(String.format("查询日期,天数:%d", reserveLimitDayNum));
        List<LocalDate> reserveDateList = new ArrayList();
        LocalDate startDate;
        if (BnsConstants.COMMON_YES.equals(ifAllowReserveToday)) {
            log.info("允许预定当天");
            startDate = LocalDate.now();
        } else {
            log.info("不允许预定当天");
            startDate = LocalDate.now().plusDays(1L);
        }

        for(int i = 0; i < reserveLimitDayNum; ++i) {
            reserveDateList.add(startDate.plusDays((long)i));
        }

        return reserveDateList;
    }

    @Override
    public List<AppletReserveRecipeVO> getReserveRecipeDetailList(AppletReserveRecipeDTO content) {
        List<AppletReserveRecipeVO> resultList = menuAppRecipeMapper.selectReserveRecipe(content.getApplyDate(), content.getRecipeId());
        if (ObjectUtil.isEmpty(resultList)) {
            return resultList;
        } else {
            resultList.sort(Collections.reverseOrder((s1, s2) -> {
                return s2.getMealtimeType() - s1.getMealtimeType();
            }));
            Long stallId = menuAppRecipeMapper.selectStallIdByWrappers(Wrappers.lambdaQuery(MenuRecipe.class).eq(MenuRecipe::getRecipeId, content.getRecipeId()));
            List<AllocStallMealtime> allocStallMealtimes = allocStallMapper.selectMealtimeByStallId(stallId);
            List<AllocStallMealtime> mealTimeList = allocStallMealtimes;
            log.info("配置api查询的档口餐次,档口id: {}, 配置: {}", stallId, JSON.toJSONString(mealTimeList));
            if (ObjectUtil.isEmpty(mealTimeList)) {
                log.info("未获取到开启餐次");
                return Lists.newArrayList();
            } else {
                if (LocalDate.now().isEqual(content.getApplyDate())) {
                    mealTimeList = mealTimeList.stream().filter((time) -> {
                        return LocalTime.now().isBefore(time.getStartTime());
                    }).collect(Collectors.toList());
                }

                if (ObjectUtil.isEmpty(mealTimeList)) {
                    log.info("未获取到餐次");
                    return Lists.newArrayList();
                } else {
                    List<AllocStallMealtime> finalMealTimeList = mealTimeList;
                    resultList = resultList.stream().filter((time) -> {
                        return finalMealTimeList.stream().map(AllocStallMealtime::getMealtimeType).collect(Collectors.toList()).contains(time.getMealtimeType());
                    }).collect(Collectors.toList());
                    return resultList;
                }
            }
        }
    }


}
