package com.fastbee.iot.strategy.impl;

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.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.strategy.DeviceRealTimeDataGetStrategy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 仁科设备数据对接
 */
@Component
public class RenKeDeviceRealTimeGetStrategy implements DeviceRealTimeDataGetStrategy {

    private final static String BASE_URL="http://farm.0531yun.cn";
    private final static String LOGIN_URL="http://api.farm.0531yun.cn/api/v2.0/entrance/user/userLogin";
    private final static String DEVICE_BASE_DATA_URL="http://api.farm.0531yun.cn/api/v2.0/entrance/device/getRealTimeData";
    private final static String DEVICE_CORE_DATA_URL="http://api.farm.0531yun.cn/api/v2.0/worm/deviceData/getWormDataAndWormDataAIBy";



    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @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());
        }
        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());
        });
        //获取token
        String token = getToken(params.get("account"), params.get("password"));
        //获取设备基础实时数据
        HttpResponse response = HttpRequest.get(DEVICE_BASE_DATA_URL)
                .header("token", token)
                .form("deviceAddrs", deviceId)
                .execute();
        String respBodyStr = response.body();
        JSONObject respBody = JSONUtil.parseObj(respBodyStr);
//        System.err.println(respBodyStr);
        if(!respBody.get("code").toString().equals("1000")){
            throw new ServiceException("获取设备实时数据失败!");
        }
        JSONArray realtimeDataList = JSONUtil.parseArray(respBody.get("data"));
        JSONObject jsonObject = JSONUtil.parseObj(realtimeDataList.get(0));
        JSONObject dataMap = JSONUtil.parseObj(jsonObject.get("data"));
        dataMap.put("deviceId",deviceId);

        //获取虫情设备关键数据
        HttpResponse response1 = HttpRequest.get(DEVICE_CORE_DATA_URL+"?deviceAddr="+deviceId)
                .header("token", token)
                .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");
            dataMap.put("pestPhotos",analyseCoordUrl.toString());
            dataMap.put("camera",imagesUrl.toString());
        }
        return dataMap;
    }

    /**
     * 获取token
     * @return
     */
    private String getToken(String account,String password){
        //判断token是否过期
        String cacheToken = stringRedisTemplate.opsForValue().get("renke:user:token");
        if (!Objects.isNull(cacheToken)){
            return cacheToken;
        }
        //获取鉴权token
        //构建请求体
        Map<String,Object> reqBody =new HashMap<>();
        reqBody.put("loginName",account);
        reqBody.put("loginPwd",password);

        HttpResponse response = HttpRequest.post(LOGIN_URL)
                .body(JSONUtil.toJsonStr(reqBody)).execute();
        String resultObjectStr = response.body();

        JSONObject resultObject = JSONUtil.parseObj(resultObjectStr);
        if(!resultObject.get("code").toString().equals("1000")){
            throw new RuntimeException("仁科获取token失败!");
        }
        JSONObject tokenObject = JSONUtil.parseObj(resultObject.get("data"));
        int currDate = Integer.parseInt(tokenObject.get("currDate").toString());
        int expDate = Integer.parseInt(tokenObject.get("expDate").toString());
        Integer periodValidity= expDate - currDate;
        //将token存入redis
//        return tokenObject.get("token").toString();
        stringRedisTemplate.opsForValue().set("renke:user:token", tokenObject.get("token").toString(),2, TimeUnit.HOURS);
//        System.err.println("请求获取到token:"+tokenObject.get("token").toString());
        return stringRedisTemplate.opsForValue().get("renke:user:token");
    }
}
