package com.buy507.mall.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.buy507.mall.dao.PmsProductCategoryAttributeRelationDao;
import com.buy507.mall.dto.PmsProductCategoryOptions;
import com.buy507.mall.dto.PmsProductCategoryParam;
import com.buy507.mall.mapper.PmsProductCategoryAttributeRelationMapper;
import com.buy507.mall.mapper.PmsProductCategoryMapper;
import com.buy507.mall.mapper.PmsProductMapper;
import com.buy507.mall.model.PmsProduct;
import com.buy507.mall.model.PmsProductCategory;
import com.buy507.mall.model.PmsProductCategoryAttributeRelation;
import com.buy507.mall.model.PmsProductCategoryAttributeRelationExample;
import com.buy507.mall.model.PmsProductCategoryExample;
import com.buy507.mall.model.PmsProductExample;
import com.buy507.mall.service.PmsProductCategoryService;
import com.github.pagehelper.PageHelper;

/**
 * PmsProductCategoryService实现类
 */
@Service
public class PmsProductCategoryServiceImpl implements PmsProductCategoryService {
	
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    
    @Autowired
    private PmsProductMapper productMapper;
    
    @Autowired
    private PmsProductCategoryAttributeRelationDao productCategoryAttributeRelationDao;
    
    @Autowired
    private PmsProductCategoryAttributeRelationMapper productCategoryAttributeRelationMapper;
    
    @Override
    public int create(PmsProductCategoryParam pmsProductCategoryParam) {
        PmsProductCategory productCategory = new PmsProductCategory();
        productCategory.setProductCount(0);
        BeanUtils.copyProperties(pmsProductCategoryParam, productCategory);
        //没有父分类时为一级分类
        setCategoryLevel(productCategory);
        int count = productCategoryMapper.insertSelective(productCategory);
        //创建筛选属性关联
        List<Long> productAttributeIdList = pmsProductCategoryParam.getProductAttributeIdList();
        if(!CollectionUtils.isEmpty(productAttributeIdList)){
            insertRelationList(productCategory.getId(), productAttributeIdList);
        }
        return count;
    }

    /**
     * 批量插入商品分类与筛选属性关系表
     * @param productCategoryId 商品分类id
     * @param productAttributeIdList 相关商品筛选属性id集合
     */
    private void insertRelationList(Long productCategoryId, List<Long> productAttributeIdList) {
        List<PmsProductCategoryAttributeRelation> relationList = new ArrayList<>();
        for (Long productAttrId : productAttributeIdList) {
            PmsProductCategoryAttributeRelation relation = new PmsProductCategoryAttributeRelation();
            relation.setProductAttributeId(productAttrId);
            relation.setProductCategoryId(productCategoryId);
            relationList.add(relation);
        }
        productCategoryAttributeRelationDao.insertList(relationList);
    }

    @Override
    public int update(Long id, PmsProductCategoryParam pmsProductCategoryParam) {
        PmsProductCategory productCategory = new PmsProductCategory();
        productCategory.setId(id);
        BeanUtils.copyProperties(pmsProductCategoryParam, productCategory);
        setCategoryLevel(productCategory);
        //更新商品分类时要更新商品中的名称
        PmsProduct product = new PmsProduct();
        product.setProductCategoryName(productCategory.getName());
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andProductCategoryIdEqualTo(id);
        productMapper.updateByExampleSelective(product,example);
        //同时更新筛选属性的信息
        if(!CollectionUtils.isEmpty(pmsProductCategoryParam.getProductAttributeIdList())){
            PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample();
            relationExample.createCriteria().andProductCategoryIdEqualTo(id);
            productCategoryAttributeRelationMapper.deleteByExample(relationExample);
            insertRelationList(id,pmsProductCategoryParam.getProductAttributeIdList());
        }else{
            PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample();
            relationExample.createCriteria().andProductCategoryIdEqualTo(id);
            productCategoryAttributeRelationMapper.deleteByExample(relationExample);
        }
        return productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    @Override
    public List<PmsProductCategory> getList(Long parentId, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.setOrderByClause("sort desc");
        example.createCriteria().andParentIdEqualTo(parentId);
        return productCategoryMapper.selectByExample(example);
    }

    @Override
    public int delete(Long id) {
        return productCategoryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PmsProductCategory getItem(Long id) {
        return productCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateNavStatus(List<Long> ids, Integer navStatus) {
        PmsProductCategory productCategory = new PmsProductCategory();
        productCategory.setNavStatus(navStatus);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andIdIn(ids);
        return productCategoryMapper.updateByExampleSelective(productCategory, example);
    }

    @Override
    public int updateShowStatus(List<Long> ids, Integer showStatus) {
        PmsProductCategory productCategory = new PmsProductCategory();
        productCategory.setShowStatus(showStatus);
        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andIdIn(ids);
        return productCategoryMapper.updateByExampleSelective(productCategory, example);
    }

    @Override
    public List<PmsProductCategoryOptions> listProductCategoryOptions() {
    	List<PmsProductCategoryOptions> options = new ArrayList<>();
    	PmsProductCategoryExample example = new PmsProductCategoryExample();
    	List<PmsProductCategory> productCategories = productCategoryMapper.selectByExample(example);
    	for(PmsProductCategory category : productCategories) {
    		//我们这里最大的根节点ID是0，所以找出所有parent id为0的节点，然后调用我们的递归算法
    		if(category.getParentId().equals(0L)){
    			options.add(recursionCategory(category, productCategories));
    		}
    	}
    	
        return options;
    }
    
    private PmsProductCategoryOptions recursionCategory(PmsProductCategory category, List<PmsProductCategory> list) {
    	List<PmsProductCategoryOptions> childList = new ArrayList<>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
    	PmsProductCategoryOptions node = new PmsProductCategoryOptions();
    	node.setValue(category.getId());
    	node.setLabel(category.getName());
    	
     	for (PmsProductCategory childCategory : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
    	    if(childCategory.getParentId().equals(category.getId())){
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
    	    	childList.add(recursionCategory(childCategory, list));
    	    }
    	}
     	
        // 当遍历完成，返回调用的节点
     	if(!childList.isEmpty()) {
     		node.setChildren(childList);
     	}
    	return node;
    }

    /**
     * 根据分类的parentId设置分类的level
     */
    private void setCategoryLevel(PmsProductCategory productCategory) {
        //没有父分类时为一级分类
        if (productCategory.getParentId() == 0) {
            productCategory.setLevel(0);
        } else {
            //有父分类时选择根据父分类level设置
            PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
            if (parentCategory != null) {
                productCategory.setLevel(parentCategory.getLevel() + 1);
            } else {
                productCategory.setLevel(0);
            }
        }
    }
}
