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

import java.util.List;

import com.bonus.canteen.core.common.utils.RedisUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.houqin.constant.GlobalConstants;
import com.bonus.common.houqin.utils.JacksonUtil;
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.cook.mapper.CookRecipeDishesMapper;
import com.bonus.canteen.core.cook.domain.CookRecipeDishes;
import com.bonus.canteen.core.cook.service.ICookRecipeDishesService;

/**
 * 菜品计划菜品关联Service业务层处理
 * 
 * @author xsheng
 * @date 2025-05-25
 */
@Service
public class CookRecipeDishesServiceImpl implements ICookRecipeDishesService {
    private static final Logger log = LoggerFactory.getLogger(CookRecipeDishesServiceImpl.class);

    @Autowired
    private CookRecipeDishesMapper cookRecipeDishesMapper;

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

    /**
     * 查询菜品计划菜品关联列表
     * 
     * @param cookRecipeDishes 菜品计划菜品关联
     * @return 菜品计划菜品关联
     */
    @Override
    public List<CookRecipeDishes> selectCookRecipeDishesList(CookRecipeDishes cookRecipeDishes) {
        return cookRecipeDishesMapper.selectCookRecipeDishesList(cookRecipeDishes);
    }

    /**
     * 新增菜品计划菜品关联
     * 
     * @param cookRecipeDishes 菜品计划菜品关联
     * @return 结果
     */
    @Override
    public int insertCookRecipeDishes(CookRecipeDishes cookRecipeDishes) {
        cookRecipeDishes.setCreateTime(DateUtils.getNowDate());
        try {
            return cookRecipeDishesMapper.insertCookRecipeDishes(cookRecipeDishes);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 修改菜品计划菜品关联
     * 
     * @param cookRecipeDishes 菜品计划菜品关联
     * @return 结果
     */
    @Override
    public int updateCookRecipeDishes(CookRecipeDishes cookRecipeDishes) {
        cookRecipeDishes.setUpdateTime(DateUtils.getNowDate());
        try {
            return cookRecipeDishesMapper.updateCookRecipeDishes(cookRecipeDishes);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

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

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

    @Override
    public int reduceMenuRecipeDishesSupplyNum(CookRecipeDishes cookRecipeDishes, Integer quantity) {
        log.info("扣减库存入参：{}，数量：{}", JacksonUtil.writeValueAsString(cookRecipeDishes), quantity);
        if(cookRecipeDishes == null || cookRecipeDishes.getRecipeDetailId() == null || cookRecipeDishes.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, cookRecipeDishes.getRecipeDetailId(), cookRecipeDishes.getDishesId());
        try {
            if (!RedisUtil.tryLock(lockKey, 10, 15)) {
                throw new ServiceException("修改库存失败");
            }
            List<CookRecipeDishes> menuRecipeDishesList = selectCookRecipeDishesList(cookRecipeDishes);
            if (menuRecipeDishesList == null || menuRecipeDishesList.isEmpty()) {
                throw new ServiceException("菜品计划菜品关联不存在");
            }
            cookRecipeDishes = menuRecipeDishesList.get(0);
            if(cookRecipeDishes.getRemanentNum() < quantity) {
                throw new ServiceException("菜品供应量不足");
            }
            return cookRecipeDishesMapper.reduceCookRecipeDishesSupplyNum(cookRecipeDishes, 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(CookRecipeDishes cookRecipeDishes, Integer quantity) {
        log.info("新增库存入参：{}，数量：{}", JacksonUtil.writeValueAsString(cookRecipeDishes), quantity);
        if(cookRecipeDishes == null || cookRecipeDishes.getRecipeDetailId() == null || cookRecipeDishes.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, cookRecipeDishes.getRecipeDetailId(), cookRecipeDishes.getDishesId());
        try {
            if (!RedisUtil.tryLock(lockKey, 10, 15)) {
                throw new ServiceException("账户有交易正在进行中");
            }
            return cookRecipeDishesMapper.addCookRecipeDishesSupplyNum(cookRecipeDishes, quantity);
        } catch (Exception e) {
            log.error("修改菜谱菜品供应量失败", e);
            throw new ServiceException("修改菜谱菜品供应量失败");
        }finally {
            try {
                RedisUtil.safeUnLock(lockKey);
            } catch (Exception ex) {
                log.error("账户操作解锁异常", ex);
            }
        }
    }
}
