package org.springblade.third.iotdevice.feign;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.OperationConstant;
import org.springblade.common.constant.PepConstant;
import org.springblade.common.utils.JsonUtils;
import org.springblade.core.tool.api.R;
import org.springblade.device.entity.IotDevice;
import org.springblade.sms.service.IPepNoticeService;
import org.springblade.third.iotdevice.constants.PepIotReturnCode;
import org.springblade.third.iotdevice.entity.*;
import org.springblade.third.iotdevice.service.IIotAepProductService;
import org.springblade.third.iotdevice.service.IIotSysConfService;
import org.springblade.third.iotdevice.util.PepIotHttpUtil;
import org.springblade.third.sms.dto.IotSmsTemplateParam;
import org.springblade.third.sms.dto.PepSmsSendDto;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author lidexi
 * @date 2021/6/3 9:29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/feign/third/perception")
public class PerceptionIotDeviceClient implements IPerceptionIotDeviceClient {

	private final IIotSysConfService iotSysConfService;
	private final RedisTemplate<String, String> redisTemplate;
	private final IIotAepProductService iotAepProductService;
	private final IPepNoticeService pepNoticeService;
	public static final String IOT_AUTH_ACCESS_TOKEN = "sptg:iot:auth:accessToken@#";

	@Override
	@PostMapping("/auth/{appId}")
	public R auth(@PathVariable("appId") String appId) {
		IotSysConf sysConf = this.iotSysConfService.getByAppId(appId);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(null);
		Map<String, Object> bizParamsMap = new HashMap<>();
		bizParamsMap.put("appId", appId);
		bizParamsMap.put("appSecret", sysConf.getAppSecret());
		PepApiResultBean apiResultBean = httpUtil.auth(bizParamsMap);
		Map status = apiResultBean.getStatus();
		Integer code = (Integer) status.get("code");
		if (code.equals(200)) {
			IotAuthentication source = apiResultBean.getContent();

			//保存到redis
			ValueOperations valueOperations = this.redisTemplate.opsForValue();
			long l = DateUtil.timeToSecond(source.getExpireTime()) - (DateUtil.currentSeconds() + 600);
			valueOperations.set(IOT_AUTH_ACCESS_TOKEN + appId, source.getAccessToken(), l, TimeUnit.SECONDS);
			return R.data(source);
		} else {//获取感知平台鉴权失败短信通知手动获取，防止数据订阅无法上传
			PepSmsSendDto pepSmsSendDto = new PepSmsSendDto();
			pepSmsSendDto.setMobile("15089107336");
			pepSmsSendDto.setPrefix("ctwing/smoke3");
			pepSmsSendDto.setTemplate_id("91556324");
			pepSmsSendDto.setTimestamp(LocalDateTime.now().toString());

			IotSmsTemplateParam iotSmsTemplateParam = new IotSmsTemplateParam();
			iotSmsTemplateParam.setParam1("感知平台");
			iotSmsTemplateParam.setParam2("感知平台");
			iotSmsTemplateParam.setParam3("感知平台");
			iotSmsTemplateParam.setParam4("感知平台");
			iotSmsTemplateParam.setParam5("感知平台获取鉴权失败且token失效");
			pepSmsSendDto.setTemplate_param(iotSmsTemplateParam);

			pepNoticeService.sendSms(pepSmsSendDto);

			return R.fail("获取感知平台鉴权失败短信通知手动获取，防止数据订阅无法上传");
		}
	}

	@Override
	@PostMapping("/addDevice")
	public R createDevice(@RequestBody IotDevice iotDevice) {
		Map<String, Object> bizParamsMap = new HashMap<>();
		bizParamsMap.put("device_id", iotDevice.getImei());
		bizParamsMap.put("imei", iotDevice.getImei());
		bizParamsMap.put("device_name", iotDevice.getDeviceName());
//		bizParamsMap.put("is_aep", iotDevice.getIsAep());
//		bizParamsMap.put("operator", iotDevice.getPerson());
		bizParamsMap.put("product_id", iotDevice.getProductId());
		bizParamsMap.put("auto_observer", 0);
		bizParamsMap.put("imsi", iotDevice.getImsi());
//		bizParamsMap.put("psk_value", iotDevice.getPsk_value());
		bizParamsMap.put("device_type", iotDevice.getDeviceType());
//		bizParamsMap.put("manufacturers_no", iotDevice.getManufacturersNo());
//		bizParamsMap.put("device_specld", iotDevice.getDeviceSpecld());
//		bizParamsMap.put("protocol_type", iotDevice.getProtocolType());
//		bizParamsMap.put("tag", iotDevice.getTag());
//		bizParamsMap.put("latitude_longitude", iotDevice.getLatitudeLongitude());
//		bizParamsMap.put("area", iotDevice.getArea());
//		bizParamsMap.put("organization", iotDevice.getOrganization());
//		bizParamsMap.put("person", iotDevice.getPerson());
//		bizParamsMap.put("ammeterId", iotDevice.getPerson());
		bizParamsMap.put("device_install_address", iotDevice.getDeviceInstallAddress());
//		bizParamsMap.put("dist_locate", iotDevice.getDistLocate());
//		bizParamsMap.put("master_key",iotDevice.getMasterKey());
		IotSysConf sysConf = this.iotSysConfService.getByAppId(PepConstant.NXDX_APPID);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		PepApiResultBean register = httpUtil.register(bizParamsMap, null, accessToken);
		System.out.println(register);
		return R.data(register);
	}

