package org.jebot.handler.impl.merchant;

import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.response.SendResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
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.MchAccount;

import java.util.regex.Pattern;

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

@Slf4j
public class MerchantBindGroupOrUnbindGroupHandler extends AbstractHandler {

    //解绑商户与群组绑定
    private static final Pattern UNBIND_MCH = Pattern.compile("^" + UNBIND_MCH_FLAG + "[a-zA-Z0-9]*$");

    //将群组与商户绑定
    private static final Pattern BIND_MCH = Pattern.compile("^" + BIND_MCH_FLAG + "[a-zA-Z0-9]*$");

    //群组+商户与支付地址绑定
    private static final Pattern BIND_MCH_URL = Pattern.compile("^" + BIND_MCH_USTDURL + "[a-zA-Z0-9]*$");

    @Override
    public boolean msgHandler(BotMessage botMessage) {

        //只处理来自管理消息
        if (!botMessage.isUserAuthenticated()) {
            return false;
        }

        String text = botMessage.getMessage().text();
        if (Strings.isEmpty(text)) {
            return false;
        }

        //根据商户号绑定商户群组
        if (BIND_MCH.matcher(text).find()) {
            bindMerchantGroupByMchId(botMessage);
            return true;
        }

        //绑定url
        if (BIND_MCH_URL.matcher(text).find()) {
            bindMerchantGroupByUrl(botMessage);
            return true;
        }

        //解绑商户群组
        if (UNBIND_MCH_FLAG.equals(text)) {
            unbindByGroup(botMessage);
            return true;
        }

        //根据商户号解绑商户群组
        if (UNBIND_MCH.matcher(text).find()) {
            unbindByMerchant(botMessage);
            return true;
        }

        return false;
    }

    //根据商户id绑定商户群组
    private void bindMerchantGroupByMchId(BotMessage botMessage) {
        Long mchId = Long.valueOf(botMessage.getMessage().text().replace(BIND_MCH_FLAG, ""));//获取商户号

        //当前群组是否绑定了数据
        if (botMessage.isGroupAuthenticated()) {
            //判断当前群组是否绑定商户号
            if (Constant.DATA_TYPE_MERCHANT.equalsIgnoreCase(botMessage.getBotGroup().getDataType())) {
                if (botMessage.getBotGroup().getDataId().equals(mchId)) {
                    botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前群组已与当前商户绑定"));
                } else {
                    botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前群组已绑定其他商户，请先解绑！"));
                }
                return;
            }

            //判断当前群组是否绑定通道号
            if (Constant.DATA_TYPE_CHANNEL.equalsIgnoreCase(botMessage.getBotGroup().getDataType())) {
                botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前群组已绑定通道，请先解绑！"));
                return;
            }
            return;

        }

        //根据商户号查询商户信息
        MchAccount mchAccount = handlerManager.getMchAccountRepository().findByMchId(mchId);
        if (mchAccount == null) {
            // 如果商户号不存在，返回提示
            botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "当前商户号不存在"));
            return;
        }

        //获取群组 ID
        Long chatId = botMessage.getMessage().chat().id();
        //查询当前群组是否绑定商户号
        BotGroup merchant = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(mchId, Constant.DATA_TYPE_MERCHANT);
        if (merchant != null) {
            //如果商户号已经存在，返回提示
            SendResponse execute = botMessage.getTelegramBot().execute(new SendMessage(chatId, String.format("当前商户已在群组 %s 绑定，请先解绑！", merchant.getGroupName())));
            if (!execute.isOk()) {
                log.error("绑定商户号结果发送失败: {}", execute);
            }
            return;
        }


        // 如果商户信息不存在，保存商户信息
        BotGroup botMerchant = new BotGroup();//创建商户对象
        botMerchant.setDataId(mchId);//设置商户号
        botMerchant.setDataName(mchAccount.getName());//设置商户名称
        botMerchant.setDataType(Constant.DATA_TYPE_MERCHANT);//设置数据类型
        botMerchant.setGroupId(chatId);//设置群组 ID
        botMerchant.setGroupName(botMessage.getMessage().chat().title());//设置群组名称
        this.handlerManager.getGroupRepository().save(botMerchant);
        botMessage.getTelegramBot().execute(new SendMessage(chatId, "绑定成功"));
    }


    //绑定url和商户
    private void bindMerchantGroupByUrl(BotMessage botMessage) {
        String url = botMessage.getMessage().text().replace(BIND_MCH_USTDURL, "");//获取url
        if (!botMessage.isGroupAuthenticated()) {
            botMessage.getTelegramBot().execute(new SendMessage(botMessage.getMessage().chat().id(), "请先绑定商户再进行操作！"));
            return;
        }
        //获取群组 ID
        Long chatId = botMessage.getMessage().chat().id();
        //查询当前群组是否绑定商户号
        BotGroup merchant = this.handlerManager.getGroupRepository().findBotGroupByGroupIdAndDataType(chatId, Constant.DATA_TYPE_MERCHANT);
        this.handlerManager.getGroupRepository().updateUrlById(url, merchant.getId());
        if (merchant.getUstdUrl() != null) {
            //如果商户号已经存在，返回提示
//            SendResponse execute = botMessage.getTelegramBot().execute(new SendMessage(chatId, String.format("当前商户已绑定固定地址 %s ，请先解绑！", merchant.getUstdUrl())));
//            if (!execute.isOk()) {
//                log.error("绑定商户固定地址结果发送失败: {}", execute);
//            }
//            return;
            botMessage.getTelegramBot().execute(new SendMessage(chatId, "固定地址已从" + merchant.getUstdUrl() + "成功替换为" + url));
        } else {
            botMessage.getTelegramBot().execute(new SendMessage(chatId, "固定地址绑定成功"));
        }
    }

    private void unbindByMerchant(BotMessage botMessage) {
        Long mchId = Long.valueOf(botMessage.getMessage().text().replace(UNBIND_MCH_FLAG, ""));//移除解绑标识
        Long chatId = botMessage.getMessage().chat().id();//获取群组 ID
        BotGroup merchant = this.handlerManager.getGroupRepository().findBotGroupByDataIdAndDataType(mchId, Constant.DATA_TYPE_MERCHANT);//查询商户号
        if (merchant == null) {
            // 如果商户号不存在，返回提示
            botMessage.getTelegramBot().execute(new SendMessage(chatId, "当前商户号不存在"));
            return;
        }
        // 删除商户号
        this.handlerManager.getGroupRepository().delete(merchant);
        // 返回提示
        botMessage.getTelegramBot().execute(new SendMessage(chatId, "解绑成功"));
    }

    private void unbindByGroup(BotMessage botMessage) {
        Long chatId = botMessage.getMessage().chat().id();
        BotGroup botMerchantGroup = botMessage.getBotGroup();
        if (botMerchantGroup == null) {
            // 如果商户号不存在，返回提示
            botMessage.getTelegramBot().execute(new SendMessage(chatId, "当前群组未绑定"));
            return;
        }

        // 判断群组是否绑定商户号
        if (Constant.DATA_TYPE_MERCHANT.equalsIgnoreCase(botMerchantGroup.getDataType())) {
            // 删除群组
            this.handlerManager.getGroupRepository().delete(botMerchantGroup);
            // 返回提示
            botMessage.getTelegramBot().execute(new SendMessage(chatId, "解绑成功"));
        }

    }


}
