package com.ruoyi.monitorInterface.sennor.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.monitorInterface.sennor.api.API;
import com.ruoyi.monitorInterface.sennor.service.SennorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SennorServiceImpl implements SennorService {

    private static final Logger log = LoggerFactory.getLogger(SennorServiceImpl.class);

    @Resource
    private ConfigService configService;

    private String secretKey;



    //这个方法应该用定时任务三分钟调用一次
    @Override
    public AjaxResult getDeviceInfo(String deviceNumber) {
        secretKey = configService.getKey("sennorSecretKey");
        //先请求
        StringBuffer URI = new StringBuffer(configService.getKey("sennorURL")+ API.getDeviceInfo);
        URI.append("?secretKey=").append(secretKey);
        URI.append("&deviceNumber=").append(deviceNumber);
        String result = HttpRequest.get(URI.toString())
                .header("Content-Type", "application/json")
                .execute().body();
        log.info("Sennor 收到数据 ==> {}", result);
        //后推送
        JSONObject object;
        String res;
        try {
            object = JSONObject.parseObject(result);
            res = HttpRequest.post(configService.getKey("centerMonitorURL")+"device/saveSennorDeviceData")
                    .header("Content-Type", "application/json")
                    .body(object.toJSONString())
                    .execute().body();
            log.info("数据推送成功! data ===> {} , result ===> {}",result, res);
            return AjaxResult.success("数据推送成功!",res);
        }catch(Exception e){
            e.printStackTrace();
            log.error("数据推送失败! data ===> {} , result ===> {}",result, e.getMessage());
            return AjaxResult.error("数据推送失败!",result);
        }

    }

    @Override
    public JSONArray getDevideCodeMapByTypes(String types) {
        //先请求
        StringBuffer URI = new StringBuffer(configService.getKey("centerMonitorURL")+ "device/getDevideCodeMapByTypes");
        URI.append("?types=").append(types);
        String result = HttpRequest.get(URI.toString())
                .header("Content-Type", "application/json")
                .execute().body();
        //后推送
        JSONObject object;
        try {
            object = JSONObject.parseObject(result);
            if(object.getInteger("code") == 200){
                return object.getJSONArray("data");
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("服务端数据校验失败! data ===> {} , result ===> {}",result, e.getMessage());
        }
        return new JSONArray();
    }
}
