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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import oracle.jdbc.proxy.annotation.Post;
import org.springblade.core.tool.api.R;
import org.springblade.third.butt.iotdevice.entity.IotAuthentication;
import org.springblade.third.butt.iotdevice.entity.PepApiResultBean;
import org.springblade.third.butt.iotdevice.util.PepIotHttpUtil;
import org.springblade.third.iotsysconf.entity.IotSysConf;
import org.springblade.third.iotsysconf.service.IIotSysConfService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * Created By lidexi in 2021/7/14
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/third/pep")
public class PepAuthController {

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

	@PostMapping("/auth")
	public R auth(@RequestParam 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 {//获取感知平台鉴权失败短信通知手动获取，防止数据订阅无法上传


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