package com.yutou.nas.utils;

import com.yutou.nas.NasApplication;
import com.yutou.nas.bangumi.BangumiTools;
import com.yutou.nas.interfaces.DownloadInterface;
import com.yutou.nas.other.QQAudio;
import com.yutou.nas.other.QQSetu;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactory;
import net.mamoe.mirai.event.GlobalEventChannel;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.BotConfiguration;
import net.mamoe.mirai.utils.ExternalResource;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QQBotManager {


    private static class QQCommands {
        private final static String QQ_HELP = "!help";
        private final static String QQ_SYSTEM_RESTART = "!restart";
        private final static String QQ_UPDATE_IP = "!更新ip";
        private final static String QQ_GET_IP = "!ip";
        private final static String QQ_OPEN_PC = "!开机";
        private final static String QQ_GET_VERSION = "!version";
        private final static String QQ_CMD = "!cmd";
        private final static String QQ_BANGUMI_TODAY = "!今日动画";
        private final static String QQ_BANGUMI_LIST = "!新番";
        private final static String QQ_BANGUMI_SUB = "!查动画";
        private final static String QQ_AUDIO = "!语音";
        private final static String QQ_AUDIO_OPEN_LAMP = "!开灯";
        private final static String QQ_AUDIO_OPEN_AIR = "!开空调";
        private final static String QQ_BT_RELOAD = "!刷BT";
        private final static String QQ_TOOLS_IDEA = "!idea";
        private final static String QQ_TOOLS_IDEA_FILE = "!idea>";
    }

    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;
            isInit = true;
            init();
        }
    }

    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long qq = 2476945931L;
                String password = "zhang34864394";
                if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("dev")) {
                    qq = 3620756944L;
                    password = "UAs6YBYMyxJU";
                }

                bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() {
                    {
                        setProtocol(MiraiProtocol.ANDROID_PAD);
                        fileBasedDeviceInfo("qq_bot_devices_info.json");
                        if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("nas")) {
                            noBotLog();
                            noNetworkLog();
                        }
                    }
                });
                //Events.registerEvents(bot, new MessageListener());
                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~");
                        com.yutou.nas.utils.Log.i(str);

                    }
                }).start();
                bot.join();

            }
        }).start();

    }

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

    public boolean isLogin() {
        return isLogin;
    }

    private Image getImage(File file) {
        if (bot != null) {
            return Objects.requireNonNull(bot.getGroup(qqGroup)).uploadImage(ExternalResource.create(file));
        }
        return null;
    }

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

    public void reportToDayBangumi() {
        getInstance().sendMessage(BangumiTools.reportToDayBangumi());
    }

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

    public String sendMessage(Long group, String text) {
        if (bot != null) {
            try {
                return Objects.requireNonNull(bot.getGroup(group)).sendMessage(text).toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getNotLoginQQ();
    }

    public void sendMessage(Long group, MessageChainBuilder builder) {
        if (bot != null) {
            Objects.requireNonNull(bot.getGroup(group)).sendMessage(builder.asMessageChain());
        }
    }


    public String sendMessage(File imageFile, String text) {
        try {
            if (bot != null) {
                Image image = getImage(imageFile);
                MessageChainBuilder builder = new MessageChainBuilder();
                if (image != null) {
                    builder.append(image);
                }
                builder.append(text);
                return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return getNotLoginQQ();
    }

    public String sendMessage(List<File> imgs, String text) {
        if (bot != null) {
            MessageChainBuilder builder = new MessageChainBuilder();
            for (File img : imgs) {
                builder.append(Objects.requireNonNull(getImage(img)));
            }
            builder.append(text);
            return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
        }
        return getNotLoginQQ();
    }

    public static List<String> getImages(String str) {
        List<String> list = new ArrayList<>();
        String regex = "<img(.*?)/img>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            list.add(matcher.group().replace("<img", "")
                    .replace("/img>", "")
                    .trim());
        }
        return list;
    }

    public static void main(String[] args) {
        getInstance();
    }

    private static class MessageListener implements Consumer<GroupMessageEvent> {


        @Override
        public void accept(GroupMessageEvent event) {
            String msg = event.getMessage().contentToString();
            switch (event.getGroup().getId() + "") {
                case qqGroup + "":
                    myGroup(msg);
                case "570197155":
                    new QQSetu().setu(msg, event);

            }
        }

        private void myGroup(String msg) {
            StringBuilder builder;
            msg = msg.replace("！", "!").toLowerCase();
            switch (msg) {
                case QQCommands.QQ_OPEN_PC:
                    RedisTools.Consumer.system("openPC", null);
                    String time = new SimpleDateFormat("HH").format(new Date());
                    if (Integer.parseInt(time) < 18) {
                        break;
                    }
                case QQCommands.QQ_AUDIO_OPEN_LAMP:
                    QQAudio.playText("小爱同学，开灯");
                    break;
                case QQCommands.QQ_AUDIO_OPEN_AIR:
                    QQAudio.playText("小爱同学，开空调");
                    break;
                case QQCommands.QQ_UPDATE_IP:
                    RedisTools.Consumer.system("updateIP", null);
                    break;
                case QQCommands.QQ_GET_IP:
                    RedisTools.Consumer.bot("getip");
                    break;
                case QQCommands.QQ_GET_VERSION:
                    sendVersion();
                    break;
                case QQCommands.QQ_BANGUMI_TODAY:
                    QQBotManager.getInstance().sendMessage(BangumiTools.reportToDayBangumi());
                    break;
                case QQCommands.QQ_BANGUMI_LIST:
                    getInstance().sendMessage("获取中...");
                    getInstance().sendMessage(BangumiTools.reportBangumiList());
                    break;
                case QQCommands.QQ_BT_RELOAD:
                    BTDownloadManager.getInstance().start();
                    break;
                case QQCommands.QQ_SYSTEM_RESTART:
                    getInstance().sendMessage("正在重启服务");
                    System.out.println("结束进程");
                    AppTools.exec("cd /media/yutou/4t/public/servier/tools && ./start.sh");
                    break;
                case QQCommands.QQ_HELP:
                    builder = new StringBuilder();
                    for (Field field : QQCommands.class.getDeclaredFields()) {
                        try {
                            field.setAccessible(true);
                            builder.append(field.get(null)).append("\n");
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    getInstance().sendMessage(builder.toString());
                    break;
                case QQCommands.QQ_TOOLS_IDEA:
                    builder = new StringBuilder();
                    for (String name : IdeaTools.getIdeaList()) {
                        builder.append(QQCommands.QQ_TOOLS_IDEA_FILE).append(name).append("\n");
                    }
                    getInstance().sendMessage(builder.toString());
                    break;
                default:
                    if (msg.startsWith(QQCommands.QQ_CMD)) {
                        RedisTools.Consumer.system("cmd", msg.replace(QQCommands.QQ_CMD, ""));
                    } else if (msg.startsWith(QQCommands.QQ_BANGUMI_SUB)) {
                        List<String> infos = null;
                        try {
                            int id = Integer.parseInt(msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim());
                            infos = BangumiTools.reportBangumiInfo(id);
                        } catch (Exception e) {
                            String key = msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim();
                            infos = BangumiTools.reportSearchBangumi(key);
                        }
                        for (String info : infos) {
                            List<String> imgs = new ArrayList<>();
                            if (info.contains("<img") && info.contains(" /img>")) {
                                imgs = getImages(info);
                                for (String img : imgs) {
                                    info = info.replace("<img " + img + " /img>", "");
                                }
                            }
                            sendImagesMsg(imgs, info);
                        }

                    } else if (msg.startsWith(QQCommands.QQ_AUDIO)) {
                        QQAudio.playText(msg.replace(QQCommands.QQ_AUDIO, ""));
                    }else if(msg.startsWith(QQCommands.QQ_TOOLS_IDEA_FILE)){
                        getInstance().sendMessage(IdeaTools.getIdea(msg.replace(QQCommands.QQ_TOOLS_IDEA_FILE,"")));
                    }
            }
        }


        private List<File> files;
        private int index = 0;

        private void sendImagesMsg(List<String> imgs, String text) {
            files = new ArrayList<>();
            index = 0;
            if (imgs.size() == 0) {
                getInstance().sendMessage(text);
                return;
            }
            for (String img : imgs) {
                Tools.download(img, new DownloadInterface() {
                    @Override
                    public void onDownload(File file) {
                        super.onDownload(file);
                        files.add(file);
                        send(imgs.size(), text);
                    }

                    @Override
                    public void onError(Exception e) {
                        super.onError(e);
                        index++;
                        send(imgs.size(), text);
                    }
                });
            }
        }

        private void send(int size, String text) {
            if ((files.size() + index) == size) {
                String str = getInstance().sendMessage(files, text);
                com.yutou.nas.utils.Log.i("str = " + str);
            }
        }

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

    }
}
