package org.springblade.third.butt.iotdevice.util;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.springblade.homecare.alarmlist.entity.Alarm;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.third.butt.iotdevice.constant.HttpConstant;
import org.springblade.third.butt.iotdevice.dto.PepPageData;
import org.springblade.third.butt.iotdevice.entity.PepApiResultBean;
import org.springblade.third.iotaepproduct.entity.ThirdIotAepProduct;
import org.springblade.third.iotsysconf.entity.IotSysConf;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * Created By lidexi in 2021/7/14
 **/
public class PepIotHttpUtil<T> {

	private IotSysConf iotSysConf;

	private final RestTemplate restTemplate = new RestTemplate();

	public PepIotHttpUtil(IotSysConf iotSysConf) {
		this.iotSysConf = iotSysConf;
	}

	/**
	 * 认证接口，返回accessToken，具有有效期
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean auth(Map<String, Object> bizParamsMap) {
		ResponseEntity<PepApiResultBean> responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", HttpConstant.APPLICATION_JSON_UTF8);
		HttpEntity<String> requestEntity = new HttpEntity<>(JsonUtils.objectToJson(bizParamsMap), headers);
		ParameterizedTypeReference<PepApiResultBean> reference = new ParameterizedTypeReference<PepApiResultBean>() {
		};
		String url = "https://scep.ctwing.cn/paas/authentication/api/v1/apps/access_token";
		URI uri = URI.create(url);
		responseEntity = this.restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
		return responseEntity.getBody();
	}

	/**
	 * AEP 产品信息列表
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean syncAepProductList(Map<String, Object> bizParamsMap, String prefix, String accessToken) {
		bizParamsMap.put("page", 1);
		bizParamsMap.put("page_size", Integer.MAX_VALUE);

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/device/getProductList";
		PepApiResultBean<PepPageData<ThirdIotAepProduct>> infoPepApiResultBean = this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);
		return infoPepApiResultBean;
	}

	/**
	 * 感知平台设备注册
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean register(Map<String, Object> bizParamsMap, String prefix, String accessToken) {
		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/device/create";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);
	}

	/**
	 * 同步设备列表
	 *
	 * @param bizParamsMap 请求参数
	 * @return
	 * @Param prefix 地址前缀
	 */
	public List<SmartDevice> syncIotDeviceList(Map<String, Object> bizParamsMap, String prefix, String accessToken) {
		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/device/list";
		PepApiResultBean<PepPageData<SmartDevice>> infoPepApiResultBean = this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);
		PepPageData<SmartDevice> data = JSONObject.parseObject(JSONUtil.toJsonStr(infoPepApiResultBean.getData()), PepPageData.class);
		List<SmartDevice> iotDevices = JSONObject.parseArray(JSONUtil.toJsonStr(data.getItems()), SmartDevice.class);

		return iotDevices;
	}

	/**
	 * 设备查询（同步设备详情）
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean<SmartDevice> syncIotDeviceDetail(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken) {

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/device/search";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);

	}

	/**
	 * 设备删除
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean delDevice(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken) {

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/device/del";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);

	}

	/**
	 * 同步告警列表
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean<PepPageData<Alarm>> syncIotAlarmList(Map<String, Object> bizParamsMap, String prefix, String accessToken) {
		bizParamsMap.put("page", 1);
		bizParamsMap.put("page_size", Integer.MAX_VALUE);
		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/alarm/list";
		PepApiResultBean<PepPageData<Alarm>> resultBean = this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);
		return resultBean;
	}

	/**
	 * 同步告警详情
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean<Alarm> syncIotAlarmDetail(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken) {

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/alarm/search";
		return (PepApiResultBean<Alarm>) this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken).getData();

	}

	/**
	 * 同步告警阈值列表
	 * @param bizParamsMap
	 * @param urlPrefix 地址前缀
	 * @return
	 */
