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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class RenkeDeviceDataService {

    @Autowired
    private RenKeAuthorizationService authenticationService;

    /**
     * 获取设备实时数据
     * @param deviceAddrs 设备地址，支持多个用英文逗号分隔
     */
    public DeviceRealtimedataWorms setData(String deviceAddrs) {
        //处理鉴权
        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();
        if(StringUtils.isBlank(respBodyStr)) {
            throw new RuntimeException("获取设备实时数据失败!");
        }
        JSONObject respBody = JSONUtil.parseObj(respBodyStr);
        JSONArray realtimeDataList = JSONUtil.parseArray(respBody.get("data"));
        JSONObject jsonObject = JSONUtil.parseObj(realtimeDataList.get(0));
        JSONObject jsonObject1 = JSONUtil.parseObj(jsonObject.get("data"));
        //获取实时时间
        String realTime = jsonObject1.get("DTime").toString();
        DeviceRealtimedataWorms deviceRealtimedataWorms = JSONUtil.toBean(jsonObject1, DeviceRealtimedataWorms.class);
        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);
        return deviceRealtimedataWorms;
    }


    public static void main(String[] args) {
        RenkeDeviceDataService renkeDeviceDataService = new RenkeDeviceDataService();
        renkeDeviceDataService.setData("1017240042");
    }

}
