package com.sptg.iot.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.iot.api.beans.ApiResultBean;
import com.sptg.iot.api.entity.IotAuthentication;
import com.sptg.iot.api.entity.IotSysConf;
import com.sptg.iot.api.feigns.IotAuthFeign;
import com.sptg.iot.api.util.IotHttpUtil;
import com.sptg.iot.biz.service.IotApiLogServiceInterface;
import com.sptg.iot.biz.service.IotAuthServiceInterface;
import com.sptg.iot.biz.service.IotSysConfServiceInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zwx
 * @create 2020/10/27 16:27
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class IotAuthController implements IotAuthFeign {

    private final IotSysConfServiceInterface iotSysConfServiceInterface;
    private final RedisTemplate redisTemplate;
    private final IotAuthServiceInterface iotAuthServiceInterface;
    private final IotApiLogServiceInterface iotApiLogServiceInterface;
    public static final String IOT_AUTH_ACCESS_TOKEN = "sptg:iot:auth:accessToken";


    @Override
    @PostMapping(value = "/iot/auth/{appId}")
    public ResultBean<IotAuthentication> auth(@PathVariable(value = "appId") String appId) {
        IotSysConf sysConf = this.iotSysConfServiceInterface.findSysConfByAppId(appId);
        IotHttpUtil httpUtil = new IotHttpUtil(null);
        Map<String, Object> bizParamsMap = new HashMap<>();
        bizParamsMap.put("appId", appId);
        bizParamsMap.put("appSecret", sysConf.getAppSecret());
        ApiResultBean apiResultBean = httpUtil.auth(bizParamsMap);
        Map status = apiResultBean.getStatus();
        Integer code = (Integer) status.get("code");
        if(code.equals(200)){
            IotAuthentication source = apiResultBean.getContent();
            IotAuthentication target = this.iotAuthServiceInterface.findByAppId(appId);
            Date date = new Date(Long.parseLong(source.getExpireTime()) * 1000L);
            if(target == null){
                target = new IotAuthentication();
                source.setAppId(appId);
                source.setExpireDate(date);
            }else{
                source.setId(target.getId());
                source.setExpireDate(date);
                source.setAppId(target.getAppId());
            }
            BeanUtil.copyProperties(source, target);
            boolean result = this.iotAuthServiceInterface.insertOrUpdate(target);
            if(result){
                //保存到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 new ResultBean<>(ResultEnum.SUCCESS, source);
            }
            return new ResultBean<>(ResultEnum.FAILURE, null);
        }else{
            String reqData = JsonUtils.objectToJson(bizParamsMap);
            this.iotApiLogServiceInterface.recordIotApiLog("iot/login", null, appId, reqData, apiResultBean);
            return new ResultBean<>(ResultEnum.FAILURE, null);
        }
    }
}