	@Override
	@PostMapping("/deleteDevice")
	public R deleteDevice(@RequestBody IotDevice iotDevice) {
		Map<String, Object> bizParamsMap = new HashMap<>();
		bizParamsMap.put("device_id", iotDevice.getDeviceId());
//		bizParamsMap.put("is_aep", iotDevice.getIsAep());
		bizParamsMap.put("product_id", iotDevice.getProductId());
//		bizParamsMap.put("master_key",iotDevice.getMasterKey());

		IotSysConf sysConf = this.iotSysConfService.getByAppId(PepConstant.NXDX_APPID);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);

		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		PepApiResultBean delDevice = httpUtil.delDevice(bizParamsMap, null, accessToken);
		System.out.println("删除设备"+delDevice.toString());
		return R.data(delDevice);
	}


	@Override
	public R queryDevice() {
		return null;
	}

	@Override
	@PostMapping("/queryDeviceList/{appId}")
	public R<List<IotDevice>> queryDeviceList(@PathVariable("appId") String appId,@RequestParam Integer page) {
		IotSysConf iotSysConf = this.iotSysConfService.getByAppId(appId);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(iotSysConf);
		Map<String, Object> bizParamsMap = new HashMap<>();
		bizParamsMap.put("page",page);
		bizParamsMap.put("page_size",10);

		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + appId);
		List<IotDevice> items = httpUtil.syncIotDeviceList(bizParamsMap,"ctwing/smoke3",accessToken);

		return R.data(items);
	}


	@Override
	public R updateDevice() {
		return null;
	}

	@Override
	@PostMapping("/queryAepList/{appId}")
	public R queryAepList(@PathVariable("appId") String appId) {
		IotSysConf iotSysConf = this.iotSysConfService.getByAppId(appId);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(iotSysConf);
		Map<String, Object> bizParamsMap = new HashMap<>();
		String prefix = "ctwing/smoke3";
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + appId);
		PepApiResultBean<PepPageData<IotAepProduct>> apiResultBean = httpUtil.syncAepProductList(bizParamsMap, prefix, accessToken);
		if (apiResultBean.getCode().equals(PepIotReturnCode.UNAUTHORIZED.getCode())) { //未认证，提示先去认证
			return R.fail(PepIotReturnCode.UNAUTHORIZED.getDescribe());
		}
		if (apiResultBean.getCode().equals(OperationConstant.ZERO)) {
			PepPageData<IotAepProduct> pageData = JSONObject.parseObject(JSONObject.toJSONString(apiResultBean.getData()),PepPageData.class);
			List<IotAepProduct> items = JSONObject.parseArray(JSONObject.toJSONString(pageData.getList()),IotAepProduct.class);
			items.stream().forEach(iotAepProduct -> {
				iotAepProduct.setPlatform(CommonConstant.THIRDPLATFORM.PERCEPTION.getValue());
				IotAepProduct oldEntity = this.iotAepProductService.getOne(new QueryWrapper<>(new IotAepProduct()).lambda().eq(IotAepProduct::getProductId,iotAepProduct.getProductId()));
				if(oldEntity != null){
					oldEntity.setProductName(iotAepProduct.getProductName());
					this.iotAepProductService.updateById(oldEntity);
				}else {
					this.iotAepProductService.save(iotAepProduct);
				}
			});
		}


		return R.data("同步aep列表成功");
	}

	@PostMapping("/iotSubscribe")
	public R iotSubscribe(@RequestBody IotSubscribe iotSubscribe){
		String appId = iotSubscribe.getAppId();
		IotSysConf iotSysConf = this.iotSysConfService.getByAppId(appId);
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(iotSysConf);
		Map<String, Object> bizParamsMap = new HashMap<>();
		String[] prefixList = iotSysConf.getPrefix().split(",");
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + appId);
		int flag = 0;
		for(int i = 0; i < prefixList.length; i++) {
			String prefix = prefixList[i];
			PepApiResultBean pepApiResultBean = httpUtil.inquireSubscribe(bizParamsMap, prefix, accessToken);
			String reqData = JsonUtils.objectToJson(bizParamsMap);
			return R.data(pepApiResultBean);
		}
		return null;


	}


}
