package com.yutou.qqbot.models.setu;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.yutou.napcat.QQDatabase;
import com.yutou.napcat.enums.MessageEnum;
import com.yutou.napcat.event.GroupMessageEvent;
import com.yutou.napcat.handle.*;
import com.yutou.napcat.http.NapCatApi;
import com.yutou.napcat.model.MessageBean;
import com.yutou.okhttp.HttpBody;
import com.yutou.qqbot.Annotations.UseModel;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.data.MessageChainBuilder;
import com.yutou.qqbot.models.Model;
import com.yutou.qqbot.utlis.AppTools;
import com.yutou.qqbot.utlis.Log;
import com.yutou.qqbot.utlis.RedisTools;
import com.yutou.napcat.event.MessageEvent;
import com.yutou.qqbot.utlis.StringUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@UseModel
public class QQSetu extends Model {

    private int db_print = 1;//统计结果
    private int db_user = 3;//当次数据
    private long group;
    private Timer timer;
    private static final Map<String, Float> setuScore = new HashMap<>();

    public void printTodaySetu() throws Exception {
        String redisKey = AppTools.getToDayTime() + "_setu";
        Log.i("今日涩图 redisKey = " + redisKey);
        String js = RedisTools.get(redisKey, db_print);
        if (js != null) {
            JSONObject json = JSON.parseObject(js);
            if (json.containsKey("isPrint") && json.getBooleanValue("isPrint")) {
                return;
            }
            Map<String, Float> groupAverage = new HashMap<>();
            Map<String, String> groupImage = new HashMap<>();
            JSONObject setu = null;
            for (String id : json.keySet()) {
                String group = json.getJSONObject(id).getJSONObject("info").getLong("group") + "";
                if (groupAverage.containsKey(group)) {
                    if (groupAverage.get(group) <= json.getJSONObject(id).getFloat("average")) {
                        groupAverage.put(group, json.getJSONObject(id).getFloat("average"));
                        groupImage.put(group, id);
                    }
                } else {
                    groupAverage.put(group, json.getJSONObject(id).getFloat("average"));
                    groupImage.put(group, id);
                }
            }
            for (String id : groupImage.keySet()) {
                setu = json.getJSONObject(groupImage.get(id));
                if (setu != null) {
                    json.put("isPrint", true);
                    RedisTools.set(db_print, redisKey, json.toJSONString());
                    JSONObject info = setu.getJSONObject("info");
                    JSONObject score = setu.getJSONObject("score");
                    HttpBody<MessageBean> body = NapCatApi.getMessageApi().getMessage(
                            MessageHandleBuild.create().setMessageId(String.valueOf(info.getLong("id"))).build()
                    ).execute().body();
                    List<BaseHandle<?>> sendList = new ArrayList<>();
                    if (body == null) {
                        sendList.add(new Text("[图片获取失败]"));
                        return;
                    }
                    MessageEvent handle = MessageEvent.parseHandleHttp(body.getSrc());
                    Image image = handle.findType(Image.class);
                    if (image == null) {
                        sendList.add(new Text("[图片获取失败]"));
                    } else {
                        sendList.add(image);
                    }

                    //builder.append(Image.fromId(info.getString("id")));
                    sendList.add(new Text(
                            "本日最佳涩图由", false
                    ));
                    sendList.add(new At(handle.getSource().getUserId()));
                    sendList.add(new Text("提供", false));
                    sendList.add(new Text("获得分数 ", false));
                    sendList.add(new Text(String.valueOf(setu.getFloat("average")), false));
                    sendList.add(new Text("共有 ", false));
                    sendList.add(new Text(String.valueOf(score.getIntValue("userNumber")), false));
                    sendList.add(new Text(" 人参与投票", false));
                    QQBotManager.getInstance().sendMessage(handle.isUser(), handle.getGroupId(), sendList);
                }
            }
        } else {
            Log.i("今日没有涩图");
        }
    }

