package com.yutou.qqbot.models.setu;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.napcat.QQDatabase;
import com.yutou.napcat.event.MessageEvent;
import com.yutou.napcat.handle.*;
import com.yutou.napcat.model.SourceFrom;
import com.yutou.qqbot.Annotations.UseModel;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.data.MessageChainBuilder;
import com.yutou.qqbot.interfaces.DownloadInterface;
import com.yutou.qqbot.models.Model;
import com.yutou.qqbot.utlis.HttpTools;
import com.yutou.qqbot.utlis.Log;
import com.yutou.qqbot.utlis.RedisTools;
import com.yutou.qqbot.utlis.StringUtils;
import redis.clients.jedis.Jedis;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@UseModel
public class GetSeTu extends Model {
    @Override
    public boolean isUserPublic() {
        return true;
    }

    @Override
    public String[] getUsePowers() {
        return new String[0];
    }

    @Override
    public String getModelName() {
        return "随机二次元图";
    }

    @Override
    public void onTime(Long qq, String time) {
        super.onTime(qq, time);
        if ("00:00:00".equals(time)) {
            del();
        } else if (RedisTools.get("Setu_time", "23:59:00").equals(time)) {
            send(qq);
        }
    }

    private void del() {
        Jedis redis = RedisTools.getRedis();
        redis.select(RedisTools.QQBOT_USER);
        Set<String> keys = redis.keys("Setu_*");
        for (String key : keys) {
            redis.del(key);
        }
        redis.close();
    }

    private void send(Long group) {
        Jedis redis = RedisTools.getRedis();
        redis.select(RedisTools.QQBOT_USER);
        String ret = redis.get("Setu_" + group);
        redis.close();
        MessageChainBuilder builder = null;
        if (!StringUtils.isEmpty(ret)) {
            JSONArray array = JSON.parseArray(ret);
            builder = new MessageChainBuilder();
            builder.append("各位老色胚们晚上好，现在公布本群涩图数据!");
            builder.append("\n");
            builder.append("本群今日共查询:");
            builder.append(String.valueOf(array.size()));
            builder.append("次!\n");
            builder.append("接下来公布大伙的XP系统:");
            builder.append("\n");
            Map<Long, List<String>> map = new HashMap<>();
            for (Object o : array) {
                JSONObject item = (JSONObject) o;
                List<String> tags = map.getOrDefault(item.getLong("user"), new ArrayList<>());
                tags.add(item.getString("key"));
                map.put(item.getLong("user"), tags);
            }
            Long maxQQ = -1L;
            int max = -1;
            for (Long qq : map.keySet()) {
                builder.append("------------------\n");
                List<String> list = map.get(qq);
                if (list.size() > max) {
                    max = list.size();
                    maxQQ = qq;
                }
                builder.append(new At(qq))
                        .append(":\n");
                for (String tag : list) {
                    if (StringUtils.isEmpty(tag)) {
                        tag = "随机";
                    }
                    builder.append(tag).append("\n");
                }
                builder.append("------------------\n");
            }
            builder.append("那么今日最色批的就是:");
            builder.append(new At(maxQQ));
            builder.append("\n");
            builder.append("如果炸群了请找他(\n");
            builder.append("明天见~");
        }
        if (builder != null) {
            QQBotManager.getInstance().sendMessage(QQDatabase.checkFriend(group), group, builder.toString());
        }
    }

    @Override
    public void onMessage(Long qq, MessageEvent event, boolean isGroup) {
        super.onMessage(qq, event, isGroup);
        boolean isRun = false;
        boolean isR18 = false;
        if (msg.contains("来点") && msg.contains("色图")) {
            isRun = true;
        } else if (msg.contains("来点") && msg.contains("涩图")) {
            isRun = true;
            isR18 = true;
            msg = msg.replace("涩图", "色图");
        }
        if (isRun) {
            Log.i(event.getSource().getFromId() + " > " + msg);
            Pattern pattern = Pattern.compile("来点(.*?)色图");
            Matcher matcher = pattern.matcher(msg);
            String key = null;
            if (matcher.find()) {
                key = matcher.group(1);
            }
            if (!getSeTu("tag", key, isR18, false, qq, event)) {
                if (!getSeTu("tag", key, isR18, true, qq, event)) {
                    if (!getSeTu("keyword", key, isR18, true, qq, event)) {
                        QQBotManager.getInstance().sendMessage(qq, "找不到喵~ 不如随便来点吧~");
                        getSeTu("tag", null, false, false, qq, event);
                    }
                }
            }

            JSONObject data = new JSONObject();
            data.put("user", event.getSource().getFromId());
            data.put("group", qq);
            data.put("key", key);

            String redis = RedisTools.get("Setu_" + qq);
            JSONArray array = new JSONArray();
            if (!StringUtils.isEmpty(redis)) {
                array = JSON.parseArray(redis);
            }
            array.add(data);
            RedisTools.set("Setu_" + qq, array.toString());
        }
    }

