package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhentao.common.PageResult;
import com.zhentao.entity.UserBrowseHistory;
import com.zhentao.entity.UserDynamics;
import com.zhentao.mapper.UserBrowseHistoryMapper;
import com.zhentao.mapper.UserDynamicsMapper;
import com.zhentao.service.BrowseHistoryService;
import com.zhentao.vo.DynamicVO;
import com.zhentao.vo.UserSimpleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 浏览历史服务实现类
 */
@Service
public class BrowseHistoryServiceImpl implements BrowseHistoryService {

    @Autowired
    private UserBrowseHistoryMapper browseHistoryMapper;
    
    @Autowired
    private UserDynamicsMapper userDynamicsMapper;
    
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrowseHistory(Integer userId, Integer dynamicId, String browseIp, String deviceInfo) {
        // 查询是否已经存在相同的浏览记录（可能有多条历史遗留记录）
        List<UserBrowseHistory> existingRecords = browseHistoryMapper.selectList(new QueryWrapper<UserBrowseHistory>()
                .eq("user_id", userId)
                .eq("dynamic_id", dynamicId)
                .orderByDesc("browse_time"));
        
        if (existingRecords != null && !existingRecords.isEmpty()) {
            // 如果存在记录，更新最新的一条记录的浏览时间（使其排在最前面）
            UserBrowseHistory latestRecord = existingRecords.get(0);
            latestRecord.setBrowseTime(LocalDateTime.now());
            latestRecord.setBrowseIp(browseIp);
            latestRecord.setDeviceInfo(deviceInfo);
            browseHistoryMapper.updateById(latestRecord);
            
            // 如果存在多条记录，删除其他旧记录（保持数据唯一性）
            if (existingRecords.size() > 1) {
                List<Integer> idsToDelete = existingRecords.subList(1, existingRecords.size())
                        .stream()
                        .map(UserBrowseHistory::getId)
                        .collect(Collectors.toList());
                if (!idsToDelete.isEmpty()) {
                    browseHistoryMapper.deleteBatchIds(idsToDelete);
                }
            }
        } else {
            // 添加新的浏览记录
            UserBrowseHistory history = new UserBrowseHistory();
            history.setUserId(userId);
            history.setDynamicId(dynamicId);
            history.setBrowseTime(LocalDateTime.now());
            history.setBrowseIp(browseIp);
            history.setDeviceInfo(deviceInfo);
            browseHistoryMapper.insert(history);
        }
        
        // 更新动态的浏览次数
        userDynamicsMapper.update(null, new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<UserDynamics>()
                .eq("dynamic_id", dynamicId)
                .setSql("view_count = view_count + 1"));
    }

    @Override
    public PageResult<DynamicVO> getBrowseHistoryList(Integer userId, Integer pageNum, Integer pageSize) {
        // 查询用户浏览的动态ID列表（按浏览时间倒序）
        List<Integer> browseDynamicIds = browseHistoryMapper.selectList(new QueryWrapper<UserBrowseHistory>()
                .eq("user_id", userId)
                .orderByDesc("browse_time"))
                .stream()
                .map(UserBrowseHistory::getDynamicId)
                .collect(Collectors.toList());
        
        if (browseDynamicIds.isEmpty()) {
            return new PageResult<DynamicVO>(new java.util.ArrayList<>(), 0L, Long.valueOf(pageNum), Long.valueOf(pageSize));
        }
        
        // 手动分页：计算起始索引和结束索引
        int total = browseDynamicIds.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        
        if (startIndex >= total) {
            return new PageResult<DynamicVO>(new java.util.ArrayList<>(), (long)total, Long.valueOf(pageNum), Long.valueOf(pageSize));
        }
        
        // 获取当前页的动态ID列表
        List<Integer> pageDynamicIds = browseDynamicIds.subList(startIndex, endIndex);
        
        // 查询动态详情（关联用户信息）- 不进行分页，因为我们已经手动分页了
        Page<UserDynamics> page = new Page<>(1, pageDynamicIds.size());
        com.baomidou.mybatisplus.core.metadata.IPage<UserDynamics> pg = userDynamicsMapper.selectDynamicsByIds(page, pageDynamicIds, userId);
        
        // 按照原始ID列表的顺序重新排序（保持浏览时间倒序）
        Map<Integer, DynamicVO> dynamicMap = pg.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toMap(DynamicVO::getDynamicId, vo -> vo, (v1, v2) -> v1));
        
        List<DynamicVO> list = pageDynamicIds.stream()
                .map(dynamicMap::get)
                .filter(vo -> vo != null)
                .collect(Collectors.toList());
        
        return new PageResult<>(list, (long)total, Long.valueOf(pageNum), Long.valueOf(pageSize));
    }
    
    /**
     * 将实体类转换为VO
     */
    private DynamicVO convertToVO(UserDynamics dynamic) {
        DynamicVO vo = new DynamicVO();
        org.springframework.beans.BeanUtils.copyProperties(dynamic, vo);

        // 解析媒体URL JSON字符串
        if (dynamic.getMediaUrls() != null && !dynamic.getMediaUrls().isEmpty()) {
            try {
                List<String> urls = objectMapper.readValue(
                        dynamic.getMediaUrls(), 
                        new TypeReference<List<String>>() {}
                );
                vo.setMediaUrls(urls);
            } catch (Exception e) {
                vo.setMediaUrls(new ArrayList<>());
            }
        } else {
            vo.setMediaUrls(new ArrayList<>());
        }

        // 确保 isLiked 和 isFavorited 正确转换为 Boolean（根据 dynamic_likes 和 dynamic_favorites 表判断）
        // SQL 返回 1/0，MyBatis 会映射为 Boolean，但为了安全起见，确保正确转换
        Object isLikedObj = dynamic.getIsLiked();
        if (isLikedObj != null) {
            if (isLikedObj instanceof Boolean) {
                vo.setIsLiked((Boolean) isLikedObj);
            } else if (isLikedObj instanceof Integer) {
                vo.setIsLiked(((Integer) isLikedObj) == 1);
            } else if (isLikedObj instanceof Number) {
                vo.setIsLiked(((Number) isLikedObj).intValue() == 1);
            } else {
                vo.setIsLiked(Boolean.TRUE.equals(isLikedObj));
            }
        } else {
            vo.setIsLiked(false);
        }

        Object isFavoritedObj = dynamic.getIsFavorited();
        if (isFavoritedObj != null) {
            if (isFavoritedObj instanceof Boolean) {
                vo.setIsFavorited((Boolean) isFavoritedObj);
            } else if (isFavoritedObj instanceof Integer) {
                vo.setIsFavorited(((Integer) isFavoritedObj) == 1);
            } else if (isFavoritedObj instanceof Number) {
                vo.setIsFavorited(((Number) isFavoritedObj).intValue() == 1);
            } else {
                vo.setIsFavorited(Boolean.TRUE.equals(isFavoritedObj));
            }
        } else {
            vo.setIsFavorited(false);
        }

        // 转换用户信息
        if (dynamic.getUser() != null) {
            UserSimpleVO userVO = new UserSimpleVO();
            userVO.setUserId(dynamic.getUser().getUserId());
            userVO.setNickname(dynamic.getUser().getNickname());
            userVO.setAvatarUrl(dynamic.getUser().getAvatarUrl());
            userVO.setGender(dynamic.getUser().getGender());
            vo.setUser(userVO);
        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearBrowseHistory(Integer userId) {
        // 清空用户的所有浏览记录
        browseHistoryMapper.delete(new QueryWrapper<UserBrowseHistory>()
                .eq("user_id", userId));
    }
}
