package org.jebot.handler.impl.channel;

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

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

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

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

        //忽略商户群组消息
        if (botMessage.isGroupMch()) {
            return false;
        }

        if (botMessage.messageTextIsEmpty()) {
            return false;
        }

        //查询群组绑定的通道成功率
        if (botMessage.isGroupChannel() && QUERY_CHANNEL_TODAY_SUCCESS_RATE.equals(botMessage.getMessage().text())) {
            Date currentTime = new Date();
            PayOrderRepository payOrderRepository = handlerManager.getPayOrderRepository();
            List<BotGroup> botGroups = handlerManager.getGroupRepository().findAllByGroupIdAndDataType(botMessage.getMessage().chat().id(), Constant.DATA_TYPE_CHANNEL);
            if (botGroups == null || botGroups.isEmpty()) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前群组未绑定任何通道"));
                return true;
            }
            //获取当前群组绑定的通道
            List<Long> passageIds = botGroups.stream().map(BotGroup::getDataId).collect(Collectors.toList());

            List<PayOrder> payOrderList = payOrderRepository.findPayOrderByPassageAndCreateTimeAll(passageIds, org.jebot.util.DateUtil.getTodayMidnight(currentTime), currentTime);
            if (payOrderList == null || payOrderList.isEmpty()) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "无当日记录"));
                return true;
            }

            List<PayPassage> passages = handlerManager.getPassageRepository().findByPassageIds(passageIds);
            StringBuilder result = new StringBuilder();


            // 时间段
            Date halfHourAgo = DateUtil.offsetMinute(currentTime, -30);
            Date oneHourAgo = DateUtil.offsetMinute(currentTime, -60);
            Date threeHoursAgo = DateUtil.offsetMinute(currentTime, -180);

            // 按通道统计
            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("通道名称: ").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");
            }
            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());
    }

}
