package com.jeesharp.business.modules.food.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.common.support.QueryInCsvSupport;
import com.jeesharp.business.modules.food.convert.FoodPackageConvert;
import com.jeesharp.business.modules.food.dto.FoodPackageSaveDTO;
import com.jeesharp.business.modules.food.entity.FoodPackage;
import com.jeesharp.business.modules.food.service.FoodPackageService;
import com.jeesharp.business.modules.food.service.FoodRestaurantService;
import com.jeesharp.business.modules.food.vo.FoodPackageInfoVO;
import com.jeesharp.business.modules.food.vo.FoodPackageListVO;
import com.jeesharp.business.modules.food.vo.FoodPackageQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 美食套餐应用服务：后台查询、保存与门店名称展示编排。
 *
 * @author jeesharp
 * @since 2026-06-04
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class FoodPackageApplicationService {

    private final FoodPackageService foodPackageService;
    private final FoodRestaurantService foodRestaurantService;

    public FoodPackageInfoVO get(String id) {
        FoodPackage entity = foodPackageService.get(id);
        if (entity == null) {
            return null;
        }
        FoodPackageInfoVO vo = FoodPackageConvert.INSTANCE.toInfoVO(entity);
        enrichInfoDisplay(vo);
        return vo;
    }

    public PageRespVO<FoodPackageListVO> findPage(Page<FoodPackage> page, FoodPackageQueryVO query) {
        FoodPackageQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<FoodPackage> result = foodPackageService.findPage(page, prepared);
        PageRespVO<FoodPackageListVO> pageVo = FoodPackageConvert.INSTANCE.toPageRespVO(result);
        enrichListDisplay(pageVo.getRecords());
        return pageVo;
    }

    public List<FoodPackageInfoVO> listOnlineByRestaurant(String restaurantId) {
        return foodPackageService.listOnlineByRestaurant(restaurantId).stream()
                .map(FoodPackageConvert.INSTANCE::toInfoVO)
                .toList();
    }

    @Transactional(readOnly = false)
    public void save(FoodPackageSaveDTO dto) {
        FoodPackage entity = FoodPackageConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            foodPackageService.createPackage(entity);
            return;
        }
        foodPackageService.updatePackage(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        foodPackageService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    /**
     * 管理端门店名称筛选 → restaurantIdInCsv（FIND_IN_SET，兼容分页 count）。
     */
    private FoodPackageQueryVO prepareQuery(FoodPackageQueryVO query) {
        FoodPackageQueryVO q = query != null ? query : new FoodPackageQueryVO();
        if (StrUtil.isNotBlank(q.getRestaurantName())) {
            List<String> restaurantIds = foodRestaurantService.findIdsByNameLike(q.getRestaurantName().trim());
            q.setRestaurantName(null);
            if (CollUtil.isEmpty(restaurantIds)) {
                return null;
            }
            q.setRestaurantIdInCsv(QueryInCsvSupport.toIdInCsv(restaurantIds));
        }
        return q;
    }

    private void enrichListDisplay(List<FoodPackageListVO> rows) {
        if (CollUtil.isEmpty(rows)) {
            return;
        }
        List<String> restaurantIds = rows.stream()
            .map(FoodPackageListVO::getRestaurantId)
            .filter(StrUtil::isNotBlank)
            .distinct()
            .toList();
        Map<String, String> restaurantNameMap = foodRestaurantService.mapRestaurantNameByIds(restaurantIds);
        for (FoodPackageListVO row : rows) {
            if (StrUtil.isNotBlank(row.getRestaurantId())) {
                row.setRestaurantName(restaurantNameMap.get(row.getRestaurantId()));
            }
        }
    }

    private void enrichInfoDisplay(FoodPackageInfoVO vo) {
        if (vo == null || StrUtil.isBlank(vo.getRestaurantId())) {
            return;
        }
        Map<String, String> nameMap = foodRestaurantService.mapRestaurantNameByIds(List.of(vo.getRestaurantId()));
        vo.setRestaurantName(nameMap.get(vo.getRestaurantId()));
    }

    private static PageRespVO<FoodPackageListVO> emptyPage(Page<FoodPackage> page) {
        PageRespVO<FoodPackageListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page != null ? page.getPageNo() : 1L);
        empty.setPageSize(page != null ? page.getPageSize() : 10L);
        return empty;
    }
}
