package com.tangguo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangguo.common.domain.PointsDetailInfo;
import com.tangguo.common.domain.QwmhUserInfo;
import com.tangguo.common.exception.ServiceException;
import com.tangguo.common.utils.SecurityUtils;
import com.tangguo.domain.BbsGrade;
import com.tangguo.domain.BbsUserPoints;
import com.tangguo.domain.BbsUserPointsDetail;
import com.tangguo.mapper.BbsUserPointsMapper;
import com.tangguo.service.IBbsGradeService;
import com.tangguo.service.IBbsUserPointsDetailService;
import com.tangguo.service.IBbsUserPointsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 用户积分Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-29
 */
@Service
public class BbsUserPointsServiceImpl extends ServiceImpl<BbsUserPointsMapper, BbsUserPoints> implements IBbsUserPointsService {

    @Resource
    private BbsUserPointsMapper bbsUserPointsMapper;

    @Resource
    private BbsUserPointsServiceImpl pointsServiceImpl;

    @Resource
    private IBbsUserPointsDetailService pointsDetailService;

    @Resource
    private IBbsGradeService gradeService;


    /**
     * 查询用户积分列表
     *
     * @param points 用户积分
     * @return 用户积分
     */
    @Override
    public List<BbsUserPoints> selectBbsUserPointsList(BbsUserPoints points) {
        return this.baseMapper.selectBbsUserPointsList(points);
    }


    /**
     * 查询用户积分
     *
     * @param userName 用户名
     * @return 积分
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public BbsUserPoints getUserPoints(String userName) {
        BbsUserPoints dbUserPoints = this.baseMapper.selectUserPoints(userName);
        if (Objects.isNull(dbUserPoints)) {
            QwmhUserInfo qwmhSysUser = this.baseMapper.selectQwmhUser(userName);
            if (Objects.isNull(qwmhSysUser)) {
                throw new ServiceException("查询用户积分失败，未查询到当前用户数据。");
            } else {
                dbUserPoints = new BbsUserPoints();
                dbUserPoints.setUserName(userName);
                dbUserPoints.setAccumulatedPoints(0);
                dbUserPoints.setCurrentPoints(0);
                BbsGrade dbGrade = this.gradeService.getInitialGrade();
                if (Objects.nonNull(dbGrade)) {
                    dbUserPoints.setGradeCode(dbGrade.getCode());
                    dbUserPoints.setGradeName(dbGrade.getName());
                    dbUserPoints.setLastUpgradeTime(new Date());
                }
                this.save(dbUserPoints);
            }
        }
        return dbUserPoints;
    }


    /**
     * 增加用户积分
     *
     * @param points 积分
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserPoints(BbsUserPoints points) {
        String userName = points.getUserName();
        PointsDetailInfo detail = new PointsDetailInfo();
        detail.setUserName(userName);
        detail.setDetailPoints(points.getIncrOrDecrPoints());
        detail.setDetailName("后台手动增加");
        detail.setDescription(String.format("管理员【%s】后台手动增加用户【%s】积分", SecurityUtils.getUsername(), userName));
        this.incrUserPoints(detail);
    }


    /**
     * 扣减用户积分
     *
     * @param points 积分
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteUserPoints(BbsUserPoints points) {
        String userName = points.getUserName();
        PointsDetailInfo detail = new PointsDetailInfo();
        detail.setUserName(userName);
        detail.setDetailPoints(points.getIncrOrDecrPoints());
        detail.setDetailName("后台手动扣减");
        detail.setDescription(String.format("管理员【%s】后台手动扣减用户【%s】积分", SecurityUtils.getUsername(), userName));
        this.decrUserPoints(detail);
    }


    /**
     * 增加用户积分
     *
     * @param detail   积分明细
     */
    @Override
    public void incrUserPoints(PointsDetailInfo detail) {
        synchronized (detail.getUserName().intern()) {
            this.pointsServiceImpl.privIncrUserPoints(detail);
        }
    }


    /**
     * 扣减用户积分
     *
     * @param detail   积分明细
     */
    @Override
    public void decrUserPoints(PointsDetailInfo detail) {
        synchronized (detail.getUserName().intern()) {
            this.pointsServiceImpl.privDecrUserPoints(detail);
        }
    }


    /**
     * 增加用户积分
     *
     * @param detail   积分明细
     */
    @Transactional(rollbackFor = Exception.class)
    public void privIncrUserPoints(PointsDetailInfo detail) {
        int points = detail.getDetailPoints();
        if (points < 1) {
            throw new ServiceException("增加用户积分失败，增加的积分分值不能小于0。");
        }

        // 更新用户积分
        String userName = detail.getUserName();
        BbsUserPoints userPoints = this.pointsServiceImpl.getUserPoints(userName);
        int beforeCurrentPoints = userPoints.getCurrentPoints();
        int afterCurrentPoints = beforeCurrentPoints + points;
        userPoints.setCurrentPoints(afterCurrentPoints);
        int accumulatedPoints = userPoints.getAccumulatedPoints() + points;
        userPoints.setAccumulatedPoints(accumulatedPoints);

        // 更新用户等级
        BbsGrade dbGrade = this.gradeService.getGradeByPoints(accumulatedPoints);
        if (Objects.nonNull(dbGrade) && !dbGrade.getCode().equals(userPoints.getGradeCode())) {
            userPoints.setGradeName(dbGrade.getName());
            userPoints.setGradeCode(dbGrade.getCode());
            userPoints.setLastUpgradeTime(new Date());
        }
        this.updateById(userPoints);

        // 添加用户积分明细
        BbsUserPointsDetail newDetail = new BbsUserPointsDetail();
        newDetail.setUserName(userName);
        newDetail.setDetailName(detail.getDetailName());
        newDetail.setDetailCode(detail.getDetailCode());
        newDetail.setDetailPoints(points);
        newDetail.setBeforePoints(beforeCurrentPoints);
        newDetail.setAfterPoints(afterCurrentPoints);
        newDetail.setDescription(detail.getDescription());
        this.pointsDetailService.save(newDetail);
    }


    /**
     * 扣减用户积分
     *
     * @param detail   积分明细
     */
    @Transactional(rollbackFor = Exception.class)
    public void privDecrUserPoints(PointsDetailInfo detail) {
        int points = detail.getDetailPoints();
        if (points < 1) {
            throw new ServiceException("扣减用户积分失败，扣减的积分分值不能小于0。");
        }

        // 更新用户积分
        String userName = detail.getUserName();
        BbsUserPoints userPoints = this.pointsServiceImpl.getUserPoints(userName);
        Integer beforeCurrentPoints = userPoints.getCurrentPoints();
        if (points > beforeCurrentPoints) {
            throw new ServiceException("扣减用户积分失败，当前用户可用积分不足。");
        }

        int afterCurrentPoints = beforeCurrentPoints - points;
        userPoints.setCurrentPoints(afterCurrentPoints);
        this.updateById(userPoints);

        // 添加用户积分明细
        BbsUserPointsDetail newDetail = new BbsUserPointsDetail();
        newDetail.setUserName(userName);
        newDetail.setDetailName(detail.getDetailName());
        newDetail.setDetailCode(detail.getDetailCode());
        newDetail.setDetailPoints(points);
        newDetail.setBeforePoints(beforeCurrentPoints);
        newDetail.setAfterPoints(afterCurrentPoints);
        newDetail.setDescription(detail.getDescription());
        this.pointsDetailService.save(newDetail);
    }

}
