package com.artfess.sysConfig.persistence.manager.impl;

import com.artfess.base.exception.BaseException;
import com.artfess.base.handler.MultiTenantHandler;
import com.artfess.base.handler.MultiTenantIgnoreResult;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.sysConfig.persistence.dao.SysCategoryDao;
import com.artfess.sysConfig.persistence.dao.SysTypeDao;
import com.artfess.sysConfig.persistence.manager.SysCategoryManager;
import com.artfess.sysConfig.persistence.model.SysCategory;
import com.artfess.sysConfig.persistence.model.SysType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sysCategoryManager")
public class SysCategoryManagerImpl extends BaseManagerImpl<SysCategoryDao, SysCategory> implements SysCategoryManager{
	@Resource
	SysTypeDao sysTypeDao;


	@Override
	public SysCategory get(Serializable id) {
		SysCategory category = null;
		try(MultiTenantIgnoreResult setThreadLocalIgnore = MultiTenantHandler.setThreadLocalIgnore()){
			category = super.get(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return category;
	}

	@Override
	public Boolean isKeyExist(String id, String groupKey) {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("id", id);
		params.put("groupKey", groupKey);
		int i = baseMapper.isKeyExist(params);
		return (i > 0);
	}

	@Override
	public SysCategory getByTypeKey(String typeKey) {
		return baseMapper.getByKey(typeKey);
	}

	@Override
	public void remove(Serializable entityId) {
		List<SysType> sysTypes = sysTypeDao.getByParentId(entityId.toString());
		if(BeanUtils.isNotEmpty(sysTypes)) {
			String val=sysTypes.get(0).getTypeGroupKey();
			SysCategory sysCategory=baseMapper.getByKey(val);
			if(BeanUtils.isNotEmpty(sysCategory)){
				val=sysCategory.getName();
			}
			throw new BaseException(String.format("分类标识[%s]下已经添加分类信息暂无法删除。", val));
		}

		super.remove(entityId);
	}

}
