package com.fastbee.deviceData.api.renke.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fastbee.deviceData.api.renke.constant.RenKeDeviceTypeConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RenKeUserDeviceOverview {
    @Autowired
    private RenKeAuthorizationService authorizationService;
    public Map getsysAllUserDevice() {
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/entrance/device/getsysUserDevice")
                .header("token", authorizationService.getToken())
                .execute();
        String resultObjectStr = response.body();
        if (StringUtils.isBlank(response.toString())) {
            throw new RuntimeException("获取token失败!");
        }
        JSONObject respBody = JSONUtil.parseObj(resultObjectStr);
        JSONArray realtimeDataList = JSONUtil.parseArray(respBody.get("data"));
        Map<String,Integer> map = new HashMap<>();
        //map = realtimeDataList.stream().collect(Collectors.groupingBy(obj -> ((JSONObject) obj).getStr("deviceType")));
        Integer MET = 0;
        Integer WORM = 0;
        Integer Irrigation = 0;
        Integer Worm = 0;
        Integer Soil =0;
        Integer Spore = 0;
        Integer Camera = 0;
        for (Object jsonObject : realtimeDataList) {
            JSONObject josnConversion = (JSONObject) jsonObject;
            if (RenKeDeviceTypeConstant.WORM.equals(josnConversion.get("deviceType"))) {
                WORM=WORM+1;
            } else if (RenKeDeviceTypeConstant.MET.equals(josnConversion.get("deviceType"))) {
                MET=MET+1;
            }else if (RenKeDeviceTypeConstant.Irrigation.equals(josnConversion.get("deviceType"))) {
                Irrigation=Irrigation+1;
            } else if (RenKeDeviceTypeConstant.Camera.equals(josnConversion.get("deviceType"))) {
                Camera=Camera+1;
            } else if (RenKeDeviceTypeConstant.Worm.equals(josnConversion.get("deviceType"))) {
                Worm=Worm+1;
            } else if (RenKeDeviceTypeConstant.Soil.equals(josnConversion.get("deviceType"))) {
                Soil=Soil+1;
            } else if (RenKeDeviceTypeConstant.Spore.equals(josnConversion.get("deviceType"))) {
                Spore=Spore+1;
            }
        }
        map.put("MET",MET);
        map.put("Worm",Worm);
        map.put("Irrigation",Irrigation);
        map.put("Camera",Camera);
        map.put("wormFlagship",WORM);
        map.put("Soil",Soil);
        map.put("Spore",Spore);
        return map;
    }
}
