package com.chinaitop.depot.intelligent.utils;

import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.unissoft.model.ResponseEntity;

/**
 * @author qingsong.han
 * @description: 云端远程检测控制工具类
 * @create 2020-06-01 11:05
 */
@Component
public class RemoteControlUtil {
    /**
     * rest接口注入
     */
    @Resource
    private RestTemplate restTemplate;
    /**
     * url常量
     */
    // 空调控制指令 POST(String vcfcode, String vdevcode, String type, String ktinfoJson, String uperson)
    public static final String airConditionDir = "/intelligents/insideCirculation/sendAirConditionDir";
    //空调控制指令
    public static final String coldStorageOnly = "/intelligents/coldStorage/sendAirConditionDir";
    //氮气房控制指令
    public static final String nitrogenAll = "/intelligents/nitrogen/sendAirConditionDir";
    //氮气气调控制指令
    public static final String gasConditionDir = "/intelligents/gas/sendAirConditionDir";
    // 虫害实时检测 POST(String storeCode)
    public static final String nowInsectPest = "/intelligents/insectPestDetection/sendNowInsectPest";
    // 气体实时检测 POST(String storeCode)
    public static final String nowGasDetection = "/intelligents/gasDetection/sendNowGasDetection";
    // 数量检测,获取测量进度 GET(String vcfcode, String ws)
    public static final String scanProgress = "/intelligents/monitorWarning/getScanResult";
    // 数量检测,获取扫描结果 GET(String vcfcode, String devcode, String operator, String orgId, String ws)
    public static final String measureWeight = "/intelligents/monitorWarning/getmeasureweight";
    // 数量检测,监测指令接口 GET(String vcfcode, String ws)
    public static final String sendOrder = "/intelligents/monitorWarning/sendNumberMonitor";
    // 粮温检测-手动选仓 POST(String storeCode)
    public static final String chooseCFCode = "/intelligents/temperatureRecord/sendTemperatureDetection";
    // 气象实时检测 POST()
    public static final String wertherinfo = "/intelligents/wertherinfo/sendNowWeatherDetection";
    // 粮情全仓检测 GET(String tType)
    public static final String foodAll = "/intelligents/temperatureRecord/sendTemperatureDetectionAll";
    // 粮情单仓检测 POST(String storeCode, String tType)
    public static final String foodOnly = "/intelligents/temperatureRecord/sendOnlyStoreDetection";
    // 气体全仓检测 GET(String orgId)
    public static final String gasAll = "/intelligents/gasDetection/sendGasDetectionAll";
    // 气体单仓检测 POST(String vCfCode, String orgId)
    public static final String gasOnly = "/intelligents/gasDetection/sendOnlyGasDetection";
    // 所有虫害检测 GET()
    public static final String pestAll = "/intelligents/insectPestDetection/sendInsectPestDetectionAll";
    // 单仓虫害检测 POST(String vCfCode)
    public static final String onlyPest = "/intelligents/insectPestDetection/sendOnlyInsectPestDetection";
    // 能耗检测 POST()
    public static final String energyOrder = "/intelligents/energyDetection/addHistoryData";
    // 通风控制 POST(String task, String aerationTaskControl, Integer orgId, String saveType)
    public static final String xzSave = "/intelligents/aerationRecord/save";

    // 同步接口
    // 与智远同步气象站信息基础数据, method = RequestMethod.GET
    public static final String wertherinfoSYN = "/intelligents/wertherinfo/synchronizationAll";
    // 与智远同步气体液位基础数据
    public static final String qtdevinfoSYN = "/intelligents/qtdevinfo/synchronizationAll";
    // 同步多通道气体基础数据
    public static final String gaseousSYN = "/intelligents/gaseous/synchronizationAll";
    // 与智远同步站点类型基础数据
    public static final String stationTypeSYN = "/intelligents/stationType/synchronizationAll";
    // 数量检测同步
    public static final String quantitySYN = "/intelligents/quantity/synchronizationAll";
    // 与智远同步虫害基础数据
    public static final String insectSYN = "/intelligents/insect/synchronizationAll";
    // 与智远同步通信设置基础数据
    public static final String stationSYN = "/intelligents/station/synchronizationAll";
    // 与智远同步粮油信息基础数据
    public static final String grainSYN = "/intelligents/grain/synchronizationAll";
    // 与智远同步空调设置基础数据
    public static final String ktinfoSYN = "/intelligents/ktinfo/synchronizationAll";
    // 与智远同步通风设备信息基础数据
    public static final String aerationParameterSYN = "/intelligents/aerationParameter/synchronizationAll";
    // 与智远同步能耗设备信息基础数据
    public static final String energyDetectionSYN = "/intelligents/energyDetection/synchronizationAll";
    // 与智远同步氮气房设置基础数据
    public static final String nitrogenSYN = "/intelligents/nitrogen/synchronizationAll";
    // 与智远同步气调设置基础数据
    public static final String gasSYN  = "/intelligents/gas/synchronizationAll";

