package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.SysGroup;
import cn.wise.sc.cement.business.entity.SysRole;
import cn.wise.sc.cement.business.mapper.SysGroupMapper;
import cn.wise.sc.cement.business.mapper.SysRoleMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.vo.GroupVo;
import cn.wise.sc.cement.business.service.ISysGroupService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-21
 */
@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupMapper, SysGroup> implements ISysGroupService {

	@Resource
	private SysGroupMapper groupMapper;

	/**
	 * 获取分页
	 *
	 * @param pageQuery
	 * @return
	 */
	@Override
	public BaseResponse<IPage<GroupVo>> getPage(PageQuery pageQuery) {
		Page<GroupVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<GroupVo> pages = groupMapper.getPage(page);
		return BaseResponse.okData(pages);
	}

	/**
	 * 新增工作组
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysGroup> create(SysGroup query) {
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("工作组名称不能为空!");
		}
		QueryWrapper<SysGroup> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = groupMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		query.setCreateTime(LocalDateTime.now());
		query.setStatus(1);
		groupMapper.insert(query);
		return BaseResponse.okData(query);
	}

	/**
	 * 修改工作组
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysGroup> update(SysGroup query) {

		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("工作组名称不能为空!");
		}
		QueryWrapper<SysGroup> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		qw.ne("id", query.getId());
		int count = groupMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		groupMapper.updateById(query);
		return BaseResponse.okData(query);
	}

}
