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;

import java.util.concurrent.*;

// 定时任务工具类
class OrderStatusScheduler {
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
    private static final ConcurrentHashMap<String, Boolean> scheduledOrders = new ConcurrentHashMap<>();

    public static void scheduleCheck(String orderId, Runnable task) {
        // 避免重复任务
        if (scheduledOrders.putIfAbsent(orderId, true) != null) {
            return;
        }

        scheduler.schedule(() -> {
            try {
                task.run();
            } finally {
                scheduledOrders.remove(orderId);
            }
        }, 20, TimeUnit.SECONDS); // 延时 20 秒执行
    }
}

@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) {
                return false;
            }

            // 获取通道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);
            }

            // 延时 30 秒后查询订单状态（只查一次）
            OrderStatusScheduler.scheduleCheck(payOrder.getPayOrderId().toString(), () -> {
                PayOrder updatedOrder = handlerManager.getPayOrderRepository()
                        .findById(payOrder.getPayOrderId())
                        .orElse(null);

                String text;
                if (updatedOrder != null && updatedOrder.getStatus() == 2) {
                    text = "订单【" + updatedOrder.getPayOrderId() + "】已完成支付 ✅";
                } else {
                    text = "补单信息已提交,暂未收到款,成功后会自动回调~";
                }

                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), text);
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
            });

            return true;
        }
        return false;
    }
}
