package com.yutou.qqbot.models.XiaoMi;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
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.HttpTools;
import com.yutou.qqbot.utlis.RedisTools;
import com.yutou.qqbot.utlis.XiaoMiRouter;
import com.yutou.napcat.event.MessageEvent;

import java.util.HashSet;
import java.util.Set;
@UseModel
public class MiRouter extends Model {
    public static String redis_key = "MiRouterDevices";

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

    @Override
    public String[] getUsePowers() {
        return new String[]{
                QQFromCommands.ROUTER_ADD,
                QQFromCommands.ROUTER_DEL
        };
    }

    @Override
    public String getModelName() {
        return "小米路由器";
    }

    @Override
    public void onMessage(Long qq, MessageEvent event, boolean isGroup) {
        super.onMessage(qq, event, isGroup);
        if (msg.equals(QQFromCommands.ROUTER_ADD)) {
            String url = "http://192.168.31.88:8002/router/device/add.do?qq=" + qq;
            QQBotManager.getInstance().sendMessage(qq, "点击该链接完成设备添加:\n" + url);
        } else if (msg.equals(QQFromCommands.ROUTER_DEL)) {
            String url = "http://192.168.31.88:8002/router/device/del.do?qq=" + qq;
            QQBotManager.getInstance().sendMessage(qq, "点击该删除设备:\n" + url);
        }
    }

    private static boolean isRunTime = true;

    @Override
    public void onTime(Long qq,String time) {
        super.onTime(qq,time);
        if (isRunTime) {
            return;
        }
        isRunTime = true;
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
        isRunTime = false;
    }
    private void run()throws  Exception{
        String url = XiaoMiRouter.getInstance().getDeviceListUrl();
        JSONObject json = JSON.parseObject(HttpTools.get(url));
        if (json.getInteger("code") == 0) {
            String _tmp = RedisTools.get(redis_key);
            if (_tmp == null) {
                return;
            }
            JSONArray devices = JSON.parseArray(_tmp);
            JSONArray devs =JSON.parseArray(devices.toString());
            JSONArray array = json.getJSONArray("list");
            Set<String> links = new HashSet<>();
            for (Object o : array) {
                JSONObject item = (JSONObject) o;
                for (Object device : devices) {
                    JSONObject _device = (JSONObject) device;
                    devs.remove(_device);
                    if (_device.getString("mac").equals(item.getString("mac")) && !_device.getBooleanValue("online")) {
                        StringBuilder builder = new StringBuilder();
                        builder.append(item.getString("oname"));
                        builder.append(" 欢迎回家！").append("\n");
                        builder.append("点击该链接开门:").append("\n");
                        builder.append("http://192.168.31.88:802/openDoor.html");
                        QQBotManager.getInstance().sendMessage(_device.getLong("qq"), builder.toString());
                        _device.put("online", true);
                        _device.put("name", item.getString("oname"));
                    }
                    if (_device.getString("mac").equals(item.getString("mac")) && _device.getBooleanValue("online")) {
                        links.add(_device.getString("mac"));
                        _device.put("linkTime", Long.parseLong(item.getJSONObject("statistics").getString("online")));
                    }
                    devs.add(_device);
                }
            }
            devices = JSON.parseArray(devs.toString());
            for (Object device : devices) {
                JSONObject item = (JSONObject) device;
                if (!links.contains(item.getString("mac")) && item.getLong("linkTime") != 0) {
                    devs.remove(device);
                    String builder = "你的设备:" +
                            item.getString("name") +
                            "已下线" + "\n" +
                            "在线时长:" + getOnLineTime(item.getString("linkTime")) + "\n";
                    QQBotManager.getInstance().sendMessage(item.getLong("qq"), builder);
                    item.put("online", false);
                    item.put("linkTime", 0);
                    devs.add(item);
                }
            }
            RedisTools.set(redis_key, devs.toString());
        }else {
            XiaoMiRouter.getInstance().setNotToken();
        }
    }

    private String getOnLineTime(String online) {
        long time = Long.parseLong(online);
        long day = time / 24 / 60 / 60;
        long h = time / 60 / 60 % 24;
        long m = time / 60 % 60;
        long s = time % 60;
        return String.format("%02d天%02d时%02d分%02d秒", day, h, m, s);
    }
}
