package org.jebot.handler.impl.channel;

import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.request.ReplyParameters;
import com.pengrad.telegrambot.request.SendMessage;
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.BotGroup;
import org.jebot.models.xxpay.PayPassage;

import java.util.List;
import java.util.regex.Pattern;

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

@Slf4j
public class ChannelBindGroupOrUnbindGroupHandler extends AbstractHandler {

    //根据通道编号绑定到群组
    private static final Pattern BIND_CHANNEL = Pattern.compile("^" + BIND_CHANNEL_FLAG + "[a-zA-Z0-9]+(,[a-zA-Z0-9]+)*$");

    private static final Pattern BIND_CODEPRO = Pattern.compile("^" + BIND_CODEPRO_FLAG + "[a-zA-Z0-9]+(,[a-zA-Z0-9]+)*$");



    //根据通道编号解绑群组
    private static final Pattern UNBIND_CHANNEL = Pattern.compile("^" + UNBIND_CHANNEL_FLAG + "[a-zA-Z0-9]+(,[a-zA-Z0-9]+)*$");
    private static final Pattern UNBIND_CODEPRO = Pattern.compile("^" + UNBIND_CODEPRO_FLAG + "[a-zA-Z0-9]+(,[a-zA-Z0-9]+)*$");

    @Override
    public boolean msgHandler(BotMessage botMessage) {

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

        //忽略商户群组消息
        if (botMessage.isGroupMch()) {
            return false;
        }

        //需要管理员权限
        if (!botMessage.isUserAuthenticated()) {
            return false;
        }

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

        //群组内管理员发送绑定命令
        if (BIND_CHANNEL.matcher(botMessage.getMessageText()).find()) {
            bindChannelByChannelId(botMessage);
            return true;
        }

        //判断消息是否包含解绑商户号的指令
        if (UNBIND_CHANNEL.matcher(botMessage.getMessageText()).find()) {
            String[] channelIds = getChannelIds(botMessage.getMessageText(), UNBIND_CHANNEL_FLAG);
            for (String channelId : channelIds) {
                this.handlerManager.getGroupRepository().deleteByDataIDAndDataType(Long.valueOf(channelId), Constant.DATA_TYPE_CHANNEL);
            }
            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;
        }


        //码商部分 通过码商id查询通道id 批量绑定解绑
        if (BIND_CODEPRO.matcher(botMessage.getMessageText()).find()) {
            bindChannelByCodeproId(botMessage);
            return true;
        }

        if (UNBIND_CODEPRO.matcher(botMessage.getMessageText()).find()) {
            // 1. 解析码商ID
            Long codeproId;
            try {
                codeproId = Long.valueOf(botMessage.getMessageText().replace(UNBIND_CODEPRO_FLAG, "").trim());
            } catch (NumberFormatException e) {
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "码商ID格式错误");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
                return true;
            }

            // 2. 查询该码商名下的通道列表
            List<PayPassage> passages = handlerManager.getPassageRepository().findByCodepro(codeproId);
            if (passages.isEmpty()) {
                SendMessage sendMessage = new SendMessage(botMessage.getMessage().chat().id(), "该码商没有绑定通道");
                sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
                botMessage.getTelegramBot().execute(sendMessage);
                return true;
            }

            // 3. 循环解绑每个通道
            for (PayPassage payPassage : passages) {
                handlerManager.getGroupRepository()
                        .deleteByDataIDAndDataType(payPassage.getId(), Constant.DATA_TYPE_CHANNEL);
            }

            // 4. 发送结果
            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;
        }

