package com.tangguo.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangguo.common.exception.ServiceException;
import com.tangguo.common.utils.StringUtils;
import com.tangguo.domain.BbsGrade;
import com.tangguo.enums.IsInitialGrade;
import com.tangguo.mapper.BbsGradeMapper;
import com.tangguo.service.IBbsGradeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 用户等级Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-28
 */
@Service
public class BbsGradeServiceImpl extends ServiceImpl<BbsGradeMapper, BbsGrade> implements IBbsGradeService {

	@Resource
	private BbsGradeMapper bbsGradeMapper;


	/**
	 * 查询用户等级列表
	 *
	 * @param grade 用户等级
	 * @return 用户等级
	 */
	@Override
	public List<BbsGrade> selectBbsGradeList(BbsGrade grade) {
		LambdaQueryWrapper<BbsGrade> lqw = Wrappers.lambdaQuery();
		lqw.like(StringUtils.isNotBlank(grade.getName()), BbsGrade::getName, grade.getName());
		lqw.eq(StringUtils.isNotBlank(grade.getCode()), BbsGrade::getCode, grade.getCode());
		lqw.orderByAsc(BbsGrade::getSort);
		lqw.orderByDesc(BbsGrade::getCreateTime);
		return bbsGradeMapper.selectList(lqw);
	}


	/**
	 * 新增等级
	 *
	 * @param grade 等级
	 */
	@Override
	public void addGrade(BbsGrade grade) {
		long nameCount = this.count(
			Wrappers.lambdaQuery(BbsGrade.class).eq(BbsGrade::getName, grade.getName())
		);
		if (nameCount > 0) {
			throw new ServiceException("添加失败，当前等级名称已存在。");
		}

		Integer s1 = grade.getMinPoints();
		Integer e1 = grade.getMaxPoints();
		if (s1 < 0 || e1 < 0 || s1 >= e1) {
			throw new ServiceException("添加失败，当前等级积分范围错误。");
		}

		List<BbsGrade> dbGrades = this.list();
		for (BbsGrade g : dbGrades) {
			if (!(e1 < g.getMinPoints() || s1 > g.getMaxPoints())) {
				throw new ServiceException("添加失败，当前等级积分范围和等级【" + g.getName() + "】积分范围冲突。");
			}
		}

		BbsGrade addGrade = new BbsGrade();
		addGrade.setName(grade.getName());
		addGrade.setCode(IdUtil.fastSimpleUUID());
		addGrade.setSort(grade.getSort());
		addGrade.setMinPoints(grade.getMinPoints());
		addGrade.setMaxPoints(grade.getMaxPoints());
		this.save(addGrade);
	}


	/**
	 * 修改等级
	 *
	 * @param grade 等级
	 */
	@Override
	public void editGrade(BbsGrade grade) {
		BbsGrade dbGrade = this.getById(grade.getId());
		if (Objects.isNull(dbGrade)) {
			throw new ServiceException("修改失败，未查询到当前等级数据。");
		}

		if (!dbGrade.getName().equals(grade.getName())) {
			long nameCount = this.count(
				Wrappers.lambdaQuery(BbsGrade.class).eq(BbsGrade::getName, grade.getName())
			);
			if (nameCount > 0) {
				throw new ServiceException("修改失败，当前等级名称已存在。");
			}
		}

		Integer s1 = grade.getMinPoints();
		Integer e1 = grade.getMaxPoints();
		if (s1 < 0 || e1 < 0 || s1 >= e1) {
			throw new ServiceException("修改失败，当前等级积分范围错误。");
		}

		List<BbsGrade> dbGrades = this.list();
		for (BbsGrade g : dbGrades) {
			if (g.getId().equals(dbGrade.getId())) {
				continue;
			}
			if (!(e1 < g.getMinPoints() || s1 > g.getMaxPoints())) {
				throw new ServiceException("修改失败，当前等级积分范围和等级【" + g.getName() + "】积分范围冲突。");
			}
		}

		BbsGrade updGrade = new BbsGrade();
		updGrade.setId(dbGrade.getId());
		updGrade.setName(grade.getName());
		updGrade.setSort(grade.getSort());
		updGrade.setMinPoints(grade.getMinPoints());
		updGrade.setMaxPoints(grade.getMaxPoints());
		this.updateById(updGrade);
	}


	/**
	 * 修改等级初始值
	 *
	 * @param grade 等级
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public void editGradeInitial(BbsGrade grade) {
		BbsGrade dbGrade = this.getById(grade.getId());
		if (Objects.isNull(dbGrade)) {
			throw new ServiceException("修改失败，未查询到当前等级数据。");
		}

		Integer isInitial = grade.getIsInitial();
		if (!dbGrade.getIsInitial().equals(isInitial)) {
			if (IsInitialGrade.YES.getValue() == isInitial) {
				this.update(Wrappers.lambdaUpdate(BbsGrade.class)
					.set(BbsGrade::getIsInitial, IsInitialGrade.NO.getValue()));
			}
			this.update(Wrappers.lambdaUpdate(BbsGrade.class)
				.set(BbsGrade::getIsInitial, isInitial)
				.eq(BbsGrade::getId, dbGrade.getId()));
		}
	}


	/**
	 * 删除等级
	 *
	 * @param gradeId 等级Id
	 */
	@Override
	public void deleteGrade(Long gradeId) {
		this.removeById(gradeId);
	}


	/**
	 * 查询初始等级
	 *
	 * @return 等级
	 */
	@Override
	public BbsGrade getInitialGrade() {
		return this.getOne(
			Wrappers.lambdaQuery(BbsGrade.class)
				.eq(BbsGrade::getIsInitial, IsInitialGrade.YES.getValue())
				.orderByDesc(BbsGrade::getCreateTime)
				.last("LIMIT 1")
		);
	}


	/**
	 * 通过积分查询等级
	 *
	 * @param points 积分
	 * @return 等级
	 */
	@Override
	public BbsGrade getGradeByPoints(int points) {
		return this.getOne(
			Wrappers.lambdaQuery(BbsGrade.class)
				.le(BbsGrade::getMinPoints, points)
				.ge(BbsGrade::getMaxPoints, points)
		);
	}

}
