package shop.alien.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.second.SecondUserCredit;
import shop.alien.entity.second.SecondUserCreditDateRecord;
import shop.alien.entity.second.SecondUserCreditRecord;
import shop.alien.entity.second.vo.SecondUserCreditRecordListVo;
import shop.alien.entity.store.LifeUserLearningRecord;
import shop.alien.entity.store.LifeUserLearningVideo;
import shop.alien.mapper.LifeUserLearningRecordMapper;
import shop.alien.mapper.LifeUserLearningVideoMapper;
import shop.alien.mapper.second.SecondUserCreditDateRecordMapper;
import shop.alien.mapper.second.SecondUserCreditMapper;
import shop.alien.mapper.second.SecondUserCreditRecordMapper;
import shop.alien.second.service.SecondUserCreditRecordService;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 二手平台用户积分记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondUserCreditRecordServiceImpl extends ServiceImpl<SecondUserCreditRecordMapper, SecondUserCreditRecord> implements SecondUserCreditRecordService {
    
    private final SecondUserCreditRecordMapper secondUserCreditRecordMapper;
    private final SecondUserCreditMapper secondUserCreditMapper;
    private final SecondUserCreditDateRecordMapper secondUserCreditDateRecordMapper;
    private final LifeUserLearningVideoMapper lifeUserLearningVideoMapper;
    private final LifeUserLearningRecordMapper lifeUserLearningRecordMapper;

    /**
     * 根据用户ID获取积分记录列表
     * @param userId 用户ID
     * @return 积分记录列表
     */
    @Override
    public List<SecondUserCreditRecord> getRecordsByUserId(Integer userId) {
        log.info("查询用户积分记录，userId={}", userId);
        LambdaQueryWrapper<SecondUserCreditRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondUserCreditRecord::getUserId, userId)
                .eq(SecondUserCreditRecord::getDeleteFlag, 0)
                .orderByDesc(SecondUserCreditRecord::getCreatedTime);
        return secondUserCreditRecordMapper.selectList(queryWrapper);
    }
    
    /**
     * 创建积分记录
     * @param record 积分记录信息
     * @return 是否创建成功
     */
    @Override
    public boolean createRecord(SecondUserCreditRecord record) {
        try {
            log.info("创建积分记录，userId={}, points={}", record.getUserId(), record.getPoints());
            record.setDeleteFlag(0);
            record.setCreatedTime(new Date());
            record.setUpdatedTime(new Date());
            int result = secondUserCreditRecordMapper.insert(record);
            return result > 0;
        } catch (Exception e) {
            log.error("创建积分记录失败，userId={}, points={}", record.getUserId(), record.getPoints(), e);
            return false;
        }
    }

    @Override
    public R<SecondUserCreditRecordListVo> getByUserId(Integer userId, Integer timeRange, Integer pointsType) {
        log.info("SecondUserCreditRecordServiceImpl.getByUserId, userId={}, timeRange={}, pointsType={}", userId, timeRange, pointsType);
        LambdaQueryWrapper<SecondUserCreditRecord> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SecondUserCreditRecord> recordsChangeQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondUserCreditRecord::getUserId, userId);
        recordsChangeQueryWrapper.eq(SecondUserCreditRecord::getUserId, userId);

        // 根据时间范围过滤
        Date startTime = null;
        if (timeRange != null) {
            startTime = calculateStartTime(timeRange);
            if (startTime != null) {
                queryWrapper.ge(SecondUserCreditRecord::getCreatedTime, startTime);
            }
        }

        // 根据积分类型过滤：0-全部，1-正分，2-负分
        if (pointsType != null) {
            if (pointsType == 1) {
                // 正分：points > 0
                recordsChangeQueryWrapper.gt(SecondUserCreditRecord::getPoints, 0);
            } else if (pointsType == 2) {
                // 负分：points < 0
                recordsChangeQueryWrapper.lt(SecondUserCreditRecord::getPoints, 0);
            }
            // pointsType == 0 或 null 表示全部，不需要过滤
        }

        recordsChangeQueryWrapper.orderByDesc(SecondUserCreditRecord::getCreatedTime);
        queryWrapper.orderByDesc(SecondUserCreditRecord::getCreatedTime);
        List<SecondUserCreditRecord> recordsChange = this.list(recordsChangeQueryWrapper);
        
        // 查询日期积分记录，按照相同的时间范围筛选
        LambdaQueryWrapper<SecondUserCreditDateRecord> dateRecordQueryWrapper = new LambdaQueryWrapper<>();
        dateRecordQueryWrapper.eq(SecondUserCreditDateRecord::getUserId, userId);
        
        if (startTime != null) {
            // 将开始时间转换为日期（忽略时间部分）
            Calendar cal = Calendar.getInstance();
            cal.setTime(startTime);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            Date startDate = cal.getTime();
            dateRecordQueryWrapper.ge(SecondUserCreditDateRecord::getRecordDate, startDate);
        }
        
        dateRecordQueryWrapper.orderByDesc(SecondUserCreditDateRecord::getRecordDate);
        List<SecondUserCreditDateRecord> dateRecords = secondUserCreditDateRecordMapper.selectList(dateRecordQueryWrapper);
        
        // 查询用户积分
        Integer userPoints = null;
        SecondUserCredit secondUserCredit = this.getUserCreditByUserId(userId);
        if (secondUserCredit != null) {
            userPoints = secondUserCredit.getUserPoints();
        }
        
        // 构建返回对象
        SecondUserCreditRecordListVo result = new SecondUserCreditRecordListVo();
        result.setRecordsChange(recordsChange);
        result.setDateRecords(dateRecords);
        result.setUserPoints(userPoints);
        return R.data(result);
    }

    /**
     * 根据时间范围计算开始时间
     * @param timeRange 时间范围：1-近一周，2-近一个月，3-近一年
     * @return 开始时间
     */
    private Date calculateStartTime(Integer timeRange) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        switch (timeRange) {
            case 1: // 近一周
                calendar.add(Calendar.DAY_OF_YEAR, -7);
                break;
            case 2: // 近一个月
                calendar.add(Calendar.MONTH, -1);
                break;
            case 3: // 近一年
                calendar.add(Calendar.YEAR, -1);
                break;
            default:
                return null;
        }

        return calendar.getTime();
    }

    @Override
    public R<String> addPointsAfterWatchingVideo(Integer userId, Integer learningId) {
        log.info("用户观看完学习视频后增加积分，userId={}, learningId={}", userId, learningId);
        
        try {
            // 1. 查询学习视频信息，获取奖励分数
            LifeUserLearningVideo learningVideo = lifeUserLearningVideoMapper.selectById(learningId);
            if (learningVideo == null) {
                return R.fail("学习视频不存在");
            }
            
            Integer score = learningVideo.getScore();
            if (score == null || score <= 0) {
                return R.fail("该学习视频没有奖励分数");
            }
            
            // 2. 检查是否已经观看过（避免重复奖励）
            LambdaQueryWrapper<LifeUserLearningRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
            recordQueryWrapper.eq(LifeUserLearningRecord::getUserId, userId)
                    .eq(LifeUserLearningRecord::getLearningId, learningId)
                    .eq(LifeUserLearningRecord::getDeleteFlag, 0);
            long count = lifeUserLearningRecordMapper.selectCount(recordQueryWrapper);
            if (count > 0) {
                return R.fail("您已经观看过该视频，无法重复获得奖励");
            }
            
            // 3. 查询或创建用户积分记录
            SecondUserCredit userCredit = this.getUserCreditByUserId(userId);
            if (userCredit == null) {
                // 如果用户没有积分记录，先创建
                userCredit = new SecondUserCredit();
                userCredit.setUserId(userId);
                userCredit.setUserPoints(0);
                userCredit.setDeleteFlag(0);
                userCredit.setCreatedTime(new Date());
                userCredit.setUpdatedTime(new Date());
                secondUserCreditMapper.insert(userCredit);
            }
            
            // 4. 更新用户积分
            secondUserCreditMapper.updatePointsByUserId(userId, score);
            
            // 5. 添加积分记录（pointsType = 8 表示学习视频奖励）
            SecondUserCreditRecord creditRecord = new SecondUserCreditRecord();
            creditRecord.setUserId(userId);
            creditRecord.setPoints(score);
            creditRecord.setCurrentScoreCount(userCredit.getUserPoints() + score);
            creditRecord.setPointsType(8); // 8-学习视频奖励
            creditRecord.setDeleteFlag(0);
            creditRecord.setCreatedTime(new Date());
            creditRecord.setUpdatedTime(new Date());
            secondUserCreditRecordMapper.insert(creditRecord);
            
            // 6. 添加学习记录
            LifeUserLearningRecord learningRecord = new LifeUserLearningRecord();
            learningRecord.setUserId(userId);
            learningRecord.setLearningId(learningId);
            learningRecord.setDeleteFlag(0);
            learningRecord.setCreatedTime(new Date());
            learningRecord.setUpdatedTime(new Date());
            lifeUserLearningRecordMapper.insert(learningRecord);
            
            log.info("用户观看完学习视频后增加积分成功，userId={}, learningId={}, score={}", userId, learningId, score);
            return R.success("观看视频成功，获得" + score + "积分");
            
        } catch (Exception e) {
            log.error("用户观看完学习视频后增加积分失败，userId={}, learningId={}", userId, learningId, e);
            return R.fail("操作失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID获取用户积分信息
     * @param userId 用户ID
     * @return 用户积分信息
     */
    private SecondUserCredit getUserCreditByUserId(Integer userId) {
        LambdaQueryWrapper<SecondUserCredit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondUserCredit::getUserId, userId)
                .eq(SecondUserCredit::getDeleteFlag, 0);
        return secondUserCreditMapper.selectOne(queryWrapper);
    }
}