package com.dayou.controller;

import cn.hutool.core.util.ObjectUtil;
import com.dayou.bo.LoginCacheUserBO;
import com.dayou.bo.SimpleParentModel;
import com.dayou.constants.JwtConstants;
import com.dayou.dto.OALoginDTO;
import com.dayou.dto.SimplePostModel;
import com.dayou.entity.User;
import com.dayou.service.IUserService;
import com.dayou.utils.JwtTokenUtil;
import com.google.common.cache.Cache;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController extends BaseController {

    @Autowired
    @Qualifier("loginCache")
    private Cache<Long, LoginCacheUserBO> loginCache;

    @Autowired
    private IUserService userService;

    /**
     * 根据token返回用户信息
     *
     * @param token token
     * @return Boolean
     */
    @PostMapping("/checkOaToken")
    public OALoginDTO checkOaToken(String token) {
        // 根据token返回用户信息
        if (StringUtils.isNotBlank(token)) {
            try {
                Claims claims = JwtTokenUtil.getClaimFromToken(token, JwtConstants.SECRET);
                String subject = claims.getSubject();
                Long userId = Long.valueOf(subject);
                LoginCacheUserBO loginCacheUserBO = loginCache.getIfPresent(userId);
                if (ObjectUtil.isNotNull(loginCacheUserBO)){
                    // 返回用户信息
                    User user = userService.getById(userId);
                    return new OALoginDTO()
                            .setUserOaId(loginCacheUserBO.getId())
                            .setName(loginCacheUserBO.getName())
                            .setDepartmentNameList(loginCacheUserBO.getDepartmentList().stream()
                                    .map(SimpleParentModel::getName)
                                    .collect(Collectors.toList()))
                            .setPostNameList(loginCacheUserBO.getPostList().stream()
                                    .map(SimplePostModel::getName)
                                    .collect(Collectors.toList()))
                            .setLastUpdateTime(user.getModified())
                            .setStaffNo(user.getStaffNo());
                }
                return null;
            } catch (MalformedJwtException | ExpiredJwtException exception) {
                return null;
            }
        } else {
            return null;
        }
    }

}
