package com.yutou.qqbot.models.setu;


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

import com.yutou.qqbot.Annotations.UseModel;
import com.yutou.qqbot.QQBotManager;
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 net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.event.events.MessageEvent;
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.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() {
        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");
                    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);
                    Log.i("今日涩图:"+builder.toString());
                }
            }
        }else {
            Log.i("今日没有涩图");
        }
    }

    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", db_user) != 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, 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;
        }
        group=qq;
        String msg=event.getMessage().contentToString();
        if ("[图片]".equals(msg.trim())) {
            Image image = (Image) event.getMessage().stream().filter(Image.class::isInstance).findFirst().orElse(null);
            if (image != null) {
                setuBuilder(image, (GroupMessageEvent) 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 sender=event.getSender().getId()+"";
                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)){
            printTodaySetu();
        }
    }

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

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

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