package org.jebot.handler.impl.channel;

import cn.hutool.core.date.DateUtil;
import com.pengrad.telegrambot.model.request.ParseMode;
import com.pengrad.telegrambot.model.request.ReplyParameters;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.jebot.constant.Constant;
import org.jebot.handler.AbstractHandler;
import org.jebot.handler.dto.BotMessage;
import org.jebot.models.jebot.BotAccountBook;
import org.jebot.models.jebot.BotGroup;
import org.jebot.models.xxpay.PayOrder;
import org.jebot.models.xxpay.PayPassage;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

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

@Slf4j
public class ChannelInfoHandler extends AbstractHandler {

//    private static final Pattern UPDATE_CHANNEL_AGENT_WARN_THRESHOLD = Pattern.compile("^" + UPDATE_CHANNEL_AGENT_WARN_THRESHOLD_FLAG + "-?\\d+(\\.\\d+)?$");
//    private static final Pattern UPDATE_CHANNEL_PAYMENT_WARN_THRESHOLD = Pattern.compile("^" + UPDATE_CHANNEL_PAYMENT_WARN_THRESHOLD_FLAG + "-?\\d+(\\.\\d+)?$");


    private static final Pattern QUERY_ORDER = Pattern.compile("^" + QUERY_CHANNEL_ORDER_FLAG + "[a-zA-Z0-9]+$");


