package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.Matchmaker;
import com.zhentao.entity.PointRule;
import com.zhentao.entity.PointsDetail;
import com.zhentao.mapper.MatchmakerMapper;
import com.zhentao.mapper.PointRuleMapper;
import com.zhentao.mapper.PointsDetailMapper;
import com.zhentao.service.PointsManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 积分管理Service实现
 *
 * @author zhentao
 * @since 2025-12-10
 */
@Service
public class PointsManageServiceImpl implements PointsManageService {

    @Autowired
    private MatchmakerMapper matchmakerMapper;

    @Autowired
    private PointRuleMapper pointRuleMapper;

    @Autowired
    private PointsDetailMapper pointsDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPointsByRuleName(Integer makerId, String ruleName, String reason) {
        // 根据规则名称查询积分规则
        PointRule rule = pointRuleMapper.selectByRuleName(ruleName);
        if (rule == null) {
            System.err.println("积分规则不存在: " + ruleName);
            return false;
        }
        if (rule.getStatus() != 1) {
            System.err.println("积分规则未启用: " + ruleName);
            return false;
        }
        if (rule.getPointValue() <= 0) {
            System.err.println("积分值必须为正数: " + ruleName);
            return false;
        }

        // 构建积分变动原因
        String fullReason = rule.getRuleName();
        if (reason != null && !reason.isEmpty()) {
            fullReason += "-" + reason;
        }

        // 调用添加积分方法
        return addPoints(makerId, rule.getPointValue(), fullReason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPointsByRuleType(Integer makerId, Integer ruleType, String reason) {
        // 根据规则类型查询积分规则
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PointRule> wrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        wrapper.eq("rule_type", ruleType).eq("status", 1);
        PointRule rule = pointRuleMapper.selectOne(wrapper);
        
        if (rule == null) {
            System.err.println("积分规则不存在，规则类型: " + ruleType);
            return false;
        }
        if (rule.getPointValue() <= 0) {
            System.err.println("积分值必须为正数，规则类型: " + ruleType);
            return false;
        }

        // 构建积分变动原因
        String fullReason = rule.getRuleName();
        if (reason != null && !reason.isEmpty()) {
            fullReason += "-" + reason;
        }

        System.out.println("添加积分 - 红娘ID: " + makerId + ", 规则类型: " + ruleType + 
                          ", 规则名称: " + rule.getRuleName() + ", 积分值: " + rule.getPointValue());

        // 调用添加积分方法
        return addPoints(makerId, rule.getPointValue(), fullReason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPoints(Integer makerId, Integer points, String reason) {
        // 查询当前红娘信息
        Matchmaker matchmaker = matchmakerMapper.selectById(makerId);
        if (matchmaker == null) {
            System.err.println("红娘不存在: " + makerId);
            return false;
        }

        // 计算新的积分值
        Integer currentPoints = matchmaker.getPoints() == null ? 0 : matchmaker.getPoints();
        Integer newPoints = currentPoints + points;

        // 更新红娘积分
        matchmaker.setPoints(newPoints);
        int updateResult = matchmakerMapper.updateById(matchmaker);
        if (updateResult <= 0) {
            System.err.println("更新红娘积分失败: " + makerId);
            return false;
        }

        // 添加积分明细
        PointsDetail detail = new PointsDetail();
        detail.setMakerId(makerId);
        detail.setPoints(points);
        detail.setReason(reason);
        detail.setRemainPoints(newPoints);
        detail.setCreateTime(LocalDateTime.now());
        detail.setUpdateTime(LocalDateTime.now());
        int insertResult = pointsDetailMapper.insert(detail);
        if (insertResult <= 0) {
            System.err.println("添加积分明细失败: " + makerId);
            return false;
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductPoints(Integer makerId, Integer points, String reason) {
        // 查询当前红娘信息
        Matchmaker matchmaker = matchmakerMapper.selectById(makerId);
        if (matchmaker == null) {
            System.err.println("红娘不存在: " + makerId);
            return false;
        }

        // 检查积分是否足够
        Integer currentPoints = matchmaker.getPoints() == null ? 0 : matchmaker.getPoints();
        if (currentPoints < points) {
            System.err.println("积分不足: " + makerId);
            return false;
        }

        // 计算新的积分值
        Integer newPoints = currentPoints - points;

        // 更新红娘积分
        matchmaker.setPoints(newPoints);
        int updateResult = matchmakerMapper.updateById(matchmaker);
        if (updateResult <= 0) {
            System.err.println("更新红娘积分失败: " + makerId);
            return false;
        }

        // 添加积分明细（使用负数表示扣除）
        PointsDetail detail = new PointsDetail();
        detail.setMakerId(makerId);
        detail.setPoints(-points);
        detail.setReason(reason);
        detail.setRemainPoints(newPoints);
        detail.setCreateTime(LocalDateTime.now());
        detail.setUpdateTime(LocalDateTime.now());
        int insertResult = pointsDetailMapper.insert(detail);
        if (insertResult <= 0) {
            System.err.println("添加积分明细失败: " + makerId);
            return false;
        }

        return true;
    }

    @Override
    public Integer getPointsBalance(Integer makerId) {
        Matchmaker matchmaker = matchmakerMapper.selectById(makerId);
        if (matchmaker == null) {
            return 0;
        }
        return matchmaker.getPoints() == null ? 0 : matchmaker.getPoints();
    }

    @Override
    public Page<PointsDetail> getPointsDetail(Integer makerId, Integer page, Integer pageSize) {
        Page<PointsDetail> pages = new Page<>(page, pageSize);
        return pointsDetailMapper.selectPage(pages, null);
    }
}