    private boolean isSetu(Long length) {
        return length > 50000;
    }

    private void setuBuilder(Image image, MessageEvent event) {
        if (StringUtils.isEmpty(image.getData().getFileSize()) || !isSetu(Long.parseLong(image.getData().getFileSize()))) {
            return;
        }
        if (RedisTools.get(event.getGroupId() + "setu", db_user) != null) {
            printSetu(event.getGroupId());
        }
        setuScore.clear();
        JSONObject json = new JSONObject();
        json.put("id", event.getMessageId());
        RedisTools.set(event.getGroupId() + "setu", json.toJSONString(), 6 * 60, db_user);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        startTimer();
    }

    private void startTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!setuScore.isEmpty()) {
                    printSetu(group);
                }
                timer.cancel();
                timer = null;
            }
        }, (long) (0.9 * 60 * 1000));
    }

    private void printSetu(long group) {
        JSONObject jt = JSON.parseObject(RedisTools.get(group + "setu", db_user));
        String id = jt.getString("id");
        float average = 0;
        float max = 0;
        float min = 10;
        float length = 0;
        String maxName = "";
        String minName = "";
        if (setuScore.size() <= 1) {
            return;
        }
        for (String name : setuScore.keySet()) {
            length += setuScore.get(name);
            average += setuScore.get(name);
            if (setuScore.get(name) > max) {
                max = setuScore.get(name);
                maxName = name.split("\\|")[0];
            }
            if (setuScore.get(name) < min) {
                min = setuScore.get(name);
                minName = name.split("\\|")[0];
            }
        }
        JSONObject score = new JSONObject();
        score.put("max", max);
        score.put("min", min);
        score.put("sum", length);
        score.put("maxName", maxName);
        score.put("minName", minName);
        score.put("userNumber", setuScore.size());

        average = average / setuScore.size();
        String builder = "涩图评分:" + average + "\n " +
                "其中最高分由:" + maxName + " 给与：" + max + "\n " +
                "其中最低分由:" + minName + " 给与:" + min;
        QQBotManager.getInstance().sendMessage(group, builder);
        String st = RedisTools.get(AppTools.getToDayTime() + "_setu", db_print);
        JSONObject json;
        if (st == null) {
            json = new JSONObject();
        } else {
            json = JSON.parseObject(st);
        }
        if (!json.containsKey(id)) {
            JSONObject item;
            if (json.containsKey("item")) {
                item = json.getJSONObject("item");
            } else {
                item = new JSONObject();
            }

            item.put("score", score);
            item.put("info", jt);
            item.put("average", average);
            json.put(id, item);
            RedisTools.set(db_print, AppTools.getToDayTime() + "_setu", json.toJSONString());
        }
        RedisTools.remove(group + "setu", db_user);
        setuScore.clear();
    }

    @Override
    public void onMessage(Long qq, MessageEvent event, boolean isGroup) {
        if (!isGroup) {
            return;
        }
        Image image = event.hasType(MessageEnum.IMAGE) ? event.findType(Image.class) : null;
        if (image != null) {
            setuBuilder(image, event);
            return;
        }
        Text text = event.hasType(MessageEnum.TEXT) ? event.findType(Text.class) : null;
        if (text == null) {
            return;
        }
        try {
            if (text.toString().trim().length() > 3) {
                return;
            }
            float i = Float.parseFloat(text.toString().trim());
            if (i > 0 && i <= 10) {
                String name = event.getSource().getNickname();
                String sender = event.getSource().getUserId() + "";
                if (!setuScore.containsKey(name)) {
                    setuScore.put(name + "|" + sender, i);
                }
            }
        } catch (Exception ignored) {
        }
    }

    @Override
    public void onTime(Long qq, String time) {
        super.onTime(qq, time);
        if ("23:59:00".equals(time)) {
            try {
                printTodaySetu();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean isUserPublic() {
        return true;
    }

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

    @Override
    public String getModelName() {
        return "涩图评分";
    }
}
