package org.jebot.handler.impl.merchant;

import cn.hutool.core.date.DateUtil;
import com.pengrad.telegrambot.request.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.jebot.constant.Constant;
import org.jebot.handler.AbstractHandler;
import org.jebot.handler.dto.BotMessage;
import org.jebot.models.xxpay.PayOrder;
import org.jebot.models.xxpay.PayPassage;
import org.jebot.models.xxpay.PayProduct;
import org.jebot.repository.xxpay.PayOrderRepository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.jebot.constant.Constant.QUERY_MCH_TODAY_SUCCESS_RATE;

@Slf4j
public class MerchantSuccessRateHandler extends AbstractHandler {
    @Override
    public boolean msgHandler(BotMessage botMessage) {

        //只处理来自商户群组的消息
        if (!botMessage.isGroupMch()) {
            return false;
        }

        //获取商户成功率
        if (botMessage.isGroupMch() && QUERY_MCH_TODAY_SUCCESS_RATE.equals(botMessage.getMessage().text())) {
            PayOrderRepository payOrderRepository = handlerManager.getPayOrderRepository();
            Date currentTime = new Date();
            List<PayOrder> payOrderList = payOrderRepository.findPayOrderByMchIdAndCreateTime(botMessage.getBotGroup().getDataId(), org.jebot.util.DateUtil.getTodayMidnight(currentTime), currentTime);
            if (payOrderList == null || payOrderList.isEmpty()) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "无当日记录"));
                return true;
            }

            List<Long> productIds = new ArrayList<>(payOrderList.stream()
                    .filter(order -> order.getProductId() != null)
                    .collect(Collectors.toMap(
                            PayOrder::getProductId,
                            PayOrder::getProductId,
                            (existing, replacement) -> existing))
                    .values());

            List<PayProduct> products = handlerManager.getProductRepository().findByProductIds(productIds);
            ;
//            List<PayPassage> passages = handlerManager.getPassageRepository().findByPassageIds(passageIds);
            StringBuilder result = new StringBuilder();

            // 总单数和总金额
//            int totalOrders = payOrderList.size();
//            BigDecimal totalAmount = payOrderList.stream().map(PayOrder::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

            // 有效单数和有效金额
            List<PayOrder> validOrders = payOrderList.stream().filter(order -> order.getStatus() == 2 || order.getStatus() == 3) // 假设状态 2 和 3 为有效
                    .collect(Collectors.toList());
//            int validOrderCount = validOrders.size();
//            BigDecimal validAmount = validOrders.stream().map(PayOrder::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

            result.append("商户id: ").append(botMessage.getBotGroup().getDataId()).append("\n");
            result.append("商户名: ").append(botMessage.getBotGroup().getDataName()).append("\n");
//            result.append("总单数: ").append(totalOrders).append("\n");
//            result.append("有效单数: ").append(validOrderCount).append("\n");
//            result.append("总金额: ").append(totalAmount.movePointLeft(Constant.AMOUNT_MOVE_POINT)).append("\n");
//            result.append("有效金额: ").append(validAmount.movePointLeft(Constant.AMOUNT_MOVE_POINT)).append("\n");
            // 按通道统计
//            for (PayPassage passage : passages) {
//                List<PayOrder> passageOrders = payOrderList.stream().filter(order -> passage.getId().equals(order.getPassageId())).collect(Collectors.toList());
//
//                // 统计不同时间段的成功率
//                double halfHourSuccessRate = calculateSuccessRate(passageOrders, halfHourAgo, currentTime);
//                double oneHourSuccessRate = calculateSuccessRate(passageOrders, oneHourAgo, currentTime);
//                double threeHourSuccessRate = calculateSuccessRate(passageOrders, threeHoursAgo, currentTime);
//                double dailySuccessRate = calculateSuccessRate(passageOrders, DateUtil.beginOfDay(currentTime), currentTime);
//
//                result.append(passage.getPassageName()).append(":\n");
//                result.append("   30分钟成功率: ").append(String.format("%.2f", halfHourSuccessRate)).append("%\n");
//                result.append("   1小时成功率: ").append(String.format("%.2f", oneHourSuccessRate)).append("%\n");
//                result.append("   3小时成功率: ").append(String.format("%.2f", threeHourSuccessRate)).append("%\n");
//                result.append("   当日成功率: ").append(String.format("%.2f", dailySuccessRate)).append("%\n");
//            }
            // 时间段
            Date fifteenMinutesAgo = DateUtil.offsetMinute(currentTime, -15);
            Date thirtyMinutesAgo = DateUtil.offsetMinute(currentTime, -30);
            Date oneHourAgo = DateUtil.offsetMinute(currentTime, -60);

            for (PayProduct product : products) {
                List<PayOrder> productOrders = payOrderList.stream()
                        .filter(order -> product.getId().equals(order.getProductId()))
                        .collect(Collectors.toList());

                // 统计不同时间段的成功率
                double fifteenMinuteSuccessRate = calculateSuccessRate(productOrders, fifteenMinutesAgo, currentTime);
                double thirtyMinuteSuccessRate = calculateSuccessRate(productOrders, thirtyMinutesAgo, currentTime);
                double oneHourSuccessRate = calculateSuccessRate(productOrders, oneHourAgo, currentTime);
                double dailySuccessRate = calculateSuccessRate(productOrders, DateUtil.beginOfDay(currentTime), currentTime);

                result.append(product.getId() + "-" + product.getProductName()).append(":\n");
                result.append("   15分钟成功率: ").append(String.format("%.2f", fifteenMinuteSuccessRate)).append("%\n");
                result.append("   30分钟成功率: ").append(String.format("%.2f", thirtyMinuteSuccessRate)).append("%\n");
                result.append("   1小时成功率: ").append(String.format("%.2f", oneHourSuccessRate)).append("%\n");
                result.append("   当日成功率: ").append(String.format("%.2f", dailySuccessRate)).append("%\n");
            }

            botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), result.toString()));
            return true;
        }

        return false;
    }

    // 计算成功率的方法
    private static double calculateSuccessRate(List<PayOrder> orders, Date startTime, Date endTime) {
        List<PayOrder> filteredOrders = orders.stream().filter(order -> startTime.before(order.getCreateTime()) && endTime.after(order.getCreateTime())).collect(Collectors.toList());
        long successCount = filteredOrders.stream().filter(order -> order.getStatus() == 2 || order.getStatus() == 3) // 假设状态 2 和 3 为成功
                .count();
        return filteredOrders.isEmpty() ? 0 : (successCount * 100.0 / filteredOrders.size());
    }
}
