package com.pj.project.tb_agreement;

import java.util.Comparator;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.pj.utils.sg.*;

/**
 * Service: tb_agreement -- 隐私政策管理
 * @author qzy 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbAgreementService extends ServiceImpl<TbAgreementMapper, TbAgreement> implements IService<TbAgreement>{

	/** 底层 Mapper 对象 */
	@Autowired
	TbAgreementMapper tbAgreementMapper;

	/** 增 */
	void add(TbAgreement t){
		//判断
		if(t == null || t.getTextType() > 2 || t.getTextType() < 0)
			throw new RuntimeException("请输入正确的类型!");
		//获取同类型最新的那一条数据
		LambdaQueryWrapper<TbAgreement> queryWrapper = new LambdaQueryWrapper<>();
		//匹配当前类型
		queryWrapper.eq(TbAgreement::getTextType,t.getTextType());
		//降序排列
		queryWrapper.orderByDesc(TbAgreement::getVersion);
		TbAgreement tbAgreement = tbAgreementMapper.selectList(queryWrapper).get(0);
		if(tbAgreement == null)throw new RuntimeException("服务器繁忙,请稍后重试~");
		//获取最新对象的版本号
		Integer version = tbAgreement.getVersion();
		//保存到对象中
		t.setVersion(version + 1);
		save(t);
	}

	/** 删 */
	void delete(Long id){
		removeById(id);
	}

	/** 改 */
	void update(TbAgreement t){
		updateById(t);

	}

	/** 查 */
	TbAgreement getById(Integer id){
		return super.getById(id);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */  
	List<TbAgreement> getList(SoMap so) { 
		return tbAgreementMapper.getList(so);	
	}

	/**
	 * 根据类型,查询单个协议,获取其最新的一条数据
	 * 类型[1=隐私政策管理,2=服务协议]
	 * @return
	 */
	TbAgreement getMaxVersion(Integer textType){
		//构建查询条件
		LambdaQueryWrapper<TbAgreement> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TbAgreement::getTextType,textType);
		List<TbAgreement> tbAgreements = tbAgreementMapper.selectList(queryWrapper);
		//过滤版本号最大的一条数据
		TbAgreement tbAgreement = tbAgreements.stream().max(Comparator.comparing(TbAgreement::getVersion)).orElse(null);
		return tbAgreement;
	}

}
