package com.yutou.nas.other;


import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.utils.QQBotManager;
import com.yutou.nas.utils.RedisTools;
import com.yutou.nas.utils.Tools;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class QQSetu {
    public static void printTodaySetu() {
        String redisKey=Tools.getToDayTime() + "_setu";
        com.yutou.nas.utils.Log.i("redisKey = " + redisKey);
        String js = RedisTools.get(redisKey, 1);
        if (js != null) {
            JSONObject json = JSONObject.parseObject(js);
            if(json.containsKey("isPrint")&&json.getBoolean("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(1,redisKey,json.toJSONString());
                    JSONObject info=setu.getJSONObject("info");
                    JSONObject score=setu.getJSONObject("score");
                    MessageChainBuilder builder = new MessageChainBuilder();
                    builder.append(Image.fromId(info.getString("id")));
                    builder.append("本日最佳涩图由").append(new At(info.getLong("sourQQ"))).append("提供\n");
                    builder.append("获得分数 ").append(String.valueOf(setu.getFloat("average"))).append("\n");
                    builder.append("共有 ").append(String.valueOf(score.getIntValue("userNumber"))).append(" 人参与投票");
                    QQBotManager.getInstance().sendMessage(info.getLong("group"),builder);
                }
            }
        }
    }

    private boolean isSetu(Image image) {
        String url = Image.queryUrl(image);
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            int length = connection.getContentLength();
            connection.disconnect();
            if (length > 50000) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return false;
    }

    private void setuBuilder(Image image, GroupMessageEvent event) {
        if (!isSetu(image)) {
            return;
        }
        if (RedisTools.get(event.getGroup().getId()+"setu") != null) {
            printSetu(event.getGroup().getId());
        }
        setuScore.clear();
        JSONObject json = new JSONObject();
        json.put("id", image.getImageId());
        json.put("sourName", event.getSenderName());
        json.put("sourQQ", event.getSender().getId());
        json.put("group", event.getGroup().getId());
        RedisTools.set(event.getGroup().getId()+"setu", json.toJSONString(),6*60);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        startTimer(event.getGroup().getId());
    }

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

    private void printSetu(long group) {
        JSONObject jt = JSONObject.parseObject(RedisTools.get(group+"setu"));
        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(Tools.getToDayTime() + "_setu", 1);
        JSONObject json;
        if (st == null) {
            json = new JSONObject();
        } else {
            json = JSONObject.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(1, Tools.getToDayTime() + "_setu", json.toJSONString());
        }
        RedisTools.remove(group+"setu",0);
        setuScore.clear();
    }
    public void setu(String msg, GroupMessageEvent event) {
        if (msg.trim().equals("[图片]")) {
            Image image = (Image) event.getMessage().stream().filter(Image.class::isInstance).findFirst().orElse(null);
            if (image != null) {
                setuBuilder(image, event);
                return;
            }
        }
        try {
            if(msg.trim().length()>3){
                return;
            }
            float i = Float.parseFloat(msg.trim());
            if (i > 0 && i <= 10) {
                String name = event.getSenderName();
                String qq=event.getSender().getId()+"";
                if (!setuScore.containsKey(name)) {
                    setuScore.put(name+"|"+qq, i);
                }
            }
        } catch (Exception ignored) {
        }
    }

    private Timer timer;
    private static Map<String, Float> setuScore = new HashMap<>();
}
