package com.yutou.qqbot;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.qqbot.Listeners.QQMessageListener;
import com.yutou.qqbot.utlis.*;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactory;
import net.mamoe.mirai.event.GlobalEventChannel;
import net.mamoe.mirai.message.MessageReceipt;
import net.mamoe.mirai.message.data.*;
import net.mamoe.mirai.utils.BotConfiguration;
import net.mamoe.mirai.utils.ExternalResource;
import xyz.cssxsh.mirai.tool.FixProtocolVersion;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

public class QQBotManager {

    public static Long defGroup = 891655174L;
    public static Long defQQ = 583819556L;


    private static QQBotManager botManager = null;
    private Bot bot;
    private static final long qqGroup = 891655174L;
    private boolean isLogin = false;
    private static boolean isInit = false;


    private QQBotManager() {
        Object isRun = ConfigTools.load(ConfigTools.CONFIG, "qq_bot");
        if (isRun != null && (boolean) isRun) {
            isLogin = true;
            init();
        }
    }

    private void init() {
        new Thread(new Runnable() {
            private void reset() {
                try {
                    Log.i("QQBot", "签名加密服务未启动,1分钟后重试");
                    Thread.sleep(60 * 1000);
                    init();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void run() {
                String url=ConfigTools.load(ConfigTools.CONFIG,"sign_url",String.class);
                if(StringUtils.isEmpty(url)){
                    url="http://192.168.31.88:7400/";
                }
                String test = HttpTools.get(url);
                try {
                    JSONObject json = JSONObject.parseObject(test);
                    if (json.getInteger("code") != 0) {
                        reset();
                        return;
                    }
                } catch (Exception e) {
                    reset();
                    return;
                }
                long qq = ConfigTools.load(ConfigTools.CONFIG, "qq_number", Long.class);
                String password = ConfigTools.load(ConfigTools.CONFIG, "qq_password", String.class);
                System.out.println("qq = " + qq);
                System.out.println("password = " + password);
                FixProtocolVersion.load(BotConfiguration.MiraiProtocol.ANDROID_PAD);

                bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() {
                    {

                        setProtocol(MiraiProtocol.ANDROID_PAD);
                        fileBasedDeviceInfo("qq_bot_devices_info.json");
                        if ("nas".equals(ConfigTools.load(ConfigTools.CONFIG, "model"))) {
                            noBotLog();
                            noNetworkLog();
                        }
                    }
                });
                //Events.registerEvents(bot, new MessageListener());
                GlobalEventChannel.INSTANCE.registerListenerHost(new QQMessageListener());
                // GlobalEventChannel.INSTANCE.subscribeAlways(GroupMessageEvent.class, new MessageListener());
                bot.login();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        String str = sendMessage("姬妻酱上线拉~☆Daze~  当前版本:" + QQBotApplication.version);
                        Log.i(str);
                        isInit = true;
                    }
                }).start();
                bot.join();
            }
        }).start();

    }

    public synchronized static QQBotManager getInstance() {
        if (botManager == null && !isInit) {
            botManager = new QQBotManager();
        }
        return botManager;
    }

    public boolean isLogin() {
        return isLogin;
    }

    private Image getImage(File file, Long qq) {
        if (file == null) {
            return null;
        }
        if (bot != null) {
            ExternalResource resource = ExternalResource.create(file);
            Image image;
            if (QQNumberManager.getManager().isGroup(qq)) {
                image = Objects.requireNonNull(bot.getGroup(qq)).uploadImage(resource);
            } else {
                image = Objects.requireNonNull(bot.getFriend(qq)).uploadImage(resource);
            }
            try {
                resource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return image;
        }
        return null;
    }

    private String getNotLoginQQ() {
        return "没有登录QQ";
    }


    public String sendMessage(String text) {
        if (bot != null && !StringUtils.isEmpty(text)) {
            try {
                return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(text).toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getNotLoginQQ();
    }

    public MessageReceipt<?> sendMessage(Long group, String text) {
        if (bot != null) {
            try {
                if (QQNumberManager.getManager().isGroup(group)) {
                    return Objects.requireNonNull(bot.getGroup(group)).sendMessage(text);
                } else {
                    return Objects.requireNonNull(bot.getFriend(group)).sendMessage(text);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public MessageReceipt<?> sendMessage(Long group, MessageChainBuilder builder) {
        if (bot != null) {
            if (QQNumberManager.getManager().isGroup(group)) {
                System.out.println("发群");
                return Objects.requireNonNull(bot.getGroup(group)).sendMessage(builder.asMessageChain());
            } else {
                System.out.println("发个人");
                return Objects.requireNonNull(bot.getFriend(group)).sendMessage(builder.asMessageChain());
            }
        }
        return null;
    }

    public MessageReceipt<?> sendMessage(File imageFile, Long qq, String text) {
        return sendMessage(imageFile, qq, null, text);
    }

    public MessageReceipt<?> sendMessage(File imageFile, Long qq, MessageChain replyMessage, String text) {
        try {
            if (bot != null) {
                Image image = getImage(imageFile, qq);
                MessageChainBuilder builder = new MessageChainBuilder();
                if (replyMessage != null) {
                    builder.append(new QuoteReply(replyMessage));
                }
                if (image != null) {
                    builder.append(image);
                }
                List<String> list = PatternTools.getQQ(text);
                if (!list.isEmpty()) {
                    for (String _qq : list) {
                        String[] tmp = text.split(_qq);
                        builder.append(tmp[0]);
                        builder.append(new At(Long.parseLong(_qq.replace("@", ""))));
                        text = text.replace(tmp[0] + _qq, "");
                    }
                }
                builder.append(text);
                if (QQNumberManager.getManager().isGroup(qq)) {
                    return Objects.requireNonNull(bot.getGroup(qq)).sendMessage(builder.asMessageChain());
                } else {
                    return Objects.requireNonNull(bot.getFriend(qq)).sendMessage(builder.asMessageChain());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public MessageReceipt<?> sendMessage(File imageFile, String text) {
        return sendMessage(imageFile, qqGroup, text);
    }

    public String sendMessage(List<File> imgs, Long qq, String text) {
        System.out.println("imgs.size() = " + imgs.size());
        if (bot != null) {
            MessageChainBuilder builder = new MessageChainBuilder();
            for (File img : imgs) {
                builder.append(Objects.requireNonNull(getImage(img, qq)));
            }
            builder.append(text);
            if (QQNumberManager.getManager().isGroup(qq)) {
                return Objects.requireNonNull(bot.getGroup(qq)).sendMessage(builder.asMessageChain()).toString();
            } else {
                return Objects.requireNonNull(bot.getFriend(qq)).sendMessage(builder.asMessageChain()).toString();
            }
        }
        return getNotLoginQQ();
    }


    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("t1", 3234567890L);
        System.out.println("json = " + json);

        String tmp = json.toString();
        JSONObject json2 = JSON.parseObject(tmp);
        System.out.println("json2 = " + json2);
    }

    public void sendVersion() {
        String localVersion = QQBotApplication.version;
        String serverVersion = HttpTools.get("http://tools.yutou233.cn:8000/public/version.do?token=zIrsh9TUZP2lfRW753PannG49E7VJvor");
        String msg = "本地版本：" + localVersion + "\n" + "服务器版本：" + serverVersion;
        QQBotManager.getInstance().sendMessage(msg);
        AppTools.sendServer("服务版本查询", msg);
    }


    public Bot getBot() {
        return bot;
    }

    public void reLogin() {
        isInit=false;
        if(bot.isOnline()){
            bot.close();
        }
        init();
    }
}
