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.common.exception.ServiceException;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.deviceData.domain.DeviceRealtimedataWorms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RenkeWormDeviceDataService {

    @Autowired
    private RenKeAuthorizationService authenticationService;

    /**
     * 获取设备实时数据
     * @param deviceAddrs 设备地址，支持多个用英文逗号分隔
     */
    public List<DeviceRealtimedataWorms> setData(String deviceAddrs) {
        List<DeviceRealtimedataWorms> dataList =new ArrayList<>();

        //处理鉴权
        String token = authenticationService.getToken();
//        String token = new RenKeAuthorizationService().getToken();
        //获取设备基础实时数据
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/entrance/device/getRealTimeData")
                .header("token", token)
                .form("deviceAddrs", deviceAddrs)
                .execute();
        String respBodyStr = response.body();

        JSONObject respBody = JSONUtil.parseObj(respBodyStr);
//        System.err.println(respBodyStr);
        if(!respBody.get("code") .toString().equals("1000")){
            System.err.println(respBodyStr);
            throw new ServiceException("获取设备实时数据失败!");
        }
        JSONArray realtimeDataList = JSONUtil.parseArray(respBody.get("data"));
        realtimeDataList.forEach(o -> {
            DeviceRealtimedataWorms deviceRealtimedataWorms= new DeviceRealtimedataWorms();
            JSONObject dataObj = JSONUtil.parseObj(o);
            JSONObject jsonObject1 = JSONUtil.parseObj(dataObj .get("data"));
            //获取实时时间
            String realTime = jsonObject1.get("DTime").toString();
            //反序列化封装基础数据
            deviceRealtimedataWorms = JSONUtil.toBean(jsonObject1, DeviceRealtimedataWorms.class);
            //获取虫情设备关键数据
            HttpResponse response1 = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataAndWormDataAIBy?deviceAddr="+deviceAddrs)
                    .header("token", token)
//                .form( "deviceAddr", deviceAddrs)
//                //开始时间是5分钟前
//                .form("beginTime", DateTimeCalculationUtils.format(DateTimeCalculationUtils.minus(5, ChronoUnit.MINUTES)))
//                .form("endTime", DateUtils.getNowDate())
//                .form("pages", 1)
//                .form("limit", 10)
                    .execute();

//        HttpResponse response1 = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataList")
//                .header("token", token)
//                .form( "deviceAddr", deviceAddrs)
//                //开始时间是5分钟前
//                .form("beginTime", DateTimeCalculationUtils.format(DateTimeCalculationUtils.minus(5, ChronoUnit.MINUTES)))
//                .form("endTime", DateUtils.getNowDate())
//                .form("pages", 1)
//                .form("limit", 10)
//                .execute();


            String respBodyStr1 = response1.body();

            JSONObject respBody1 = JSONUtil.parseObj(respBodyStr1);
//        System.err.println(respBodyStr1);
            if(!respBody1.get("code") .toString().equals("1000")) {
                throw new RuntimeException("获取设备实时数据失败!");
            }
            System.err.println(respBody1);
            JSONArray jsonArray = JSONUtil.parseArray(respBody1.get("data"));
            JSONObject entries = JSONUtil.parseObj(jsonArray.get(0));

            //获取害虫种类以及数量
            JSONArray analyseData = JSONUtil.parseArray(entries.get("analyseData"));
            //有害虫时保存
//        if(!analyseData.isEmpty()){
            //获取拍照图片
            Object imagesUrl = entries .get("imagesUrl");
            //获取虫情分析后的图片地址
            Object analyseCoordUrl = entries .get("analyseCoordUrl");

            deviceRealtimedataWorms.setPestPhotos(analyseCoordUrl.toString());
            deviceRealtimedataWorms.setCamera(imagesUrl.toString());
//        }

            deviceRealtimedataWorms.setSaveTime(DateUtils.getNowDate());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = sdf.parse(realTime);
                deviceRealtimedataWorms.setRealTime(date);
            } catch (ParseException e) {
                throw new ServiceException("时间格式转换失败！");
            }
            System.err.println("虫情设备实时数据："+deviceRealtimedataWorms);
            dataList.add(deviceRealtimedataWorms);
        });

//        JSONObject jsonObject = JSONUtil.parseObj(realtimeDataList.get(0));
//        JSONObject jsonObject1 = JSONUtil.parseObj(jsonObject.get("data"));

        return dataList;
    }


    public static void main(String[] args) {
//        RenkeDeviceDataService renkeDeviceDataService = new RenkeDeviceDataService();
//        renkeDeviceDataService.setData("1017240042");
        HttpResponse response1 = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataAndWormDataAIBy?deviceAddr="+"1017240042")
                .header("token", "300591732787388355")
                .execute();
        String respBodyStr1 = response1.body();

        JSONObject respBody1 = JSONUtil.parseObj(respBodyStr1);
        System.err.println(respBodyStr1);
    }

}