//    public PepApiResultBean<PepPageData<IotAlarmThreshold>> syncAlarmThresholdList(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken){
//        int page = 0;
//        int page_size = 100;
//        boolean flag = true;
//        PepPageData<IotAlarmThreshold> pageData = new PepPageData<>();
//        List<IotAlarmThreshold> items = new ArrayList<>();
//        pageData.setItems(items);
//        PepApiResultBean<PepPageData<IotAlarmThreshold>> apiResultBean = new PepApiResultBean<>();
//        while(flag){
//            ResponseEntity<PepApiResultBean<PepPageData<IotAlarmThreshold>>> responseEntity = null;
//            HttpHeaders headers = new HttpHeaders();
//            headers.add("Content-Type", HttpConstant.APPLICATION_JSON);
//            headers.add("accessToken", accessToken);
//            page = page + 1;
//            bizParamsMap.put("page", page);
//            bizParamsMap.put("page_size", page_size);
//            HttpEntity<String> requestEntity = new HttpEntity<>(JsonUtils.objectToJson(bizParamsMap),headers);
//            ParameterizedTypeReference<PepApiResultBean<PepPageData<IotAlarmThreshold>>> reference = new ParameterizedTypeReference<PepApiResultBean<PepPageData<IotAlarmThreshold>>>() {};
//            String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/alarm/thresholdList";
//            URI uri = URI.create(url);
//            try{
//                responseEntity = this.restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
//                PepApiResultBean<PepPageData<IotAlarmThreshold>> infoPepApiResultBean = responseEntity.getBody();
//                PepPageData<IotAlarmThreshold> data = infoPepApiResultBean.getData();
//                pageData.setCount(data.getCount());
//                int size = data.getItems().size();
//                if(size < page_size){
//                    flag = false;
//                }
//                items.addAll(data.getItems());
//            }catch (HttpClientErrorException e){
//                PepApiResultBean<PepPageData<IotAlarmThreshold>> errorPepApiResultBean = new PepApiResultBean<>();
//                errorPepApiResultBean.setCode(e.getStatusCode().value());
//                errorPepApiResultBean.setMsg(e.getMessage());
//                return apiResultBean;
//            }
//        }
//        apiResultBean.setCode(OperationConstant.ZERO);
//        apiResultBean.setMsg("成功");
//        apiResultBean.setData(pageData);
//        return apiResultBean;
//    }

	/**
	 * 同步告警工单列表
	 * @param bizParamsMap
	 * @return
	 */
//    public PepApiResultBean<PepPageData<IotAlarmWorkOrder>> syncAlarmWorkOrderList(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken){
//        int page = 0;
//        int page_size = 100;
//        boolean flag = true;
//        PepPageData<IotAlarmWorkOrder> pageData = new PepPageData<>();
//        List<IotAlarmWorkOrder> items = new ArrayList<>();
//        pageData.setItems(items);
//        PepApiResultBean<PepPageData<IotAlarmWorkOrder>> apiResultBean = new PepApiResultBean<>();
//        while(flag){
//            ResponseEntity<PepApiResultBean<PepPageData<IotAlarmWorkOrder>>> responseEntity = null;
//            HttpHeaders headers = new HttpHeaders();
//            headers.add("Content-Type", HttpConstant.APPLICATION_JSON);
//            headers.add("accessToken", accessToken);
//            page = page + 1;
//            bizParamsMap.put("page", page);
//            bizParamsMap.put("page_size", page_size);
//            HttpEntity<String> requestEntity = new HttpEntity<>(JsonUtils.objectToJson(bizParamsMap),headers);
//            ParameterizedTypeReference<PepApiResultBean<PepPageData<IotAlarmWorkOrder>>> reference = new ParameterizedTypeReference<PepApiResultBean<PepPageData<IotAlarmWorkOrder>>>() {};
//            String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/order/list";
//            URI uri = URI.create(url);
//            try{
//                responseEntity = this.restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
//                PepApiResultBean<PepPageData<IotAlarmWorkOrder>> infoPepApiResultBean = responseEntity.getBody();
//                PepPageData<IotAlarmWorkOrder> data = infoPepApiResultBean.getData();
//                pageData.setCount(data.getCount());
//                int size = data.getItems().size();
//                if(size < page_size){
//                    flag = false;
//                }
//                items.addAll(data.getItems());
//            }catch (HttpClientErrorException e){
//                PepApiResultBean<PepPageData<IotAlarmWorkOrder>> errorPepApiResultBean = new PepApiResultBean<>();
//                errorPepApiResultBean.setCode(e.getStatusCode().value());
//                errorPepApiResultBean.setMsg(e.getMessage());
//                return apiResultBean;
//            }
//        }
//        apiResultBean.setCode(OperationConstant.ZERO);
//        apiResultBean.setMsg("成功");
//        apiResultBean.setData(pageData);
//        return apiResultBean;
//    }


	/**
	 * 同步告警工单列表
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean updateAlarmWorkOrder(Map<String, Object> bizParamsMap, String urlPrefix, String accessToken) {

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + urlPrefix + "/order/update";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);

	}

	/**
	 * 订阅接口
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean subscribe(Map<String, Object> bizParamsMap, String prefix, String accessToken) {

		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/setting/subscribe";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);

	}

	/**
	 * 订阅接口查询
	 *
	 * @param bizParamsMap
	 * @return
	 */
	public PepApiResultBean inquireSubscribe(Map<String, Object> bizParamsMap, String prefix, String accessToken) {
		String url = iotSysConf.getHost() + ":" + iotSysConf.getPort() + "/" + prefix + "/setting/inquire";
		return this.postQuery(JSONUtil.toJsonStr(bizParamsMap), url, accessToken);
	}



	public PepApiResultBean postQuery(String body, String url, String accessToken) {
		ResponseEntity<PepApiResultBean<T>> responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", HttpConstant.APPLICATION_JSON);
		headers.add("accessToken", accessToken);
		HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
		ParameterizedTypeReference<PepApiResultBean<T>> reference = new ParameterizedTypeReference<PepApiResultBean<T>>() {
		};
		URI uri = URI.create(url);
		responseEntity = this.restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
		return responseEntity.getBody();
	}
}
