package com.xinelu.applet.controller.mobileAuthorization;


import com.xinelu.applet.vo.mobileAuthorization.MobileAuthorizationVO;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.utils.uuid.IdUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description 移动端权限认证控制器
 * @Author 纪寒
 * @Date 2022-12-09 09:47:06
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/nurseApplet/authorization")
public class MobileAuthorizationController {

    /**
     * 令牌秘钥标识
     */
    @Value("${token.secret}")
    private String secret;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 移动端令牌生成接口
     *
     * @return 令牌信息
     */
    @GetMapping("/createMobileToken")
    public AjaxResult createMobileAuthorization() {
        //随机字符串
        String uuid = IdUtils.fastUUID();
        //JWT链
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.MOBILE_AUTHORIZATION_PREFIX, uuid);
        //使用JWT生成token信息
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        //将token存入Redis中默认有效期为1个月
        String tokenKey = Constants.MOBILE_AUTHORIZATION_KEY + uuid;
        //将token的有效期设置为10天
        redisTemplate.opsForValue().set(tokenKey, token, 240, TimeUnit.HOURS);
        MobileAuthorizationVO authorizationVO = new MobileAuthorizationVO();
        authorizationVO.setToken(token);
        return AjaxResult.success(authorizationVO);
    }
}
