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.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) {
        // 先检查是否已经存在相同的浏览记录（避免重复记录）
        UserBrowseHistory existingRecord = browseHistoryMapper.selectOne(new QueryWrapper<UserBrowseHistory>()
                .eq("user_id", userId)
                .eq("dynamic_id", dynamicId));
        
        if (existingRecord != null) {
            // 更新浏览时间
            existingRecord.setBrowseTime(LocalDateTime.now());
            existingRecord.setBrowseIp(browseIp);
            existingRecord.setDeviceInfo(deviceInfo);
            browseHistoryMapper.updateById(existingRecord);
        } 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));
        }
        
        // 查询动态详情（关联用户信息）
        Page<UserDynamics> page = new Page<>(pageNum, pageSize);
        com.baomidou.mybatisplus.core.metadata.IPage<UserDynamics> pg = userDynamicsMapper.selectDynamicsByIds(page, browseDynamicIds, userId);
        
        List<DynamicVO> list = pg.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return new PageResult<>(list, pg.getTotal(), pg.getCurrent(), pg.getSize());
    }
    
    /**
     * 将实体类转换为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<>());
        }

        // 转换用户信息
        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));
    }
}