    // orgInfo CRUD到硬件方 POST(String orgInfoJson, String CUD)
    public static final String saveGrainPoint = "/intelligents/wareHouseBasicInfo/saveGrainpoint";
    // storeHouse CRUD到硬件方 POST(String basicStorehouseJson,String del)
    public static final String syncStoreHouse = "/intelligents/wareHouseBasicInfo/synchronizationStoreHouse";
    //多通道气体设备:保存与更新 POST(String grainJson)
    public static final String gaseousSave = "/intelligents/gaseous/save";
    //多通道气体设备:删除 POST(String id, String dcsQtInfoInfoJson)
    public static final String gaseousRemove = "/intelligents/gaseous/deleteById";
    //粮情信息:数据更新与添加 POST(String grainJson)
    public static final String grainSave = "/intelligents/grain/save";
    //粮情信息:根据粮情id删除粮油信息 POST(String id,String basicGrainSetJson)
    public static final String grainRemove = "/intelligents/grain/deleteById";
    //气调设备:数据更新与添加 POST(String grainJson)
    public static final String gasSave = "/intelligents/gas/save";
    //气调设备:根据气调id删除 POST(String id,String basicGasSetJson)
    public static final String gasRemove = "/intelligents/gas/deleteById";
    //虫害设备:数据更新与添加 POST(String grainJson)
    public static final String insectSave = "/intelligents/insect/save";
    //虫害设备:根据气调id删除 POST(String id, String insectJson)
    public static final String insectRemove = "/intelligents/insect/deleteById";
    //氮气房设备:数据更新与添加 POST(String grainJson)
    public static final String nitrogenSave = "/intelligents/nitrogen/save";
    //氮气房设备:根据气调id删除 POST(String id, String basicRoomSetJson)
    public static final String nitrogenRemove = "/intelligents/nitrogen/deleteById";
    //气体液位设备:数据更新与添加 POST(String grainJson)
    public static final String qtdevinfoSave = "/intelligents/qtdevinfo/save";
    //气体液位设备:根据气调id删除 POST(String id, String basicRoomSetJson)
    public static final String qtdevinfoRemove = "/intelligents/qtdevinfo/deleteById";
    //数量检测设备:数据更新与添加 POST(String grainJson)
    public static final String quantityfoSave = "/intelligents/quantity/save";
    //数量检测设备:根据气调id删除 POST(String id, String basicRoomSetJson)
    public static final String quantityRemove = "/intelligents/quantity/deleteById";
    //空调设备:数据更新与添加 POST(String grainJson)
    public static final String ktinfoSave = "/intelligents/ktinfo/save";
    //空调设备:根据气调id删除 POST(String id, String ktinfoJson)
    public static final String ktinfoRemove = "/intelligents/ktinfo/deleteById";
    //通信设备:数据更新与添加 POST(String grainJson)
    public static final String stationSave = "/intelligents/station/save";
    //通信设备:根据气调id删除 POST(String id, String stationJson)
    public static final String stationRemove = "/intelligents/station/deleteById";
    //能耗检测:保存数据 POST(String tEnergyInfoJson)
    public static final String energyDetectionSave = "/intelligents/energyDetection/saveAmmeter";
    //能耗检测:根据id删除 POST(String id, String ammeterJson)
    public static final String energyDetectionRemove = "/intelligents/energyDetection/deleteById";
    //通风参数值设置:数据更新与添加 POST(String aerationParameterJson, Integer orgId)
    public static final String aerationParameterSave = "/intelligents/aerationParameter/save";
    //通风参数值设置:根据气调id删除 POST(String id, String aerationParamJson)
    public static final String aerationParameterRemove = "/intelligents/aerationParameter/deleteById";
    //气象站设备:数据更新与添加 POST(String aerationParameterJson, Integer orgId)
    public static final String wertherinfoSave = "/intelligents/wertherinfo/save";
    //气象站设备:根据气调id删除 POST(String id, String aerationParamJson)
    public static final String wertherinfoRemove = "/intelligents/wertherinfo/deleteById";

    /**
     * 远程库端请求方法
     *
     * @param url           库端地址
     * @param requestEntity post请求参数 无参数传入 new LinkedMultiValueMap<>()
     * @param httpType      http 类型
     * @param requestMap    get请求参数 无参数传入 new HashMap<>()
     * @return string
     */
    public ResponseEntity remoteScan(@Valid @NotNull String url, MultiValueMap requestEntity,@Valid  @NotNull String httpType, Map requestMap) {
        httpType = httpType.toUpperCase();
        ResponseEntity responseEntity = null;
        try {
            if ("GET".equals(httpType)) {
                responseEntity = restTemplate.getForObject(getForObject(url, requestMap), ResponseEntity.class);
            } else {
                responseEntity = restTemplate.postForObject(url, requestEntity, ResponseEntity.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }

    /**
     * POST 方法重载
     * @param url http
     * @param requestEntity 参数对象
     * @return ResponseEntity
     */
    public ResponseEntity remoteScan(@Valid @NotNull String url, MultiValueMap requestEntity) {
        return restTemplate.postForObject(url, requestEntity, ResponseEntity.class);
    }

    /**
     * GET 方法重载
     * @param url http
     * @param requestMap 参数对象
     * @return ResponseEntity
     */
    public ResponseEntity remoteScan(@Valid @NotNull String url, Map requestMap) {
        return restTemplate.getForObject(getForObject(url, requestMap), ResponseEntity.class);
    }

    /**
     * 封装的get请求，暂时只支持map传参，并且value只支持基本类型和String
     *
     * @param url    库端配置url
     * @param object 接收数据(只支持map类型)
     * @return string类型带参数get请求url
     */
    private static String getForObject(String url, Object object) {
        StringBuilder stringBuilder = new StringBuilder(url);
        if (object instanceof Map) {
            Iterator iterator = ((Map) object).entrySet().iterator();
            if (iterator.hasNext()) {
                stringBuilder.append("?");
                Object element;
                while (iterator.hasNext()) {
                    element = iterator.next();
                    Map.Entry entry = (Map.Entry) element;
                    //过滤value为null，value为null时进行拼接字符串会变成 "null"字符串
                    if (entry.getValue() != null) {
                        stringBuilder.append(element).append("&");
                    }
                    url = stringBuilder.substring(0, stringBuilder.length() - 1);
                }
            }
        } else {
            throw new RuntimeException("url请求:" + url + "请求参数有误不是map类型");
        }
        return url;
    }

}
