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

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.account.service.impl.AccSubServiceImpl;
import com.bonus.canteen.core.common.utils.RedisUtil;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.menu.domain.MenuRecipeDetail;
import com.bonus.canteen.core.menu.mapper.MenuRecipeDetailMapper;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.houqin.constant.GlobalConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.menu.mapper.MenuRecipeDishesMapper;
import com.bonus.canteen.core.menu.domain.MenuRecipeDishes;
import com.bonus.canteen.core.menu.service.IMenuRecipeDishesService;

/**
 * 菜品计划菜品关联Service业务层处理
 *
 * @author xsheng
 * @date 2025-04-03
 */
@Service


public class MenuRecipeDishesServiceImpl extends ServiceImpl<MenuRecipeDishesMapper, MenuRecipeDishes> implements IMenuRecipeDishesService {

    private static final Logger log = LoggerFactory.getLogger(MenuRecipeDishesServiceImpl.class);
    @Autowired
    private MenuRecipeDishesMapper menuRecipeDishesMapper;

    /**
     * 查询菜品计划菜品关联
     *
     * @param id 菜品计划菜品关联主键
     * @return 菜品计划菜品关联
     */
    @Override
    public MenuRecipeDishes selectMenuRecipeDishesById(Long id) {
        return menuRecipeDishesMapper.selectMenuRecipeDishesById(id);
    }

    @Override
    public boolean saveBatch(Collection<MenuRecipeDishes> entityList) {
        Iterator var2 = CollUtil.split(entityList, 500).iterator();

        while(var2.hasNext()) {
            List<MenuRecipeDishes> menuRecipeDishes = (List)var2.next();
            menuRecipeDishesMapper.insertValues(menuRecipeDishes);
        }

        return true;
    }

    /**
     * 查询菜品计划菜品关联列表
     *
     * @param menuRecipeDishes 菜品计划菜品关联
     * @return 菜品计划菜品关联
     */
    @Override
    public List<MenuRecipeDishes> selectMenuRecipeDishesList(MenuRecipeDishes menuRecipeDishes) {
        return menuRecipeDishesMapper.selectMenuRecipeDishesList(menuRecipeDishes);
    }

    /**
     * 新增菜品计划菜品关联
     *
     * @param menuRecipeDishes 菜品计划菜品关联
     * @return 结果
     */
    @Override
    public int insertMenuRecipeDishes(MenuRecipeDishes menuRecipeDishes) {
        menuRecipeDishes.setCreateTime(LocalDateTime.now());
        try {
            return menuRecipeDishesMapper.insertMenuRecipeDishes(menuRecipeDishes);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 修改菜品计划菜品关联
     *
     * @param menuRecipeDishes 菜品计划菜品关联
     * @return 结果
     */
    @Override
    public int updateMenuRecipeDishes(MenuRecipeDishes menuRecipeDishes) {
        menuRecipeDishes.setUpdateTime(LocalDateTime.now());
        try {
            return menuRecipeDishesMapper.updateMenuRecipeDishes(menuRecipeDishes);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    @Override
    public int reduceMenuRecipeDishesSupplyNum(MenuRecipeDishes menuRecipeDishes, Integer quantity) {
        if(menuRecipeDishes == null || menuRecipeDishes.getDetailId() == null || menuRecipeDishes.getDishesId() == null) {
            throw new ServiceException("参数错误");
        }
        String lockKey = String.format("sc:menu_recipe_dishes_supply_num_tenant_%s_detailed_%s_dishes_id_%s",
                GlobalConstants.TENANT_ID, menuRecipeDishes.getDetailId(), menuRecipeDishes.getDishesId());
        try {
            if (!RedisUtil.tryLock(lockKey, 10, 15)) {
                throw new ServiceException("修改库存失败");
            }
            List<MenuRecipeDishes> menuRecipeDishesList = selectMenuRecipeDishesList(menuRecipeDishes);
            if (menuRecipeDishesList == null || menuRecipeDishesList.isEmpty()) {
                throw new ServiceException("菜品计划菜品关联不存在");
            }
            menuRecipeDishes = menuRecipeDishesList.get(0);
            if(menuRecipeDishes.getSurplusNum() < quantity) {
                throw new ServiceException("菜品供应量不足");
            }
            return menuRecipeDishesMapper.reduceMenuRecipeDishesSupplyNum(menuRecipeDishes, quantity);
        } catch (Exception e) {
            log.error("修改菜谱菜品供应量失败", e);
            throw new ServiceException("修改菜谱菜品供应量失败");
        }finally {
            try {
                RedisUtil.safeUnLock(lockKey);
            } catch (Exception ex) {
                log.error("账户操作解锁异常", ex);
            }
        }
    }

    @Override
    public int addMenuRecipeDishesSupplyNum(MenuRecipeDishes menuRecipeDishes, Integer quantity) {
        if(menuRecipeDishes == null || menuRecipeDishes.getDetailId() == null || menuRecipeDishes.getDishesId() == null) {
            throw new ServiceException("参数错误");
        }
        String lockKey = String.format("sc:menu_recipe_dishes_supply_num_tenant_%s_detailed_%s_dishes_id_%s",
                GlobalConstants.TENANT_ID, menuRecipeDishes.getDetailId(), menuRecipeDishes.getDishesId());
        try {
            if (!RedisUtil.tryLock(lockKey, 10, 15)) {
                throw new ServiceException("账户有交易正在进行中");
            }
            return menuRecipeDishesMapper.addMenuRecipeDishesSupplyNum(menuRecipeDishes, quantity);
        } catch (Exception e) {
            log.error("修改菜谱菜品供应量失败", e);
            throw new ServiceException("修改菜谱菜品供应量失败");
        }finally {
            try {
                RedisUtil.safeUnLock(lockKey);
            } catch (Exception ex) {
                log.error("账户操作解锁异常", ex);
            }
        }
    }

    /**
     * 批量删除菜品计划菜品关联
     *
     * @param ids 需要删除的菜品计划菜品关联主键
     * @return 结果
     */
    @Override
    public int deleteMenuRecipeDishesByIds(Long[] ids) {
        return menuRecipeDishesMapper.deleteMenuRecipeDishesByIds(ids);
    }

    /**
     * 删除菜品计划菜品关联信息
     *
     * @param id 菜品计划菜品关联主键
     * @return 结果
     */
    @Override
    public int deleteMenuRecipeDishesById(Long id) {
        return menuRecipeDishesMapper.deleteMenuRecipeDishesById(id);
    }

    @Override
    public Boolean deleteByDetailId(Long detailId) {
        return this.remove(Wrappers.lambdaQuery(MenuRecipeDishes.class)
                .eq(MenuRecipeDishes::getDetailId, detailId));
    }
}