    private boolean getSeTu(String model, String key, boolean r18, boolean fuzzyR18, Long qq, MessageEvent event) {
        return getSeTu(model, key, r18, fuzzyR18, qq, event, 3);
    }

    private boolean getSeTu(String model, String key, boolean r18, boolean fuzzyR18, Long qq, MessageEvent event, int reset) {
        if (reset <= 0) {
            QQBotManager.getInstance().sendMessage(qq, "获取失败喵~");
            return false;
        }
        String url = "https://api.lolicon.app/setu/v2?r18=0&size=regular";
        if (r18) {
            url = "https://api.lolicon.app/setu/v2?r18=1&size=regular";
        }
        final String tmpKey = key;
        if (!StringUtils.isEmpty(key)) {
            if ("tag".equals(model)) {
                String[] keys = key.split(" ");
                StringBuilder keyBuilder = new StringBuilder();
                for (String _key : keys) {
                    keyBuilder.append(URLEncoder.encode(_key, StandardCharsets.UTF_8)).append("&tag=");
                }
                key = keyBuilder.toString();
                key = key.substring(0, key.length() - 5);
            } else {
                key = URLEncoder.encode(key, StandardCharsets.UTF_8);
            }
            if (r18) {
                url = "https://api.lolicon.app/setu/v2?" + model + "=" + key + "&r18=1&size=regular";
            } else {
                url = "https://api.lolicon.app/setu/v2?" + model + "=" + key + "&r18=0&size=regular";
            }
        }
        if (fuzzyR18) {
            url = url.replace("&r18=0", "&r18=2").replace("&r18=1", "&r18=2");
        }
        System.out.println("url = " + url);
        String ret = HttpTools.http_get(url, null, false);
        JSONObject json = JSON.parseObject(ret);
        if (json.getJSONArray("data").size() == 0) {
            return false;
        }
        JSONObject item = json.getJSONArray("data").getJSONObject(0);
        StringBuilder builder = new StringBuilder();
        builder.append(item.getString("title"));
        builder.append("\n");
        builder.append("P站ID:");
        builder.append(item.getInteger("pid"));
        builder.append("\n");
        builder.append("R18:");
        if (item.getBooleanValue("r18")) {
            builder.append("YES!");
        } else {
            builder.append("NO~");
        }
        builder.append("\n");
        builder.append("tags:");
        for (Object tags : item.getJSONArray("tags")) {
            builder.append(tags).append("、");
        }
        builder.append("\n看不到图?点这里:").append(item.getJSONObject("urls").getString("regular"));
        QQBotManager.getInstance().sendMessage(false, qq,
                new Reply(event.getMessageId()),
                new Text(builder.toString())
        );
        HttpTools.download(item.getJSONObject("urls").getString("regular"),
                System.currentTimeMillis() + ".png",
                true,
                new DownloadInterface() {
                    @Override
                    public void onDownload(File file) {
                        super.onDownload(file);
                        Log.i("下载完成");
                        QQBotManager.getInstance().sendMessage(false, qq,
                                new Image(file),
                                new Reply(event.getMessageId())
                        );
                    }

                    @Override
                    public void onError(Exception e) {
                        super.onError(e);
                        QQBotManager.getInstance().sendMessage(false, qq,
                                new Image(item.getJSONObject("urls").getString("regular")),
                                new Reply(event.getMessageId())
                        );
                    }
                }
        );


        return true;
    }

    public static void main(String[] args) {
        String msg = "来点色图";
        Pattern pattern = Pattern.compile("来点(.*?)色图");
        Matcher matcher = pattern.matcher(msg);
        MessageEvent event = new MessageEvent();
        SourceFrom sourceFrom = new SourceFrom();
        sourceFrom.setUserId(891655174L);
        event.setMessageType("private");
        event.setSource(sourceFrom);
        event.setGroupId(891655174L);
        event.setMessageId(-1);
        event.setRawMessage(msg);
        new GetSeTu().onMessage(891655174L, event, true);
    }
}
