package com.kexue.skills.common;

import com.kexue.skills.entity.request.LoginUser;
import com.kexue.skills.mapper.*;
import jakarta.servlet.http.HttpServletRequest;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * LoginUser缓存工具类
 * 用于更新Redis中的LoginUser对象
 */
@Component
public class LoginUserCacheUtil {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private CmsContentLikeMapper cmsContentLikeMapper;

    @Resource
    private CmsContentViewMapper cmsContentViewMapper;

    @Resource
    private CmsContentMapper cmsContentMapper;

    @Resource
    private ContentPurchaseMapper contentPurchaseMapper;

    /**
     * 更新用户的收藏列表
     *
     * @param token 用户token
     * @param userId 用户ID
     */
    public void updateFavorites(String token, Long userId) {
        updateLoginUserList(token, userId, "favorites", () -> cmsContentLikeMapper.queryRecentLikesByUserId(userId, 20));
    }

    /**
     * 更新用户的查看历史列表
     *
     * @param token 用户token
     * @param userId 用户ID
     */
    public void updateHistory(String token, Long userId) {
        updateLoginUserList(token, userId, "history", () -> cmsContentViewMapper.queryRecentViewsByUserId(userId, 20));
    }

    /**
     * 更新用户的创建记录列表
     *
     * @param token 用户token
     * @param userId 用户ID
     */
    public void updateCreate(String token, Long userId) {
        updateLoginUserList(token, userId, "create", () -> cmsContentMapper.queryRecentCreatedByUserId(userId, 20));
    }

    /**
     * 更新用户的购买记录列表
     *
     * @param token 用户token
     * @param userId 用户ID
     */
    public void updateHas(String token, Long userId) {
        updateLoginUserList(token, userId, "has", () -> {
            List<Long> has = new ArrayList<>();
            try {
                com.kexue.skills.entity.dto.ContentPurchaseDto purchaseDto = new com.kexue.skills.entity.dto.ContentPurchaseDto();
                purchaseDto.setUserId(userId);
                List<com.kexue.skills.entity.ContentPurchase> purchases = contentPurchaseMapper.getList(purchaseDto);
                if (purchases != null && !purchases.isEmpty()) {
                    java.util.LinkedHashSet<Long> contentIdSet = new java.util.LinkedHashSet<>();
                    for (com.kexue.skills.entity.ContentPurchase purchase : purchases) {
                        if (contentIdSet.size() < 20) {
                            contentIdSet.add(purchase.getContentId());
                        } else {
                            break;
                        }
                    }
                    has.addAll(contentIdSet);
                }
            } catch (Exception e) {
                e.printStackTrace();
                has = java.util.Collections.emptyList();
            }
            return has;
        });
    }

    /**
     * 更新LoginUser中的列表属性
     *
     * @param token     用户token
     * @param userId    用户ID
     * @param fieldName 字段名
     * @param supplier  列表数据提供者
     */
    private void updateLoginUserList(String token, Long userId, String fieldName, java.util.function.Supplier<List<Long>> supplier) {
        try {
            String key = "loginUser:" + token;
            Object loginUserObj = redissonClient.getBucket(key).get();
            if (loginUserObj != null) {
                String loginUserJson = loginUserObj.toString();
                com.kexue.skills.entity.request.LoginUser loginUser = com.alibaba.fastjson.JSON.parseObject(loginUserJson, com.kexue.skills.entity.request.LoginUser.class);
                
                if (loginUser != null && loginUser.getUserInfo() != null && loginUser.getUserInfo().getUserId().equals(userId)) {
                    List<Long> list = supplier.get();
                    
                    switch (fieldName) {
                        case "favorites":
                            loginUser.setFavorites(list);
                            break;
                        case "history":
                            loginUser.setHistory(list);
                            break;
                        case "create":
                            loginUser.setCreate(list);
                            break;
                        case "has":
                            loginUser.setHas(list);
                            break;
                    }
                    
                    // 写回Redis
                    redissonClient.getBucket(key).set(com.alibaba.fastjson.JSON.toJSONString(loginUser));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从请求中获取token
     *
     * @return token
     */
    public String getTokenFromRequest() {
        org.springframework.web.context.request.RequestAttributes requestAttributes = org.springframework.web.context.request.RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null && requestAttributes instanceof org.springframework.web.context.request.ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request != null) {
                return request.getHeader("Authorization");
            }
        }
        return null;
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 用户ID
     */
    public Long getCurrentUserId() {
        try {
            Object loginId = cn.dev33.satoken.stp.StpUtil.getLoginId();
            return Long.parseLong(loginId.toString());
        } catch (Exception e) {
            return null;
        }
    }
}
