package com.fastbee.iot.timer;

import cn.hutool.core.date.DateTime;
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 com.fastbee.deviceData.api.renke.service.RenKeAuthorizationService;
import com.fastbee.deviceData.domain.DeviceRealtimedataWorms;

import com.fastbee.deviceData.service.impl.DeviceRealtimedataWormsServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author mijiupro
 */
@Component("renkeDeviceDateTask")
public class DeviceDateTask {
//

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DeviceRealtimedataWormsServiceImpl deviceRealtimedataWormsServiceImpl;

    @Autowired
    private RenKeAuthorizationService renKeAuthorizationService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 在执行定时任务中出现了异常会终止调度，所以需要捕获异常以便于下一轮
     * 执行，不会影响下一次执行
     */
    public void getRenkeDeviceRealtimeData() throws Exception{

        //获取设备实时数据
        //请求参数
        HttpResponse response = HttpRequest.get("http://api.farm.0531yun.cn/api/v2.0/entrance/device/getRealTimeData")
                .header("token", renKeAuthorizationService.getToken())
                .execute();
        String respBodyStr = response.body();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取设备实时数据失败!");
        }
        JSONObject respBody = JSONUtil.parseObj(respBodyStr);
        JSONArray realtimeList = JSONUtil.parseArray(respBody.get("data"));
//        threadPoolTaskExecutor.execute( () -> {System.err.println("设备实时数据："+realtimeList);});

        //TODO 解析实时数据保存到数据库
        for (Object realtimeData : realtimeList){
            JSONObject jsonConversion = JSONUtil.parseObj(realtimeData);
            if (RenKeDeviceTypeConstant.WORM.equals(jsonConversion.get("deviceType"))){
                JSONObject jsonObject1 = JSONUtil.parseObj(jsonConversion.get("data"));
                DeviceRealtimedataWorms deviceRealtimedataWorms = JSONUtil.toBean(jsonObject1, DeviceRealtimedataWorms.class);
                deviceRealtimedataWorms.setCreateTime(DateTime.now());
//                System.err.println("序列化为蠕虫设备数据类："+deviceRealtimedataWorms);
                if(deviceRealtimedataWormsServiceImpl.insertDeviceRealtimedataWorms(deviceRealtimedataWorms)!=1){
                    System.out.println("插入失败!");
                };
            }

        }
    }


}

