package com.fastbee.iot.strategy.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fastbee.deviceData.api.devlink.service.ZhanLianConfig;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.strategy.DeviceRealTimeDataGetStrategy;
import com.fastbee.iot.zhanlian.ZhanLianAuthorizationService;
import com.fastbee.iot.zhanlian.ZhanLianBaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * 展连设备获取实时数据
 */

@Component
public class ZhanLianDeviceRealTimeDataGetStrategy implements DeviceRealTimeDataGetStrategy {
    private final static String BASE_URL = "https://plat.developlink.cloud/prod-api/iot/data/forward";

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public JSONObject getDeviceRealTimeData(String deviceId) {

        //查询对应设备信息
        Device device = new LambdaQueryChainWrapper<>(deviceMapper)
                .select(Device::getDeviceId,Device::getSerialNumber,Device::getDevParams)
                .eq(Device::getSerialNumber,deviceId)
                .eq(Device::getDelFlag, 0)
                .one();
        if(device == null){
            throw new RuntimeException("展连设备不存在!设备id为："+deviceId);
        }

        //解析设备对接参数
        String devParams = device.getDevParams();
        if(StringUtils.isBlank(devParams)){
            throw new RuntimeException("展连设备对接参数为空!设备id为："+device.getDeviceId()+"设备序列号为："+device.getSerialNumber());
        }
        JSONArray paramArray = JSONUtil.parseArray(devParams);
        //解析参数列表建立map
        Map<String, String> params = new HashMap<>();
        //解析参数列表建立map
        paramArray.forEach(paramObj->{
            JSONObject entries = JSONUtil.parseObj(paramObj);
            Object key = entries.get("key");
            Object value = entries.get("value");
            params.put(key.toString(),value.toString());
        });

        //获取请求地址
        String authEndpoint = ZhanLianAuthorizationService.getAuthEndpoint(ZhanLianConfig.builder()
                        .ak(params.get("ak"))
                        .sk(params.get("sk"))
                        .authId( params.get("authId"))
                        .endpoint(BASE_URL)
                .build());
        //请求参数构建
        HashMap<String, Object> reqBody = new HashMap<>();
        reqBody.put("method","get");
        reqBody.put("path","api/v1/product/device/run_status");

        Map<String,Object> param =new HashMap<>();

        param.put("id", deviceId);
        reqBody.put("params",param);

        ZhanLianBaseService zhanLianBaseService = new ZhanLianBaseService();
        //请求设备
        // System.err.println(reqBody);
        JSONObject respObj = zhanLianBaseService.baseRequest(reqBody, authEndpoint);
        //解析设备实时数据
        JSONObject deviceRealTimeData = getDeviceRealTimeData(respObj, deviceId);
        //映射为数据存储对象
        return deviceRealTimeData;
    }

    /**
     * 根据设备id请求数据并解析设备实时数据为易于存储的map键值对
     * @param deviceId 设备id
     * @return 实时数据
     */
    public JSONObject getDeviceRealTimeData(JSONObject data ,String deviceId){

        //获取设备状态
        JSONObject jsonObjectData = JSONUtil.parseObj(data);
        Object status = jsonObjectData.get("status");
        //获取设备属性以及实时数据值
        Object properties = jsonObjectData.get("properties");
        //获取数据上报时间
        String time = jsonObjectData.get("lastOnlineTime").toString();
        JSONArray propertiesArray = JSONUtil.parseArray(properties);
        //获取设备各项属性实时数据
        //设备属性与值建立map
        JSONObject propertiesMap = new JSONObject();
        propertiesArray.forEach(p -> {
            Object property = JSONUtil.parseObj(p).get("property");
            JSONObject propertyMap = JSONUtil.parseObj(property);
            //属性名称
            String name = propertyMap.get("name").toString();
            //属性key
            String key = propertyMap.get("key").toString();
            //属性值
            Object value1 = JSONUtil.parseObj(p).get("value");
            String value="" ;
            if(value1!=null){
                value = value1.toString();
            }

            //TODO 属性值历史数据，是否需要
            Object list = JSONUtil.parseObj(p).get("list");
            //建立属性-值映射关系
            propertiesMap.put(key,value);
        });
        propertiesMap.put("status",status.toString());
        propertiesMap.put("deviceId",deviceId);
        propertiesMap.put("realTime",time);
        return propertiesMap;
    }

}
