package org.jebot.handler.impl.merchant;

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 lombok.extern.slf4j.Slf4j;
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.xxpay.MchAccount;
import org.jebot.models.xxpay.PayOrder;
import org.jebot.repository.xxpay.MchAccountRepository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

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

@Slf4j
public class MerchantInfoHandler extends AbstractHandler {

    //商户查询订单
    private static final Pattern QUERY_ORDER = Pattern.compile("^" + QUERY_MCH_ORDER_FLAG + "[a-zA-Z0-9]+$");


    @Override
    public boolean msgHandler(BotMessage botMessage) {

        //只处理来自群组的消息
        if (!botMessage.isGroupMch()) {
            //botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "未绑定商户,请先绑定商户再进行操作"));
            return false;
        }

        //查询当前群组商户信息
        if (botMessage.isGroupMch() && MCH_INFO.equals(botMessage.getMessage().text())) {
            SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), String.format("商户号: `%s`\n商户名: %s", botMessage.getBotGroup().getDataId(), botMessage.getBotGroup().getDataName()));
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            sendMessage.parseMode(ParseMode.MarkdownV2);
            botMessage.getTelegramBot().execute(sendMessage);
            return true;

        }

        //查询当前群组商户url信息
        if (botMessage.isGroupMch() && MCH_URL_INFO.equals(botMessage.getMessage().text())) {
            SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), String.format("商户号: `%s`\n商户名: %s \n地址: %s", botMessage.getBotGroup().getDataId(), botMessage.getBotGroup().getDataName(), botMessage.getBotGroup().getUstdUrl()));
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            sendMessage.parseMode(ParseMode.MarkdownV2);
            botMessage.getTelegramBot().execute(sendMessage);
            return true;

        }

        //查询代收余额
        if (botMessage.isGroupMch() && !botMessage.messageTextIsEmpty() && QUERY_MCH_BALANCE.equals(botMessage.getMessage().text())) {
            Date endDate = new Date();
            Date startDate = org.jebot.util.DateUtil.getTodayMidnight(endDate);
            MchAccount mchAccount = handlerManager.getMchAccountRepository().findByMchId(botMessage.getBotGroup().getDataId());
            if (mchAccount == null) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "商户不存在"));
                return true;
            }
            BotAccountBook merchantAccountBook = handlerManager.getAccountBookRepository().findByBelongIdAndType(mchAccount.getMchId(), DATA_TYPE_MERCHANT);
            if (merchantAccountBook == null) {
                merchantAccountBook = new BotAccountBook();
                merchantAccountBook.setBelongId(botMessage.getBotGroup().getDataId());
                merchantAccountBook.setBelongName(botMessage.getBotGroup().getDataName());
                merchantAccountBook.setType(Constant.DATA_TYPE_MERCHANT);
                merchantAccountBook.setAgentBalance(0L);
                merchantAccountBook.setPaymentBalance(0L);
                merchantAccountBook = handlerManager.getAccountBookRepository().save(merchantAccountBook);
            }

            List<PayOrder> payOrderList = handlerManager.getPayOrderRepository().findSuccessPayOrderByMchIdAndCreateTime(Long.valueOf(botMessage.getBotGroup().getDataId()), startDate, endDate);
            StringBuilder stringBuffer = new StringBuilder();
            stringBuffer.append("商户名: ").append(mchAccount.getName()).append("\n");
            stringBuffer.append("商户号: ").append(mchAccount.getMchId()).append("\n");
            if (payOrderList != null && !payOrderList.isEmpty()) {
                // 计算未减去手续费的总金额
                BigDecimal totalAmount = payOrderList.stream()
                        .map(PayOrder::getAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                // 计算减去手续费后的总金额
                BigDecimal totalAmountAfterFee = payOrderList.stream()
                        .map(order -> {
                            BigDecimal amount = order.getAmount();
                            BigDecimal mchRate = order.getMchRate();
                            if (mchRate.doubleValue() < 100.00) {
                                return amount.subtract(amount.multiply(mchRate.movePointLeft(AMOUNT_MOVE_POINT)));
                            }
                            return amount;
                        })
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                stringBuffer.append("当日跑量: ").append(totalAmount.movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue()).append("\n");
                stringBuffer.append("应得余额: ").append(totalAmountAfterFee.movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue()).append("\n");

                double paymentBalance = merchantAccountBook.getPaymentBalance();
                stringBuffer.append("当前预付: ").append(paymentBalance).append("\n");
                stringBuffer.append("剩余预付: ").append(paymentBalance - totalAmountAfterFee.movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue()).append("\n");
            } else {
                double paymentBalance = merchantAccountBook.getPaymentBalance();
                stringBuffer.append("当日跑量: 0.0\n");
                stringBuffer.append("应得余额: 0.0\n");
                stringBuffer.append("当前预付: ").append(paymentBalance).append("\n");
                stringBuffer.append("剩余预付: ").append(paymentBalance).append("\n");
            }
            stringBuffer.append("统计时间: ").append(DateUtil.formatDateTime(endDate));
            botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), stringBuffer.toString()));
            return true;
        }

        //商户查单
        if (botMessage.isGroupMch() && !botMessage.messageTextIsEmpty() && QUERY_ORDER.matcher(botMessage.getMessage().text()).find()) {
            String orderId = botMessage.getMessage().text().replace(QUERY_MCH_ORDER_FLAG, "");
            PayOrder payOrder = this.handlerManager.getPayOrderRepository().findByPayOrderIdOrMchOrderNo(orderId, Long.valueOf(botMessage.getBotGroup().getDataId()));
            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.getMchOrderNo()).append("`").append("\n");
            stringBuffer.append("平台单号: ").append("`").append(payOrder.getPayOrderId()).append("`").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;
        }
        return false;
    }


}
