package org.jebot.handler.impl.complaint;

import cn.hutool.core.date.DateUtil;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.ReplyParameters;
import com.pengrad.telegrambot.request.CopyMessage;
import com.pengrad.telegrambot.request.DeleteMessage;
import com.pengrad.telegrambot.request.GetFile;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.MessageIdResponse;
import com.pengrad.telegrambot.response.SendResponse;
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.BotComplaint;
import org.jebot.models.jebot.BotGroup;
import org.jebot.models.xxpay.PayOrder;
import org.jebot.repository.jebot.BotAccountBookRepository;
import org.jebot.service.dto.UpdateBalance;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Date;


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

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

        //文字和图片都存在，类似投诉转发
        if (botMessage.isContainsTextAndPhoto()) {
            String orderId = botMessage.getMessage().caption().trim();

            BotComplaint botComplaint = this.handlerManager.getComplaintRepository().findByComplaintId(orderId);
            if (botComplaint != null) {
                log.warn("投诉单号已存在，跳过处理: {}", orderId);
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "订单重复");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
                if (!execute.isOk()) {
                    log.error("重复投诉结果发送失败: {}", execute);
                }
                return true;
            }

            //查询订单信息
            PayOrder payOrder = handlerManager.getPayOrderRepository().findByPayOrderIdOrChannelOrderNo(orderId);

            //判断订单是否存在
            if (payOrder == null) {
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "订单未找到");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
                if (!execute.isOk()) {
                    log.error("查询订单结果发送失败: {}", execute);
                }
                return true;
            }

            Long mchId = payOrder.getMchId();
            BotGroup merchantGroup = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(mchId, Constant.DATA_TYPE_MERCHANT);
            if (merchantGroup == null) {
                log.info("商户号未绑定群组: {}", mchId);
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "商户号未绑定群组");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
                if (!execute.isOk()) {
                    log.error("查询订单结果发送失败: {}", execute);
                }
                return true;
            }

            BotGroup channelGroup = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(payOrder.getPassageId(), Constant.DATA_TYPE_CHANNEL);
            if (channelGroup == null) {
                log.info("通道号未绑定群组: {}", payOrder.getPassageId());
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "通道号未绑定群组");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
                if (!execute.isOk()) {
                    log.error("查询订单结果发送失败: {}", execute);
                }
                return true;
            }

            botComplaint = new BotComplaint();
            botComplaint.setComplaintId(orderId);
            botComplaint.setMchId(merchantGroup.getDataId());
            botComplaint.setComplaintContent(payOrder.toString());
            Update update = botMessage.getUpdate();
            // 获取 file_id
            String fileId = update.message().photo()[update.message().photo().length - 1].fileId();

            // 获取文件路径
            String filePath = botMessage.getTelegramBot().execute(new GetFile(fileId)).file().filePath();


            //商户加预付金额
            //查询商户预付记账本
            BotAccountBookRepository accountBookRepository = handlerManager.getAccountBookRepository();
            BotAccountBook merchantAccountBook = accountBookRepository.findByBelongIdAndType(merchantGroup.getDataId(), Constant.DATA_TYPE_MERCHANT);
            if (merchantAccountBook == null) {
                merchantAccountBook = new BotAccountBook();
                merchantAccountBook.setBelongId(merchantGroup.getDataId());
                merchantAccountBook.setBelongName(merchantGroup.getDataName());
                merchantAccountBook.setType(Constant.DATA_TYPE_MERCHANT);
                merchantAccountBook.setPaymentBalance(0);
                merchantAccountBook.setAgentBalance(0);
                merchantAccountBook = accountBookRepository.save(merchantAccountBook);
            }

            BotAccountBook channelAccountBook = accountBookRepository.findByBelongIdAndType(channelGroup.getDataId(), Constant.DATA_TYPE_CHANNEL);
            if (channelAccountBook == null) {
                channelAccountBook = new BotAccountBook();
                channelAccountBook.setBelongId(merchantGroup.getDataId());
                channelAccountBook.setBelongName(merchantGroup.getDataName());
                channelAccountBook.setType(Constant.DATA_TYPE_MERCHANT);
                channelAccountBook.setPaymentBalance(0);
                channelAccountBook.setAgentBalance(0);
                channelAccountBook = accountBookRepository.save(merchantAccountBook);
            }

            double oldMerchantPaymentBalance = merchantAccountBook.getPaymentBalance();
            double oldChannelPaymentBalance = channelAccountBook.getPaymentBalance();
            double amount = payOrder.getAmount().movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue();
            double newMerchantPaymentBalance = BigDecimal.valueOf(oldMerchantPaymentBalance).movePointRight(Constant.AMOUNT_MOVE_POINT).
                    add(payOrder.getAmount()).movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue();
            double newChannelPaymentBalance = BigDecimal.valueOf(oldChannelPaymentBalance).movePointRight(Constant.AMOUNT_MOVE_POINT).
                    add(payOrder.getAmount()).movePointLeft(Constant.AMOUNT_MOVE_POINT).doubleValue();

            //转发消息到商户群组
            CopyMessage sendMerchantCopyMessage = new CopyMessage(merchantGroup.getGroupId(), update.message().chat().id(), update.message().messageId());
            sendMerchantCopyMessage.caption(payOrder.getMchOrderNo());

            //更新商户余额
            UpdateBalance updateMerchantPaymentBalance = new UpdateBalance();
            updateMerchantPaymentBalance.setId(merchantAccountBook.getId());
            updateMerchantPaymentBalance.setOldBalance(oldMerchantPaymentBalance);
            updateMerchantPaymentBalance.setNewBalance(newMerchantPaymentBalance);
            updateMerchantPaymentBalance.setAmount(amount);
            BotMessage merchantMessage = new BotMessage();
            merchantMessage.setBotGroup(merchantGroup);
            merchantMessage.setBotUser(botMessage.getBotUser());
            updateMerchantPaymentBalance.setMessage(merchantMessage);

            //更新通道余额
            UpdateBalance updateChannelPaymentBalance = new UpdateBalance();
            updateChannelPaymentBalance.setId(channelAccountBook.getId());
            updateChannelPaymentBalance.setOldBalance(oldChannelPaymentBalance);
            updateChannelPaymentBalance.setNewBalance(newChannelPaymentBalance);
            updateChannelPaymentBalance.setAmount(amount);
            BotMessage channelMessage = new BotMessage();
            channelMessage.setBotGroup(channelGroup);
            channelMessage.setBotUser(botMessage.getBotUser());
            updateChannelPaymentBalance.setMessage(channelMessage);
            //构建发出投诉单号到上游群组的消息
            StringBuilder stringBuilderChannel = new StringBuilder();
            stringBuilderChannel.append("投诉订单: ").append("\n");
            stringBuilderChannel.append("投诉金额: ").append(amount).append("\n");
            stringBuilderChannel.append("投诉前: ").append(oldChannelPaymentBalance).append("\n");
            stringBuilderChannel.append("投诉后: ").append(newChannelPaymentBalance).append("\n");
            SendMessage sendChannelMessage = new SendMessage(channelGroup.getGroupId(), stringBuilderChannel.toString());
            StringBuilder stringBuilderChannelOrder = new StringBuilder();
            stringBuilderChannelOrder.append("投诉订单: ").append("\n");
            stringBuilderChannelOrder.append("订单号: ").append(payOrder.getPayOrderId()).append("\n");
            stringBuilderChannelOrder.append("金额: ").append(amount).append("\n");
            stringBuilderChannelOrder.append("投诉时间: ").append(DateUtil.formatDateTime(new Date())).append("\n");
            SendMessage sendChannelMessageOrder = new SendMessage(channelGroup.getGroupId(), stringBuilderChannelOrder.toString());

            StringBuilder stringBuilderMerchant = new StringBuilder();
            stringBuilderMerchant.append("投诉订单: ").append("\n");
            stringBuilderMerchant.append("投诉金额: ").append(amount).append("\n");
            stringBuilderMerchant.append("投诉前: ").append(oldMerchantPaymentBalance).append("\n");
            stringBuilderMerchant.append("投诉后: ").append(newMerchantPaymentBalance).append("\n");
            SendMessage sendMerchantMessage = new SendMessage(merchantGroup.getGroupId(), stringBuilderMerchant.toString());
            MessageIdResponse merchantCopyResponse = null;
            SendResponse merchantMessageResponse = null;
            SendResponse channelMessageResponse = null;
            SendResponse channelOrderMessageResponse = null;
            try {
                merchantCopyResponse = botMessage.getTelegramBot().execute(sendMerchantCopyMessage);
                Thread.sleep(300);
                merchantMessageResponse = botMessage.getTelegramBot().execute(sendMerchantMessage);
                Thread.sleep(300);
                channelMessageResponse =   botMessage.getTelegramBot().execute(sendChannelMessage);
                Thread.sleep(300);
                channelOrderMessageResponse =   botMessage.getTelegramBot().execute(sendChannelMessageOrder);
                Thread.sleep(300);
                if (!merchantCopyResponse.isOk() || !merchantMessageResponse.isOk() || !channelMessageResponse.isOk()){
                    log.error("消息发送失败: {}", merchantCopyResponse);
                    throw new Exception("消息发送失败");
                }
            } catch (Exception e) {
                log.error("消息发送失败，开始撤回已发送的消息: {}", e.getMessage());
                try {
                    if (merchantCopyResponse != null && merchantCopyResponse.messageId() != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(merchantGroup.getGroupId(), merchantCopyResponse.messageId()));
                    }
                    if (merchantMessageResponse != null && merchantMessageResponse.message().messageId() != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(merchantGroup.getGroupId(), merchantMessageResponse.message().messageId()));
                    }
                    if (channelMessageResponse != null && channelMessageResponse.message().messageId()  != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(channelGroup.getGroupId(), channelMessageResponse.message().messageId() ));
                    }
                    if (channelOrderMessageResponse != null && channelOrderMessageResponse.message().messageId()  != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(channelGroup.getGroupId(), channelOrderMessageResponse.message().messageId() ));
                    }
                } catch (Exception rollbackException) {
                    log.error("消息撤回失败: {}", rollbackException.getMessage());
                }
            }

            try {
                handlerManager.getAccountBookService().updateMutiPaymentBalanceByIdAndPaymentBalance(updateMerchantPaymentBalance, updateChannelPaymentBalance);
            } catch (Exception e) {
                log.error("更新商户或通道余额失败: {}", e.getMessage());
                e.printStackTrace();
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "处理失败，请稍后再试");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
                try {
                    if (merchantCopyResponse != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(merchantGroup.getGroupId(), merchantCopyResponse.messageId()));
                    }
                    if (merchantMessageResponse != null && merchantMessageResponse.message() != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(merchantGroup.getGroupId(), merchantMessageResponse.message().messageId()));
                    }
                    if (channelMessageResponse != null && channelMessageResponse.message() != null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(channelGroup.getGroupId(), channelMessageResponse.message().messageId()));
                    }
                    if (channelOrderMessageResponse != null&& channelOrderMessageResponse.message() !=null) {
                        botMessage.getTelegramBot().execute(new DeleteMessage(channelGroup.getGroupId(), channelOrderMessageResponse.message().messageId()));
                    }
                } catch (Exception rollbackException) {
                    log.error("消息撤回失败: {}", rollbackException.getMessage());
                }
                return true;
            }

            // 下载图片并转换为 Base64
            SendMessage sendMessage = null;
            try {
                byte[] imageBytes = getImageBytes(botMessage, filePath);
                String base64Image = Base64.getEncoder().encodeToString(imageBytes);
                botComplaint.setComplaintPhoto(base64Image);
                this.handlerManager.getComplaintRepository().save(botComplaint);
                sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "入库成功");
            } catch (Exception e) {
                log.error("图片下载或转换失败: {}", e.getMessage());
                try {
                    botComplaint.setComplaintPhoto("图片下载或转换失败:" + e.getMessage());
                    this.handlerManager.getComplaintRepository().save(botComplaint);
                    sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "入库成功");
                } catch (Exception ex) {
                    log.error("保存投诉数据失败: {}", ex.getMessage());
                }
            }

            if (sendMessage == null) {
                sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "已发送下游，入库失败");
            }
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            SendResponse sendResponse = botMessage.getTelegramBot().execute(sendMessage);
            if (!sendResponse.isOk()) {
                log.error("投诉单号转发结果发送失败: {}", sendResponse);
            }
            return true;
        }
        return false;
    }

    private static byte[] getImageBytes(BotMessage botMessage, String filePath) throws IOException {
        String fileUrl = "https://api.telegram.org/file/bot" + botMessage.getTelegramBot().getToken() + "/" + filePath;
        HttpURLConnection connection = (HttpURLConnection) new URL(fileUrl).openConnection();
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        byte[] imageBytes;
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            byte[] temp = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(temp)) != -1) {
                buffer.write(temp, 0, bytesRead);
            }
            imageBytes = buffer.toByteArray();
        }
        return imageBytes;
    }
}