        return false;
    }


    //根据通道id绑定到群组
    private void bindChannelByChannelId(BotMessage botMessage) {
        StringBuilder sb = new StringBuilder();
        Chat chat = botMessage.getMessage().chat();
        for (String channelIdStr : getChannelIds(botMessage.getMessageText(), BIND_CHANNEL_FLAG)) {
            Long channelId = Long.valueOf(channelIdStr);
            //发起查询通道信息请求
            PayPassage payPassage = handlerManager.getPassageRepository().findByPassageId(channelId);
            if (payPassage==null) {
                continue;
            }

            BotGroup botGroup = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(channelId, Constant.DATA_TYPE_CHANNEL);
            if (botGroup == null) {
                //如果通道不存在，保存通道
                botGroup = new BotGroup();
                botGroup.setDataId(channelId);
                botGroup.setDataName(payPassage.getPassageName());
                botGroup.setGroupId(chat.id());
                botGroup.setGroupName(chat.title());
                botGroup.setDataType(Constant.DATA_TYPE_CHANNEL);
                this.handlerManager.getGroupRepository().save(botGroup);
                sb.append(String.format("%s:%s\r\n", channelId, "绑定成功"));
                continue;
            }

            if (botMessage.getMessage().chat().id().equals(botGroup.getGroupId())) {
                sb.append(String.format("%s:%s\r\n", channelId, "已绑定到当前群组"));
                continue;
            }

            //变更绑定到当前群组
            botGroup.setGroupId(chat.id());
            this.handlerManager.getGroupRepository().save(botGroup);
            sb.append(String.format("%s:%s\r\n", channelId, String.format("从绑定 %s 群组变更为绑定 %s 群组\r\n", payPassage.getPassageName(), chat.title())));
        }
        SendMessage sendMessage = new SendMessage(chat.id(), sb.toString());
        sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
        SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
        if (!execute.isOk()) {
            log.error("绑定通道结果发送失败: {}", execute);
        }
    }

    private void bindChannelByCodeproId(BotMessage botMessage) {
        StringBuilder sb = new StringBuilder();
        Chat chat = botMessage.getMessage().chat();

        // 1. 获取码商ID
        Long codeproId;
        try {
            codeproId = Long.valueOf(botMessage.getMessageText().replace(BIND_CODEPRO_FLAG, "").trim());
        } catch (NumberFormatException e) {
            SendMessage sendMessage = new SendMessage(chat.id(), "码商ID格式错误");
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            botMessage.getTelegramBot().execute(sendMessage);
            return;
        }

        // 2. 根据码商ID查询通道列表
        List<PayPassage> passages = handlerManager.getPassageRepository().findByCodepro(codeproId);
        if (passages.isEmpty()) {
            SendMessage sendMessage = new SendMessage(chat.id(), "该码商没有对应的通道");
            sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
            botMessage.getTelegramBot().execute(sendMessage);
            return;
        }

        // 3. 循环绑定每个通道
        for (PayPassage payPassage : passages) {
            Long channelId = payPassage.getId();

            BotGroup botGroup = handlerManager.getGroupRepository()
                    .findBotGroupByDataIdAndDataType(channelId, Constant.DATA_TYPE_CHANNEL);

            if (botGroup == null) {
                // 通道不存在，保存通道绑定信息
                botGroup = new BotGroup();
                botGroup.setDataId(channelId);
                botGroup.setDataName(payPassage.getPassageName());
                botGroup.setGroupId(chat.id());
                botGroup.setGroupName(chat.title());
                botGroup.setDataType(Constant.DATA_TYPE_CHANNEL);
                handlerManager.getGroupRepository().save(botGroup);
                sb.append(String.format("%s:%s\r\n", channelId, "绑定成功"));
                continue;
            }

            if (chat.id().equals(botGroup.getGroupId())) {
                sb.append(String.format("%s:%s\r\n", channelId, "已绑定到当前群组"));
                continue;
            }

            // 变更绑定到当前群组
            botGroup.setGroupId(chat.id());
            handlerManager.getGroupRepository().save(botGroup);
            sb.append(String.format("%s:%s\r\n", channelId, String.format("从绑定 %s 群组变更为绑定 %s 群组", payPassage.getPassageName(), chat.title())));
        }

        // 4. 发送绑定结果
        SendMessage sendMessage = new SendMessage(chat.id(), sb.toString());
        sendMessage.replyParameters(new ReplyParameters(botMessage.getMessage().messageId()));
        SendResponse execute = botMessage.getTelegramBot().execute(sendMessage);
        if (!execute.isOk()) {
            log.error("绑定通道结果发送失败: {}", execute);
        }
    }


    private static String[] getChannelIds(String text, String replaceStr) {
        String channelIdsStr = text.replace(replaceStr, "");
        if (channelIdsStr.contains(",")) {
            return channelIdsStr.split(",");
        }
        return new String[]{channelIdsStr};
    }
}
