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

import com.jeesharp.business.modules.common.enums.ShelfStatusEnum;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.food.entity.FoodPackage;
import com.jeesharp.business.modules.common.enums.OnlineEnabledEnum;

import com.jeesharp.business.modules.food.mapper.FoodPackageMapper;
import com.jeesharp.business.modules.food.service.FoodPackageService;
import com.jeesharp.business.modules.food.vo.FoodPackageQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.mybatis.core.service.CrudService;
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;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
public class FoodPackageServiceImpl extends CrudService<FoodPackageMapper, FoodPackage, FoodPackageQueryVO> implements FoodPackageService {

    private static final int DEFAULT_SORT_NO = 0;
    private static final int DEFAULT_MAX_QUANTITY_PER_ORDER = 20;
    private static final String IDS_SEPARATOR = ",";
    private static final String MSG_STOCK_INSUFFICIENT = "库存不足，请减少份数或稍后重试";

    @Override
    public List<FoodPackage> listOnlineByRestaurant(String restaurantId) {
        FoodPackageQueryVO query = new FoodPackageQueryVO();
        query.setRestaurantId(restaurantId);
        query.setStatus(ShelfStatusEnum.ONLINE.getValue());
        query.closeDataScope();
        return findList(query);
    }

    @Override
    public List<String> findIdsByNameLike(String name) {
        if (StrUtil.isBlank(name)) {
            return List.of();
        }
        FoodPackageQueryVO query = new FoodPackageQueryVO();
        query.setName(name.trim());
        return findList(query).stream()
            .map(FoodPackage::getId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .collect(Collectors.toList());
    }

    @Override
    public Map<String, String> mapPackageNameByIds(List<String> ids) {
        Map<String, FoodPackage> packageMap = mapPackageByIds(ids);
        if (packageMap.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, FoodPackage> entry : packageMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue().getName());
        }
        return map;
    }

    @Override
    public Map<String, FoodPackage> mapPackageByIds(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, FoodPackage> map = new HashMap<>();
        List<FoodPackage> packages = getBaseMapper().selectByIds(distinctIds);
        if (packages == null) {
            return map;
        }
        for (FoodPackage pkg : packages) {
            if (pkg != null && StrUtil.isNotBlank(pkg.getId())) {
                map.put(pkg.getId(), pkg);
            }
        }
        return map;
    }

    @Override
    @Transactional(readOnly = false)
    public void createPackage(FoodPackage entity) {
        if (entity.getSortNo() == null) {
            entity.setSortNo(DEFAULT_SORT_NO);
        }
        if (entity.getMaxQuantityPerOrder() == null || entity.getMaxQuantityPerOrder() < 1) {
            entity.setMaxQuantityPerOrder(DEFAULT_MAX_QUANTITY_PER_ORDER);
        }
        if (entity.getOnlineOrderEnabled() == null) {
            entity.setOnlineOrderEnabled(OnlineEnabledEnum.ENABLED.getValue());
        }
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updatePackage(FoodPackage entity) {
        if (entity.getSortNo() == null) {
            entity.setSortNo(DEFAULT_SORT_NO);
        }
        if (entity.getMaxQuantityPerOrder() != null && entity.getMaxQuantityPerOrder() < 1) {
            entity.setMaxQuantityPerOrder(DEFAULT_MAX_QUANTITY_PER_ORDER);
        }
        if (entity.getOnlineOrderEnabled() == null) {
            entity.setOnlineOrderEnabled(OnlineEnabledEnum.ENABLED.getValue());
        }
        update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void decrementAvailableQuantityIfConfigured(FoodPackage pkg, int quantity) {
        if (pkg == null || pkg.getAvailableQuantity() == null) {
            return;
        }
        if (getBaseMapper().decrementAvailableQuantity(pkg.getId(), quantity) != 1) {
            throw new BizErrorException(MSG_STOCK_INSUFFICIENT);
        }
    }

}
