package com.ruoyi.framework.web.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.info.management.api.ManagementTeacherApi;
import com.ruoyi.info.management.dto.ManagementTeacherDto;
import com.ruoyi.info.nursing.api.NursingWorkerApi;
import com.ruoyi.info.nursing.dto.NursingWorkerDto;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.model.UserCacheInfo;
import com.ruoyi.user.domain.vo.UserVo;
import com.ruoyi.user.service.IUserService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * 小程序token验证处理
 *
 * @author ruoyi
 */
@Component
public class ApiTokenService {
    // token自定义标识
    @Value("${api-token.header}")
    private String header;
    // token令牌秘钥
    @Value("${api-token.secret}")
    private String secret;
    // token有效期
    @Value("${api-token.expireTime}")
    private int expireTime;
    // token有效期
    @Value("${api-token.refreshTime}")
    private int refreshTime;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private ManagementTeacherApi managementTeacherApi;

    @Autowired
    private NursingWorkerApi nursingWorkerApi;

    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        // 自定义参数，把需要存入token的参数都可以自定义到这里，比如 角色 部门类的关键参数
        claims.put(Constants.USER_ID, user.getId());
        return doGenerateToken(claims, user.getNickname());
    }

    public void removeToken(String token) {
        UserCacheInfo user = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(Constants.JWT_TOKEN + token), UserCacheInfo.class);
        stringRedisTemplate.delete(Constants.JWT_TOKEN +  token);
        // 删除userId关联的token
        stringRedisTemplate.opsForSet().remove(Constants.JWT_ONLINE_USER_TOKEN + user.getId(), token);
    }

    /**
     * 根据手机号强制登出用户
     *
     * @param mobile
     */
    public void forcedLogoutByMobile(String mobile) {
        // 获取护工对应的用户id
        User user = userService.loadByMobile(mobile, true);
        Set<String> tokens = stringRedisTemplate.opsForSet().members(Constants.JWT_ONLINE_USER_TOKEN + user.getId());
        if (CollUtil.isNotEmpty(tokens)) {
            for (String token : tokens) {
                removeToken(token);
            }
        }
    }

    /**
     * 生成小程序token
     *
     * @param claims
     * @param subject
     * @return
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = new Date();
        final Date expirationDate = calculateExpirationDate(createdDate);

        System.out.println("当前时间+" + DateUtil.format(createdDate, DateUtils.YYYY_MM_DD_HH_MM_SS));
        System.out.println("过期时间+" + DateUtil.format(expirationDate, DateUtils.YYYY_MM_DD_HH_MM_SS));

        String token = Jwts.builder()
            .setClaims(claims) // 存入自定义参数
            .setSubject(subject)
            .setIssuedAt(createdDate)
            .setExpiration(expirationDate)
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();

        //  缓存用户信息至redis
        Long userId = (Long) claims.get(Constants.USER_ID);
        cacheUserInfo(userId, token);

        return token;
    }


    /**
     * 计算过期时间
     *
     * @param createdDate
     * @return
     */
    private Date calculateExpirationDate(Date createdDate) {
        return DateUtils.addSeconds(createdDate, expireTime);
    }

    /**
     * 判断是否在需要刷新token的临界值以内
     *
     * @param expirationDate 过期时间
     * @return
     */
    public Boolean isRefreshToken(Date expirationDate) {
        //判断是否过期
        if (expirationDate.getTime() <= System.currentTimeMillis()) {
            return false;
        }
        //间隔时间
        long intervalSeconds = (expirationDate.getTime() - System.currentTimeMillis()) / 1000;
        return intervalSeconds <= refreshTime;
    }

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    public Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    private void cacheUserInfo(Long userId, String token) {
        UserVo userVo = userService.getUserById(userId, true);
        UserCacheInfo userCacheInfo = BeanCopyUtils.copy(userVo, UserCacheInfo.class);

        if (userCacheInfo == null) {
            throw new ServiceException("用户不存在");
        }
        // 查询是否为管理老师
        ManagementTeacherDto managementTeacherDto = managementTeacherApi.getByPhoneNumber(userVo.getMobile(), true);
        if (managementTeacherDto != null) {
            userCacheInfo.setTeacherId(managementTeacherDto.getId());
        }
        // 查询是否为护工
        NursingWorkerDto nursingWorkerDto = nursingWorkerApi.getByPhoneNumber(userVo.getMobile(), true);
        if (nursingWorkerDto != null) {
            userCacheInfo.setWorkerId(nursingWorkerDto.getId());
        }

        // 缓存至redis
        stringRedisTemplate.opsForValue().set(Constants.JWT_TOKEN + token, JSONUtil.toJsonStr(userCacheInfo), expireTime, TimeUnit.SECONDS);
        // 缓存用户在线用户userId，方便强制踢出
        stringRedisTemplate.opsForSet().add(Constants.JWT_ONLINE_USER_TOKEN + userId, token);
    }

}
