package com.fuint.common.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuint.common.dto.ext.ShopAlertInfo;
import com.fuint.common.service.AlertService;
import com.fuint.common.service.EmailService;
import com.fuint.repository.mapper.MtOrderMapper;
import com.fuint.repository.mapper.MtStoreMapper;
import com.fuint.repository.model.MtOrder;
import com.fuint.repository.model.MtStore;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class AlertServiceImpl implements AlertService {
    private EmailService emailService;

    private MtStoreMapper mtStoreMapper;

    private MtOrderMapper mtOrderMapper;


    /**
     * 检查当日营业额并发送预警邮件
     */
    @Override
    @Transactional(readOnly = true)
    public void checkDailySalesAndAlert() {
        // 0. 获取时间范围（统一时间变量）
        LocalDateTime start = LocalDate.now().atStartOfDay();
        LocalDateTime end = LocalDateTime.now();

        // 1. 获取所有店铺
        List<MtStore> shops = mtStoreMapper.selectList(new QueryWrapper<MtStore>().isNotNull("mail"));
        List<Long> shopIds = shops.stream().map(MtStore::getId).collect(Collectors.toList());

        // 2. 批量查询所有相关订单（优化性能）
        Map<Long, List<MtOrder>> ordersByShop = shopIds.isEmpty() ?
                Collections.emptyMap() :
                mtOrderMapper.selectList(
                        new LambdaQueryWrapper<MtOrder>()
                                .in(MtOrder::getStoreId, shopIds)
                                .between(MtOrder::getCreateTime, start, end)
                ).stream().collect(Collectors.groupingBy(MtOrder::getStoreId));

        // 3. 构建预警数据（包含订单明细）
        Map<String, List<ShopAlertInfo>> alertMap = shops.stream()
                .map(shop -> {
                    // 计算总销售额
                    BigDecimal sales = Optional.ofNullable(ordersByShop.get(shop.getId()))
                            .orElse(Collections.emptyList())
                            .stream()
                            .map(MtOrder::getAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    // 注入订单明细
                    return new ShopAlertInfo(
                            shop,
                            sales,
                            ordersByShop.getOrDefault(shop.getId(), Collections.emptyList())
                    );
                })
                .filter(info -> info.getTotalSales().compareTo(info.getShop().getThreshold()) < 0)
                .collect(Collectors.groupingBy(info -> info.getShop().getMail()));

        // 4. 发送邮件（逻辑保持不变）
        alertMap.forEach((mail, list) -> emailService.sendAggregatedAlertEmail(mail, list));
    }
}