package com.yutou.qqbot.Controllers;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.qqbot.models.XiaoMi.MiRouter;
import com.yutou.qqbot.utlis.HttpTools;
import com.yutou.qqbot.utlis.RedisTools;
import com.yutou.qqbot.utlis.XiaoMiRouter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/router/")
public class MiRouterDevices {
    @RequestMapping("device/add.do")
    @ResponseBody
    public String addDevice(HttpServletRequest request,String qq) {
        String data = RedisTools.get(MiRouter.redis_key);
        JSONArray array;
        if (data == null) {
            array = new JSONArray();
        } else {
            array = JSON.parseArray(data);
        }
        for (Object o : array) {
            JSONObject item = (JSONObject) o;
            if (item.getString("mac").equals(getRemoteAddress(request.getRemoteAddr()))) {
                return "已经添加过了";
            }
        }
        JSONObject item=new JSONObject();
        item.put("qq",qq);
        item.put("mac",getRemoteAddress(request.getRemoteAddr()));
        item.put("online",false);
        array.add(item);
        RedisTools.set(MiRouter.redis_key,array.toString());
        return "添加成功，关闭当前页面即可";
    }
    @ResponseBody
    @RequestMapping("device/del.do")
    public String delDevice(HttpServletRequest request,String qq){
        String data = RedisTools.get(MiRouter.redis_key);
        JSONArray array;
        if (data == null) {
            array = new JSONArray();
        } else {
            array = JSON.parseArray(data);
        }
        JSONArray _array= JSON.parseArray(array.toString());
        for (Object o : array) {
            JSONObject item = (JSONObject) o;
            if (item.getString("mac").equals(getRemoteAddress(request.getRemoteAddr()))) {
                _array.remove(item);
                RedisTools.set(MiRouter.redis_key,_array.toString());
                return "已成功删除";
            }
        }
        return "未找到该设备";
    }

    private String getRemoteAddress(String ip) {
        JSONObject data = JSON.parseObject(HttpTools.get(XiaoMiRouter.getInstance().getDeviceListUrl()));
        if (data.getInteger("code") == 0) {
                JSONArray array=data.getJSONArray("list");
            for (Object o : array) {
                JSONObject item= (JSONObject) o;
                if(item.getJSONArray("ip").getJSONObject(0).getString("ip").equals(ip)){
                    return item.getString("mac");
                }
            }
        }
        return null;

    }
}
