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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.food.entity.FoodDish;
import com.jeesharp.business.modules.food.mapper.FoodDishMapper;
import com.jeesharp.business.modules.food.service.FoodDishService;
import com.jeesharp.business.modules.food.vo.FoodDishQueryVO;
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.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class FoodDishServiceImpl extends CrudService<FoodDishMapper, FoodDish, FoodDishQueryVO> implements FoodDishService {

    private static final int DEFAULT_SORT_NO = 0;
    private static final String IDS_SEPARATOR = ",";
    private static final String DISH_NOT_FOUND_MESSAGE = "菜品不存在";

    @Override
    @Transactional(readOnly = false)
    public void createDish(FoodDish entity) {
        if (entity.getSortNo() == null) {
            entity.setSortNo(DEFAULT_SORT_NO);
        }
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateDish(FoodDish entity) {
        if (StrUtil.isBlank(entity.getId()) || get(entity.getId()) == null) {
            throw new BizErrorException(DISH_NOT_FOUND_MESSAGE);
        }
        if (entity.getSortNo() == null) {
            entity.setSortNo(DEFAULT_SORT_NO);
        }
        update(entity);
    }

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

    @Override
    public Map<String, FoodDish> mapDishByIds(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        List<String> distinctIds = ids.stream().filter(StrUtil::isNotBlank).distinct().toList();
        if (distinctIds.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, FoodDish> map = new HashMap<>();
        List<FoodDish> dishes = getBaseMapper().selectByIds(distinctIds);
        if (dishes == null) {
            return map;
        }
        for (FoodDish dish : dishes) {
            if (dish != null && StrUtil.isNotBlank(dish.getId())) {
                map.put(dish.getId(), dish);
            }
        }
        return map;
    }
}
