package com.gyf.ec.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.bety.web.service.CommoditySpuService;
import com.gohuinuo.common.base.ServiceMybatis;
import com.gyf.ec.mapper.EcCatalogueMapper;
import com.gyf.ec.model.EcCatalogue;


@Service("ecCatalogueService")
@CacheConfig(cacheNames="ecCatalogue_cache")
public class EcCatalogueService extends ServiceMybatis<EcCatalogue> {
	
	@Resource
	private EcCatalogueMapper ecCatalogueMapper;
	@Resource
	private EcSkuService skuService;
	@Resource
	private CommoditySpuService spuService;
	/**
	 *æ°å¢oræ´æ°SysArea
	 */
	
	@CacheEvict(allEntries=true)
	public int saveEcCatalogue(EcCatalogue ecCatalogue){
		int count = 0;
		//æ°çparentIds
		ecCatalogue.setParentIds(ecCatalogue.getParentIds()+ecCatalogue.getParentId()+","); 
		if(null == ecCatalogue.getId()){
			count = this.insertSelective(ecCatalogue);
		}else{
			//getParentIds() å½åéæ©çç¶èç¹parentIds , getParentId()ç¶èç¹çid
			//åæ´æ°parentIdï¼æ­¤èç¹çparentIdsä»¥æ´æ
			count = this.updateByPrimaryKeySelective(ecCatalogue); 
			//ä¸ç§»å¨èç¹ä¸æ´æ°å­èç¹çpids
			if(!StringUtils.equals(ecCatalogue.getOldParentIds(), ecCatalogue.getParentIds())){
				ecCatalogueMapper.updateParentIds(ecCatalogue); //æ¹éæ´æ°å­èç¹çparentIds
			}
		}
		return count;
	}
	
	/**
	 * æ¥è¯¢å¨é¨çåºå
	* @return
	 */
	@Cacheable(key="'ecCatalogue_all'")
	public List<EcCatalogue> findAllEcCatalogue(){
		return this.select(new EcCatalogue());
	}
	
	/**
	 * ææ¡£åç±»ç®¡çåé¡µæ¾ç¤ºç­éæ¥è¯
	 * 
	 * @param params
	 *            {"name":"ææ¡£åç±»åå­","id":"ææ¡£åç±»id"}
	 * @return
	 */
	public List<EcCatalogue> findEcCatalogueList(Map<String, Object> params){
		List<EcCatalogue> list = ecCatalogueMapper.findEcCatalogueList(params);
		return list;
	}
	
	/**
	 * æ ¹æ®ç¶idå é¤èªèº«å·²ç»ææå­èç¹
	* @param id
	* @return
	 */
	@CacheEvict(allEntries=true)	
	public int deleteEcCatalogueByRootId(Long id){
		//int count = this.beforeDeleteTreeStructure(id,"areaId", SysOffice.class,SysArea.class);
		//int count2 = this.beforeDeleteTreeStructure(id, "areaId", EcSuppliers.class,SysArea.class);
		int count1 = skuService.querySkuByCatalogue(id);
		int count2 = spuService.findCountByType(id);
		if(count1>0||count2>0){
			return -1;
		}
		int num = -1;
		//if(count != -1 && count2 != -1) {
			num = ecCatalogueMapper.deleteEcCatalogueByRootId(id);
		//}
	
		return num;
	}
	public EcCatalogue findOneByName(String name){
		return ecCatalogueMapper.findOneByName(name);
	}
	


}
