package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.GoodsCategoryDao;
import com.ym.mec.biz.dal.entity.GoodsCategory;
import com.ym.mec.biz.service.GoodsCategoryService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class GoodsCategoryServiceImpl extends BaseServiceImpl<Integer, GoodsCategory>  implements GoodsCategoryService {
	
	@Autowired
	private GoodsCategoryDao goodsCategoryDao;

	@Override
	public BaseDAO<Integer, GoodsCategory> getDAO() {
		return goodsCategoryDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(GoodsCategory goodsCategory) {
		goodsCategoryDao.insert(goodsCategory);
		List<GoodsCategory> goodsCategories = goodsCategory.getGoodsCategories();
		goodsCategories.forEach(e->{
			e.setParentId(goodsCategory.getId());
			goodsCategoryDao.insert(e);
		});
	}

	@Override
	public void upsetGoodsCategory(GoodsCategory goodsCategory) {
		Integer parentId = upset(goodsCategory, null);
		List<GoodsCategory> goodsCategories = goodsCategory.getGoodsCategories();
		goodsCategories.forEach(e->{
			upset(e, parentId);
		});
	}

	private Integer upset(GoodsCategory goodsCategory, Integer parentId){
		if(parentId != null){
			goodsCategory.setParentId(parentId);
		}
		if(goodsCategory.getId() != null){
			goodsCategory.setUpdateTime(new Date());
			goodsCategoryDao.update(goodsCategory);
		}else {
			goodsCategoryDao.insert(goodsCategory);
		}
		return goodsCategory.getId();
	}
}