package com.union.ai.api.controller;

import com.alibaba.fastjson.JSON;
import com.union.ai.api.consts.RedisKeys;
import com.union.ai.api.dao.model.App;
import com.union.ai.api.dto.AuthDto;
import com.union.ai.api.dto.AuthParamDto;
import com.union.ai.api.enums.ErrorEnum;
import com.union.ai.api.result.AppResponse;
import com.union.ai.api.result.TokenResult;
import com.union.ai.api.service.AppService;
import com.union.ai.api.util.AuthUtil;
import com.union.ai.api.util.CheckUtil;
import com.union.ai.api.util.Config;
import com.union.ai.api.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2019/3/24
 * Time: 下午4:44
 */
@Slf4j
@RestController
@RequestMapping("/oauth/2.0")
public class AuthController {

    @Autowired
    private AppService appService;

    /**
     * 获得token
     *
     * @param authParamDto
     * @return
     */
    @ResponseBody
    @RequestMapping("/token")
    public TokenResult auth(@RequestBody @Valid AuthParamDto authParamDto) {

        try {
            App app = appService.getEnableAppInfo(authParamDto.getClient_id(), authParamDto.getClient_secret());
            if (CheckUtil.isNull(app)) {
                return new TokenResult("invalid_client", "unknown client id");
            }
            //生成token
            String token = AuthUtil.getToken(app.getAppId(), app.getApiKey(), app.getSecretKey());
            Integer redisExpire = Config.getInstance().getTokenExpireTime() * 24 * 3600;
            //token 放入redis，并设置失效时间
            RedisUtil.setex(token, redisExpire, app.getAppId().toString());

            long expireTime = System.currentTimeMillis() / 1000 + redisExpire;
            return new TokenResult(token, expireTime);
        } catch (Exception e) {
            log.error("生成token错误,param" + JSON.toJSONString(authParamDto), e);
            return new TokenResult("invalid_client", "system_error");
        }

    }
}
