package org.jebot.handler.impl.merchant;

import cn.hutool.core.date.DateUtil;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.request.SendPhoto;
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.repository.jebot.BotAccountBookRepository;
import org.jebot.service.dto.UpdateBalance;
import org.jebot.util.SnowflakeId;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

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

@Slf4j
public class MerchantAccountBookHandler extends AbstractHandler {


    //代收正则表达式
    private static final Pattern paymentAccount = Pattern.compile("^" + PAYMENT_ACCOUNT_FLAG + "-?\\d+(\\.\\d+)?$");

    //代付正则表达式
    private static final Pattern agentAccount = Pattern.compile("^" + AGENT_ACCOUNT_FLAG + "-?\\d+(\\.\\d+)?$");


    @Override
    public boolean msgHandler(BotMessage message) {

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

        //只处理群组消息
        if (!message.isUserAuthenticated()) {
            return false;
        }

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

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

        //获取账本
        BotAccountBook accountBook = handlerManager.getAccountBookRepository().findByBelongIdAndType(message.getBotGroup().getDataId(), Constant.DATA_TYPE_MERCHANT);
        if (accountBook == null) {
            accountBook = new BotAccountBook();
            accountBook.setBelongId(message.getBotGroup().getDataId());
            accountBook.setBelongName(message.getBotGroup().getDataName());
            accountBook.setType(Constant.DATA_TYPE_MERCHANT);
            accountBook.setAgentBalance(0L);
            accountBook.setPaymentBalance(0L);
            accountBook = handlerManager.getAccountBookRepository().save(accountBook);
        }

        //代收记账处理
        if (paymentAccount.matcher(messageText).find()) {
            double paymentAccountAmount = Double.parseDouble(messageText.replace(PAYMENT_ACCOUNT_FLAG, ""));
            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()) {
            double agentAccountAmount = Double.parseDouble(messageText.replace(AGENT_ACCOUNT_FLAG, ""));
            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;
    }

}
