package org.jebot.handler.impl.channel;

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.jebot.BotAccountBook;
import org.jebot.models.jebot.BotAccountBookHistory;
import org.jebot.service.dto.UpdateBalance;

import javax.imageio.ImageIO;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;

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

@Slf4j
public class ChannelAccountBookHandler extends AbstractHandler {


    // 代收正则表达式：支持数字和运算符
    private static final Pattern paymentAccount = Pattern.compile("^" + PAYMENT_ACCOUNT_FLAG + "[0-9+\\-*/.]+$");

    // 代付正则表达式：支持数字和运算符
    private static final Pattern agentAccount = Pattern.compile("^" + AGENT_ACCOUNT_FLAG + "[0-9+\\-*/.]+$");



    @Override
    public boolean msgHandler(BotMessage message) {

        //只处理群组认证
        if (!message.isGroupChannel()) {
            return false;
        }

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


        //只处理来自管理员的消息
        if (!message.isUserAuthenticated()) {
            return false;
        }


        String messageText = message.getMessageText();
        if (!paymentAccount.matcher(messageText).find() && !agentAccount.matcher(messageText).find()) {
            return false;
        }

        BotAccountBook accountBook = handlerManager.getAccountBookRepository().findByBelongIdAndType(message.getBotGroup().getGroupId(), DATA_TYPE_CHANNEL);
        if (accountBook == null) {
            accountBook = new BotAccountBook();
            accountBook.setBelongId(message.getBotGroup().getGroupId());
            accountBook.setBelongName(message.getBotGroup().getGroupName());
            accountBook.setType(Constant.DATA_TYPE_CHANNEL);
            accountBook.setAgentBalance(0L);
            accountBook.setPaymentBalance(0L);
            accountBook = handlerManager.getAccountBookRepository().save(accountBook);
        }

        //代收处理
        if (paymentAccount.matcher(messageText).find()) {
            String expr = messageText.replace(PAYMENT_ACCOUNT_FLAG, ""); // 去掉前缀 "代收"
            double paymentAccountAmount = evalExpression(expr); // 支持表达式
            if (paymentAccountAmount == 0) {
                return true;
            }
            double paymentBalanceOld = accountBook.getPaymentBalance();
            double paymentBalanceNew = paymentBalanceOld + paymentAccountAmount;
            SendMessage sendMessage = null;
            try {
                UpdateBalance updateBalance = new UpdateBalance();
                updateBalance.setId(accountBook.getId());
                updateBalance.setAmount(paymentAccountAmount);
                updateBalance.setOldBalance(paymentBalanceOld);
                updateBalance.setNewBalance(paymentBalanceNew);
                updateBalance.setMessage(message);
                handlerManager.getAccountBookService().updatePaymentBalanceByIdAndPaymentBalance(updateBalance);
                sendMessage = new SendMessage(message.getMessage().chat().id(), String.format("入账提醒\n入账金额: %.2f\n入账前: %.2f\n入账后: %.2f", paymentAccountAmount, paymentBalanceOld, paymentBalanceNew));
            } catch (Exception e) {
                log.error("更新通道群组账本失败,群组ID:{},群组名称:{},用户ID:{},用户名称:{},金额:{},错误信息:{}", message.getBotGroup().getDataId(), message.getBotGroup().getDataName(), message.getBotUser().getUserId(), message.getBotUser().getUserName(), paymentAccountAmount, e.getMessage());
                e.printStackTrace();
                sendMessage = new SendMessage(message.getMessage().chat().id(), "处理失败,请重试");
            } finally {
                if (sendMessage != null) {
                    message.getTelegramBot().execute(sendMessage);
                }
            }
            return true;
        }

        //代付处理
        if (agentAccount.matcher(messageText).find()) {
            String expr = messageText.replace(AGENT_ACCOUNT_FLAG, ""); // 去掉前缀 "代收"
            double agentAccountAmount = evalExpression(expr); // 支持表达式
            if (agentAccountAmount == 0) {
                return true;
            }
            double agentBalanceOld = accountBook.getAgentBalance();
            double agentBalanceNew = agentBalanceOld + agentAccountAmount;
            SendMessage sendMessage = null;
            try {
                UpdateBalance updateBalance = new UpdateBalance();
                updateBalance.setId(accountBook.getId());
                updateBalance.setAmount(agentAccountAmount);
                updateBalance.setOldBalance(agentBalanceOld);
                updateBalance.setNewBalance(agentBalanceNew);
                updateBalance.setMessage(message);
                handlerManager.getAccountBookService().updateAgentBalanceByIdAndAgentBalance(updateBalance);
                sendMessage = new SendMessage(message.getMessage().chat().id(), String.format("入账提醒\n入账金额: %.2f\n入账前: %.2f\n入账后: %.2f", agentAccountAmount, agentBalanceOld, agentBalanceNew));
            } catch (Exception e) {
                log.error("更新通道群组账本失败,群组ID:{},群组名称:{},用户ID:{},用户名称:{},金额:{},错误信息:{}", message.getBotGroup().getDataId(), message.getBotGroup().getDataName(), message.getBotUser().getUserId(), message.getBotUser().getUserName(), agentAccountAmount, e.getMessage());
                e.printStackTrace();
                sendMessage = new SendMessage(message.getMessage().chat().id(), "处理失败,请重试");
            } finally {
                if (sendMessage != null) {
                    message.getTelegramBot().execute(sendMessage);
                }
            }
            return true;
        }

        return false;
    }

    // 工具方法：支持计算表达式
    private double evalExpression(String expr) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            Object result = engine.eval(expr);
            return Double.parseDouble(result.toString());
        } catch (ScriptException e) {
            log.error("表达式计算失败: {}", expr, e);
            throw new RuntimeException("金额表达式错误: " + expr);
        }
    }


}