    @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_BALANCE.equals(botMessage.getMessage().text())) {
            Date endDate = new Date();
            Date startDate = org.jebot.util.DateUtil.getTodayMidnight(endDate);
            List<BotGroup> botGroups = handlerManager.getGroupRepository().findAllByGroupIdAndDataType(botMessage.getBotGroup().getGroupId(), DATA_TYPE_CHANNEL);
            if (botGroups == null || botGroups.isEmpty()) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前群组未绑定任何通道"));
                return true;
            }

            //转化为Long类型
            List<Long> passageIds = botGroups.stream().map(BotGroup::getDataId).collect(Collectors.toList());
            //根据通道ID查询通道
            List<PayPassage> payPassages = handlerManager.getPassageRepository().findByPassageIds(passageIds);
            //获取通道id
            List<Long> payPassageIds = payPassages.stream().map(PayPassage::getId).collect(Collectors.toList());
            //根据通道ID和时间查询订单
            List<PayOrder> payOrders = handlerManager.getPayOrderRepository().findPayOrderByPassageAndCreateTime(payPassageIds, startDate, endDate);
            //根据通道id分组
            Map<Long, List<PayOrder>> payOrderMap = payOrders.stream().collect(Collectors.groupingBy(PayOrder::getPassageId));
            //定义一个StringBuilder对象
            StringBuilder stringBuffer = new StringBuilder();
            BigDecimal channelTotalAfterFeeAmount = BigDecimal.ZERO;
            BotAccountBook accountBook = handlerManager.getAccountBookRepository().findByBelongIdAndType(botMessage.getBotGroup().getGroupId(), DATA_TYPE_CHANNEL);
            if (accountBook == null) {
                accountBook = new BotAccountBook();
                accountBook.setBelongId(botMessage.getBotGroup().getGroupId());
                accountBook.setBelongName(botMessage.getBotGroup().getGroupName());
                accountBook.setType(DATA_TYPE_CHANNEL);
                accountBook.setAgentBalance(0L);
                accountBook.setPaymentBalance(0L);
                accountBook = handlerManager.getAccountBookRepository().save(accountBook);
            }
            for (PayPassage payPassage : payPassages) {
                List<PayOrder> payPassageOrders = payOrderMap.get(payPassage.getId());
                if (payPassageOrders != null && !payPassageOrders.isEmpty()) {
                    // 计算未减去手续费的总金额
                    BigDecimal totalAmount = payPassageOrders.stream()
                            .map(PayOrder::getAmount)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    // 计算减去手续费后的总金额
                    BigDecimal totalAmountAfterFee = payPassageOrders.stream()
                            .map(order -> {
                                BigDecimal amount = order.getAmount();
                                BigDecimal payPassageRate = order.getPayPassageRate();
                                if (payPassageRate.doubleValue() < 100.00) {
                                    return amount.subtract(amount.multiply(payPassageRate.movePointLeft(AMOUNT_MOVE_POINT)));
                                }
                                return amount;
                            })
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    channelTotalAfterFeeAmount = channelTotalAfterFeeAmount.add(totalAmountAfterFee);
                    stringBuffer.append("通道名: ").append(payPassage.getPassageName()).append("\n");
                    stringBuffer.append("通道号: ").append(payPassage.getId()).append("\n");
                    stringBuffer.append("当日跑量: ").append(totalAmount.movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue()).append("\n");
                    stringBuffer.append("应得余额: ").append(totalAmountAfterFee.movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue()).append("\n\n");
                } else {
                    stringBuffer.append("通道名: ").append(payPassage.getPassageName()).append("\n");
                    stringBuffer.append("通道号: ").append(payPassage.getId()).append("\n");
                    stringBuffer.append("当日跑量: 0.0\n");
                    stringBuffer.append("应得余额: 0.0\n\n");
                }
            }
            stringBuffer.append("当前预付: ").append(accountBook.getPaymentBalance()).append("\n");
            stringBuffer.append("剩余预付: ").append(accountBook.getPaymentBalance() - channelTotalAfterFeeAmount.movePointLeft(AMOUNT_MOVE_POINT).doubleValue()).append("\n");
            stringBuffer.append("统计时间: ").append(DateUtil.formatDateTime(endDate)).append("\n\n");
            botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), stringBuffer.toString()));
            return true;
        }

        //通道查单
        if (botMessage.isGroupChannel() && !botMessage.messageTextIsEmpty() && QUERY_ORDER.matcher(botMessage.getMessage().text()).find()) {
            String orderId = botMessage.getMessage().text().replace(QUERY_CHANNEL_ORDER_FLAG, "");
            PayOrder payOrder = this.handlerManager.getPayOrderRepository().findByPayOrderIdOrChannelOrderNo(orderId);
            if (payOrder == null) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "订单不存在"));
                return true;
            }

            StringBuilder stringBuffer = new StringBuilder();
            stringBuffer.append("商户号: ").append(payOrder.getMchId()).append("\n");
            stringBuffer.append("平台单号: ").append("`").append(payOrder.getPayOrderId()).append("`").append("\n");
            if (Strings.isNotEmpty(payOrder.getChannelOrderNo())) {
                stringBuffer.append("通道单号: ").append("`").append(payOrder.getChannelOrderNo()).append("`").append("\n");
            } else {
                stringBuffer.append("通道单号: 无\n");
            }
            stringBuffer.append("支付金额: ").append(payOrder.getAmount().movePointLeft(Constant.AMOUNT_MOVE_POINT)).append("\n");
            stringBuffer.append("支付状态: ").append(payOrder.getStatusMsg()).append("\n");
            if (payOrder.getPaySuccTime() != null) {
                stringBuffer.append("支付时间: ").append(DateUtil.formatDateTime(payOrder.getPaySuccTime())).append("\n");
            } else {
                stringBuffer.append("支付时间: 无\n");
            }
            stringBuffer.append("创建时间: ").append(payOrder.getCreateTime()).append("\n");
            SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), this.strEscape(stringBuffer.toString()));
            sendMessage.parseMode(ParseMode.MarkdownV2);
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            botMessage.getTelegramBot().execute(sendMessage);
            return true;
        }

        if (QUERY_CHANNEL_INFO.equals(botMessage.getMessageText())) {
            List<BotGroup> botGroups = this.handlerManager.getGroupRepository().findAllByGroupIdAndDataType(botMessage.getMessage().chat().id(), Constant.DATA_TYPE_CHANNEL);
            StringBuilder sb = new StringBuilder();
            if (botGroups == null || botGroups.isEmpty()) {
                sb.append("当前群组未绑定任何通道");
            } else {
                for (BotGroup botGroup : botGroups) {
                    sb.append(String.format("通道ID: %s\r\n", botGroup.getDataId()));
                    sb.append(String.format("通道名称: %s\r\n", botGroup.getDataName()));
                    sb.append(String.format("绑定时间: %s\r\n", botGroup.getCreateTime()));
                }
            }
            SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), sb.toString());
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
            if (!execute.isOk()) {
                log.error("通道信息发送失败: {}", execute);
            }
        }
        return false;
    }


}
