package org.springblade.third.butt.iotdevice.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.common.constant.CommonConstant;
import org.springblade.community.houseuserthird.entity.ThirdHouseUser;
import org.springblade.core.tool.api.R;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.third.butt.iotdevice.constant.PepConstant;
import org.springblade.third.butt.iotdevice.dto.PepPageData;
import org.springblade.third.butt.iotdevice.entity.IotAuthentication;
import org.springblade.third.butt.iotdevice.entity.IotThirdPlatform;
import org.springblade.third.butt.iotdevice.entity.PepApiResultBean;
import org.springblade.third.butt.iotdevice.entity.PepIotReturnCode;
import org.springblade.third.butt.iotdevice.service.IperceptionIotDeviceService;
import org.springblade.third.butt.iotdevice.util.PepIotHttpUtil;
import org.springblade.third.iotaepproduct.entity.ThirdIotAepProduct;
import org.springblade.third.iotaepproduct.service.IThirdIotAepProductService;
import org.springblade.third.iotsysconf.entity.IotSysConf;
import org.springblade.third.iotsysconf.service.IIotSysConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created By lidexi in 2021/7/14
 **/
@Service
public class PerceptionIotDeviceImpl implements IperceptionIotDeviceService {

	@Autowired
	private IIotSysConfService iotSysConfService;
	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	@Autowired
	private IThirdIotAepProductService thirdIotAepProductService;

	public static final String IOT_AUTH_ACCESS_TOKEN = "sptg:iot:auth:accessToken@#";

	@Override
	public R<IotAuthentication> auth(String appId) {
		IotSysConf sysConf = this.iotSysConfService.getOne(new QueryWrapper<>(new IotSysConf()).lambda()
				.eq(IotSysConf::getAppId,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
	public R registerDevice(SmartDevice 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.getOne(new QueryWrapper<>(new IotSysConf()).lambda()
			.eq(IotSysConf::getAppId,PepConstant.NXDX_APPID));
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);
		//获取accessToken
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		if(accessToken == null){
			R<IotAuthentication> auth = this.auth("617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
			if(auth.isSuccess()){
				accessToken = auth.getData().getAccessToken();
			}
		}
		PepApiResultBean register = httpUtil.register(bizParamsMap, iotDevice.getPrefix(), accessToken);
		System.out.println(register);
		return R.data(register);
	}

	@Override
	public R deleteDevice(SmartDevice 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.getOne(new QueryWrapper<>(new IotSysConf()).lambda()
			.eq(IotSysConf::getAppId,PepConstant.NXDX_APPID));
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);

		//获取accessToken
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		if(accessToken == null){
			R<IotAuthentication> auth = this.auth("617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
			if(auth.isSuccess()){
				accessToken = auth.getData().getAccessToken();
			}
		}
		PepApiResultBean delDevice = httpUtil.delDevice(bizParamsMap, iotDevice.getPrefix(), accessToken);
		System.out.println("删除设备"+delDevice.toString());
		return R.data(delDevice);
	}

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

	@Override
	public R<List<SmartDevice>> queryDeviceList(String appId, Integer page) {
		IotSysConf sysConf = this.iotSysConfService.getOne(new QueryWrapper<>(new IotSysConf()).lambda()
			.eq(IotSysConf::getAppId,PepConstant.NXDX_APPID));
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);
		Map<String, Object> bizParamsMap = new HashMap<>();
		bizParamsMap.put("page",page);
		bizParamsMap.put("page_size",10);
		//获取accessToken
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		if(accessToken == null){
			R<IotAuthentication> auth = this.auth("617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
			if(auth.isSuccess()){
				accessToken = auth.getData().getAccessToken();
			}
		}
		List<SmartDevice> items = httpUtil.syncIotDeviceList(bizParamsMap,"ctwing/smoke3",accessToken);

		return R.data(items);
	}

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

	@Override
	public R queryAepList(String appId) {
		IotSysConf sysConf = this.iotSysConfService.getOne(new QueryWrapper<>(new IotSysConf()).lambda()
			.eq(IotSysConf::getAppId,PepConstant.NXDX_APPID));
		PepIotHttpUtil httpUtil = new PepIotHttpUtil(sysConf);
		Map<String, Object> bizParamsMap = new HashMap<>();
		String prefix = "ctwing/smoke3";
		//获取accessToken
		String accessToken = redisTemplate.opsForValue().get(IOT_AUTH_ACCESS_TOKEN + PepConstant.NXDX_APPID);
		if(accessToken == null){
			R<IotAuthentication> auth = this.auth("617fb531-c8bb-47c0-b3c4-d2fa4162a18e");
			if(auth.isSuccess()){
				accessToken = auth.getData().getAccessToken();
			}
		}
		PepApiResultBean<PepPageData<ThirdIotAepProduct>> apiResultBean = httpUtil.syncAepProductList(bizParamsMap, prefix, accessToken);
		if (apiResultBean.getCode().equals(PepIotReturnCode.UNAUTHORIZED.getCode())) { //未认证，提示先去认证
			return R.fail(PepIotReturnCode.UNAUTHORIZED.getDescribe());
		}
		if (apiResultBean.getCode().equals(0) ){
			PepPageData<ThirdIotAepProduct> pageData = JSONObject.parseObject(JSONObject.toJSONString(apiResultBean.getData()),PepPageData.class);
			List<ThirdIotAepProduct> items = JSONObject.parseArray(JSONObject.toJSONString(pageData.getList()),ThirdIotAepProduct.class);
			items.stream().forEach(iotAepProduct -> {
				iotAepProduct.setPlatform(IotThirdPlatform.PERCEPTION.getValue());
				ThirdIotAepProduct oldEntity = this.thirdIotAepProductService.getOne(new QueryWrapper<>(new ThirdIotAepProduct())
					 .lambda().eq(ThirdIotAepProduct::getProductId,iotAepProduct.getProductId()));
				if(oldEntity != null){
					oldEntity.setProductName(iotAepProduct.getProductName());
					this.thirdIotAepProductService.updateById(oldEntity);
				}else {
					this.thirdIotAepProductService.save(iotAepProduct);
				}
			});
		}


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