package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.PageResult;
import com.emotion.dto.request.UserStatsCreateRequest;
import com.emotion.dto.request.UserStatsIncrementRequest;
import com.emotion.dto.request.UserStatsPageRequest;
import com.emotion.dto.request.UserStatsUpdateValueRequest;
import com.emotion.dto.response.UserStatsResponse;
import com.emotion.entity.UserStats;
import com.emotion.mapper.UserStatsMapper;
import com.emotion.service.UserStatsService;
import com.emotion.util.SnowflakeIdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户统计服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class UserStatsServiceImpl extends ServiceImpl<UserStatsMapper, UserStats> implements UserStatsService {

    private final SnowflakeIdGenerator snowflakeIdGenerator;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public UserStatsServiceImpl(SnowflakeIdGenerator snowflakeIdGenerator) {
        this.snowflakeIdGenerator = snowflakeIdGenerator;
    }

    @Override
    public PageResult<UserStatsResponse> getPageWithResponse(UserStatsPageRequest request) {
        Page<UserStats> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<UserStats> wrapper = new LambdaQueryWrapper<>();

        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.like(UserStats::getUserId, request.getKeyword())
                    .or().like(UserStats::getStatsType, request.getKeyword());
        }

        // 用户ID查询
        if (StringUtils.hasText(request.getUserId())) {
            wrapper.eq(UserStats::getUserId, request.getUserId());
        }

        // 统计类型查询
        if (StringUtils.hasText(request.getStatsType())) {
            wrapper.eq(UserStats::getStatsType, request.getStatsType());
        }

        wrapper.eq(UserStats::getIsDeleted, 0);

        // 排序
        if (StringUtils.hasText(request.getOrderBy())) {
            if ("asc".equalsIgnoreCase(request.getOrderDirection())) {
                wrapper.orderByAsc(UserStats::getCreateTime);
            } else {
                wrapper.orderByDesc(UserStats::getCreateTime);
            }
        } else {
            wrapper.orderByDesc(UserStats::getCreateTime);
        }

        Page<UserStats> resultPage = this.page(page, wrapper);
        List<UserStatsResponse> responses = resultPage.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        PageResult<UserStatsResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setRecords(responses);

        return pageResult;
    }

    @Override
    public boolean updateStatsValue(UserStatsUpdateValueRequest request) {
        LambdaUpdateWrapper<UserStats> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserStats::getUserId, request.getUserId())
                .eq(UserStats::getStatsType, request.getStatsType())
                .eq(UserStats::getIsDeleted, 0)
                .set(UserStats::getValue, request.getValue())
                .set(UserStats::getUpdateTime, LocalDateTime.now());
        return this.update(wrapper);
    }

    @Override
    public boolean incrementStatsValue(UserStatsIncrementRequest request) {
        LambdaUpdateWrapper<UserStats> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserStats::getUserId, request.getUserId())
                .eq(UserStats::getStatsType, request.getStatsType())
                .eq(UserStats::getIsDeleted, 0)
                .setSql("value = value + " + request.getIncrement())
                .set(UserStats::getUpdateTime, LocalDateTime.now());
        return this.update(wrapper);
    }

    @Override
    public boolean recalculateUserStats(String userId) {
        // 这里应该根据业务逻辑重新计算用户统计数据
        // 示例：更新用户的总活跃天数、总发帖数等
        return true;
    }

    @Override
    public boolean recalculateAllUserStats() {
        // 这里应该重新计算所有用户的统计数据
        return true;
    }

    @Override
    public UserStatsResponse createOrUpdateUserStatsWithResponse(UserStatsCreateRequest request) {
        UserStats stats = createOrUpdateUserStats(request.getUserId(), request.getStatsType(), request.getValue(),
                request.getPeriod());
        return convertToResponse(stats);
    }

    @Override
    public boolean deleteExpiredStats(Integer days) {
        LocalDateTime expireTime = LocalDateTime.now().minusDays(days);
        LambdaUpdateWrapper<UserStats> wrapper = new LambdaUpdateWrapper<>();
        wrapper.lt(UserStats::getCreateTime, expireTime)
                .set(UserStats::getIsDeleted, 1)
                .set(UserStats::getUpdateTime, LocalDateTime.now());
        return this.update(wrapper);
    }

    /**
     * 创建或更新用户统计
     */
    private UserStats createOrUpdateUserStats(String userId, String statsType, Double value, String period) {
        UserStats stats = getByUserIdAndStatsType(userId, statsType);
        if (stats == null) {
            stats = new UserStats();
            stats.setId(snowflakeIdGenerator.nextIdAsString());
            stats.setUserId(userId);
            stats.setStatsType(statsType);
            stats.setValue(value);
            stats.setPeriod(period);
            stats.setCreateTime(LocalDateTime.now());
            stats.setUpdateTime(LocalDateTime.now());
            stats.setIsDeleted(0);
            this.save(stats);
        } else {
            stats.setValue(value);
            stats.setPeriod(period);
            stats.setUpdateTime(LocalDateTime.now());
            this.updateById(stats);
        }
        return stats;
    }

    /**
     * 根据用户ID和统计类型获取统计信息
     */
    private UserStats getByUserIdAndStatsType(String userId, String statsType) {
        LambdaQueryWrapper<UserStats> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserStats::getUserId, userId)
                .eq(UserStats::getStatsType, statsType)
                .eq(UserStats::getIsDeleted, 0);
        return this.getOne(wrapper);
    }

    /**
     * 转换为响应对象
     */
    private UserStatsResponse convertToResponse(UserStats stats) {
        UserStatsResponse response = new UserStatsResponse();
        BeanUtils.copyProperties(stats, response);
        response.setId(stats.getId());
        if (stats.getCreateTime() != null) {
            response.setCreateTime(stats.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (stats.getUpdateTime() != null) {
            response.setUpdateTime(stats.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }
}