package org.jebot.handler.impl.merchant;

import com.pengrad.telegrambot.model.request.ReplyParameters;
import com.pengrad.telegrambot.request.CopyMessage;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.MessageIdResponse;
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.BotGroup;
import org.jebot.models.xxpay.PayOrder;

@Slf4j
public class MerchantDropOrderHandler extends AbstractHandler {
    @Override
    public boolean msgHandler(BotMessage botMessage) {
        //判断是否类似掉单待处理
        if (botMessage.isContainsTextAndPhoto()) {
            //查询当前群组是否绑定商户号
            if (!botMessage.isGroupMch()) {
                return false;
            }

            //如果商户号存在，查询订单所属上游
            PayOrder payOrder = handlerManager.getPayOrderRepository().findByPayOrderIdOrMchOrderNo(botMessage.getMessage().caption().trim(), botMessage.getBotGroup().getDataId());
            if (payOrder == null) {
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "订单不存在");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
                return true;
            }

            //获取通道id
            Long channelId = payOrder.getPassageId();

            //根据通道id获取绑定的群组
            BotGroup botChannel = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(channelId, Constant.DATA_TYPE_CHANNEL);
            if (botChannel == null) {
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "订单通道未绑定群组");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
                return false;
            }

            //复制需要转发的掉单信息到通道群组
            CopyMessage message = new CopyMessage(botChannel.getGroupId(), botMessage.getMessage().chat().id(), botMessage.getMessage().messageId());
            message.caption(payOrder.getPayOrderId());
            MessageIdResponse execute = botMessage.getTelegramBot().execute(message);
            if (!execute.isOk()) {
                log.error("转发消息失败: {}", execute);
            }
            SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "处理成功");
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            botMessage.getTelegramBot().execute(sendMessage);
            return true;
        }

        return false;
    }
}
