package com.iotechn.unimall.admin.api.dict;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.sys.dict.SysDictType;
import com.iotechn.unimall.data.mapper.sys.dict.SysDictTypeMapper;
import com.iotechn.unimall.data.model.Page;

/**
 * 
 * @author dyl
 *
 */
@Service
public class DictTypeServiceImpl implements DictTypeService {

	@Autowired
	private SysDictTypeMapper typeMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean add(SysDictType sysDictType) throws ServiceException {
		Long dictId;
		if (sysDictType.getDictId() == null)
			dictId = -1L;
		else
			dictId = sysDictType.getDictId();
		SysDictType dictType = typeMapper.checkDictTypeUnique(sysDictType);
		if (dictType != null && dictType.getDictId().longValue() != dictId.longValue()) {
			throw new AdminServiceException(ExceptionDefinition.DICT_TYPE_HAS_EXISTED);
		}
		return typeMapper.insert(sysDictType) > 0;
	}

	@Override
	public Page<SysDictType> list(String dictName, String dictType, Integer page, Integer limit)
			throws ServiceException {
		Wrapper<SysDictType> wrapper = new EntityWrapper<SysDictType>();
		if (!StringUtils.isEmpty(dictName)) {
			wrapper.like("dict_name", dictName);
		}
		if (!StringUtils.isEmpty(dictType)) {
			wrapper.eq("dict_type", dictType);
		}
		List<SysDictType> SysDictTypeS = typeMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
		Integer count = typeMapper.selectCount(wrapper);
		return new Page<SysDictType>(SysDictTypeS, page, limit, count);
	}

	@Override
	public Boolean delete(String dictIds) throws ServiceException {
		String[] ids=dictIds.split(",");
		Wrapper<SysDictType> wrapper = new EntityWrapper<SysDictType>();
		wrapper.in("dict_id", ids);
		return typeMapper.delete(wrapper) > 0;
	}

	@Override
	public Boolean update(SysDictType dictType) throws ServiceException {

		return typeMapper.updateById(dictType) > 0;
	}

	@Override
	public SysDictType get(Long dictId) throws ServiceException {
		return typeMapper.selectById(dictId);
	}

	@Override
	public List<SysDictType> optionselect() throws ServiceException {
		return typeMapper.selectDictTypeAll();
	}


}
