package com.ruoyi.app.mendian;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.OperatingUtil;
import com.ruoyi.app.user.dto.StoreOutput;
import com.ruoyi.common.utils.LocaleUtils;
import com.ruoyi.system.domain.OperatingHours;
import com.ruoyi.system.domain.PosFood;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.PosReview;
import com.ruoyi.system.domain.PosStore;
import com.ruoyi.system.mapper.PosFoodMapper;
import com.ruoyi.system.service.IOperatingHoursService;
import com.ruoyi.system.service.IPosOrderService;
import com.ruoyi.system.service.IPosReviewService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class PosStoreEnrichService {

    @Autowired
    private IPosReviewService posReviewService;
    @Autowired
    private IPosOrderService posOrderService;
    @Autowired
    private IOperatingHoursService operatingHoursService;
    @Autowired
    private PosFoodMapper posFoodMapper;

    /**
     * 为门店列表设置评分、月售、营业状态。
     */
    public void enrichStoreList(List<PosStore> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        List<Long> mdIds = list.stream()
                .map(store -> store.getId() == null ? null : store.getId().longValue())
                .filter(idVal -> idVal != null)
                .collect(Collectors.toList());

        Map<Long, List<PosReview>> reviewMap = Collections.emptyMap();
        Map<Long, Long> orderCountMap = Collections.emptyMap();
        List<OperatingHours> hourslist = Collections.emptyList();

        if (!mdIds.isEmpty()) {
            QueryWrapper<PosReview> reviewWrapper = new QueryWrapper<>();
            reviewWrapper.in("md_id", mdIds);
            List<PosReview> reviews = posReviewService.list(reviewWrapper);
            reviewMap = reviews.stream()
                    .collect(Collectors.groupingBy(PosReview::getMdId));

            QueryWrapper<PosOrder> orderWrapper = new QueryWrapper<>();
            orderWrapper.in("md_id", mdIds);
            orderWrapper.apply("DATE_FORMAT(cretim,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')");
            List<PosOrder> orders = posOrderService.list(orderWrapper);
            orderCountMap = orders.stream()
                    .collect(Collectors.groupingBy(PosOrder::getMdId, Collectors.counting()));

            QueryWrapper<OperatingHours> wrapper = new QueryWrapper<>();
            wrapper.in("md_id", mdIds);
            hourslist = operatingHoursService.list(wrapper);
        }

        DateUtil dateUtil = new DateUtil();
        for (PosStore store : list) {
            Long mdId = store.getId() == null ? null : store.getId().longValue();
            List<PosReview> storeReviews = (mdId == null || reviewMap.isEmpty()) ? null : reviewMap.get(mdId);

            double score;
            if (storeReviews == null || storeReviews.isEmpty()) {
                score = 4.5d;
            } else {
                double avg = storeReviews.stream()
                        .mapToDouble(PosReview::getScore)
                        .average()
                        .orElse(4.5d);
                score = Math.round(avg * 2.0d) / 2.0d;
            }
            store.setPingf(score);

            long monthCount = (mdId == null || orderCountMap.isEmpty()) ? 0L : orderCountMap.getOrDefault(mdId, 0L);
            store.setDdsl(monthCount);

            boolean dayang = false;
            List<OperatingHours> mdHours = hourslist.stream()
                    .filter(x -> store.getId() != null && store.getId().equals(x.getMdId().intValue()))
                    .collect(Collectors.toList());
            dayang = OperatingUtil.storeIsOperatingOfDay(mdHours);
            if (!dayang) {
                store.setState(1L);
            }
        }
    }

    /**
     * 将门店列表转换为带商品列表的分页结构（StoreOutput）。
     */
    public Page<StoreOutput> buildStoreOutputPage(List<PosStore> storeList, String language, int page, long total) {
        String lang = LocaleUtils.toLangCode(language);
        List<Integer> storeIds = storeList.stream()
                .map(PosStore::getId)
                .collect(Collectors.toList());

        Map<Integer, List<PosFood>> foodMap = new java.util.HashMap<>();
        if (!storeIds.isEmpty()) {
            List<Long> storeIdsLong = storeIds.stream()
                    .map(Integer::longValue)
                    .collect(Collectors.toList());
            List<PosFood> allFoods = posFoodMapper.selectFoodsByStoreIdsWithLimit(storeIdsLong, lang, 6);
            foodMap = allFoods.stream()
                    .collect(Collectors.groupingBy(food -> food.getMdid().intValue()));
        }

        List<StoreOutput> storeOutputList = new ArrayList<>();
        for (PosStore store : storeList) {
            StoreOutput storeOutput = new StoreOutput();
            BeanUtils.copyProperties(store, storeOutput);
            List<PosFood> foodList = foodMap.getOrDefault(store.getId(), new ArrayList<>());
            storeOutput.setFoodList(foodList);
            storeOutputList.add(storeOutput);
        }

        Page<StoreOutput> result = new Page<>(page, 10);
        result.setTotal(total);
        result.setRecords(storeOutputList);
        return result;
    }
}
