package com.jeesharp.business.modules.food.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.food.entity.FoodMealRule;
import com.jeesharp.business.modules.food.mapper.FoodMealRuleMapper;
import com.jeesharp.business.modules.food.service.FoodMealRuleService;
import com.jeesharp.business.modules.food.vo.FoodMealRuleQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import com.jeesharp.framework.exception.BizErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
@Transactional(readOnly = true)
public class FoodMealRuleServiceImpl extends CrudService<FoodMealRuleMapper, FoodMealRule, FoodMealRuleQueryVO> implements FoodMealRuleService {

    private static final String IDS_SEPARATOR = ",";
    private static final String RULE_NOT_FOUND_MESSAGE = "订餐规则不存在";
    private static final String DEL_NORMAL = "0";
    private static final int STATUS_ENABLED = 1;

    @Override
    @Transactional(readOnly = false)
    public void createRule(FoodMealRule entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateRule(FoodMealRule entity) {
        if (StrUtil.isBlank(entity.getId()) || get(entity.getId()) == null) {
            throw new BizErrorException(RULE_NOT_FOUND_MESSAGE);
        }
        update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateStatus(String id, Integer status) {
        FoodMealRule current = get(id);
        if (current == null) {
            throw new BizErrorException(RULE_NOT_FOUND_MESSAGE);
        }
        FoodMealRule update = new FoodMealRule();
        update.setId(id);
        update.setStatus(status);
        update(update);
    }

    @Override
    public List<FoodMealRule> listEnabledByScopeTypes(Set<String> scopeTypes) {
        return getBaseMapper().selectList(new LambdaQueryWrapper<FoodMealRule>()
            .eq(FoodMealRule::getStatus, STATUS_ENABLED)
            .eq(FoodMealRule::getDelFlag, DEL_NORMAL)
            .in(FoodMealRule::getScopeType, scopeTypes));
    }

    @Override
    public boolean existsSameRule(String id, String serviceAreaId, String mealType, String scopeType) {
        return baseMapper.countSameRule(id, StrUtil.nullToEmpty(serviceAreaId), StrUtil.nullToEmpty(mealType), scopeType) > 0;
    }
}
