package com.buy507.mall.portal.component;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.buy507.mall.common.util.Constants;
import com.buy507.mall.mapper.DmsDistributionDictionaryMapper;
import com.buy507.mall.mapper.UmsAreaMapper;
import com.buy507.mall.model.DmsDistributionDictionary;
import com.buy507.mall.model.UmsArea;
import com.buy507.mall.portal.domain.AreaOptions;
import com.buy507.mall.portal.service.RedisService;
import com.google.gson.Gson;

/**
 * 缓存初始化
 * @author yeyun
 *
 */
@Component
public class CacheInitializtion implements CommandLineRunner {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CacheInitializtion.class);
	
	@Autowired
	private DmsDistributionDictionaryMapper distributionDictionaryMapper;
	
	@Autowired
    private UmsAreaMapper areaMapper;
	
	@Autowired
    private RedisService redisService;

	@Override
	public void run(String... args) throws Exception {
		LOGGER.debug("Cache initialize start");
		Gson gson = new Gson();
		List<DmsDistributionDictionary> dictionariesList = distributionDictionaryMapper.selectAll();
		LOGGER.debug("distribution dictionary init {}", dictionariesList.size());
		redisService.set(Constants.DISTRIBUTION_DICTIONARY, gson.toJson(dictionariesList));
		
		List<UmsArea> areaList = areaMapper.selectAll();
		List<AreaOptions> optionList = new ArrayList<>();
		for(UmsArea area : areaList) {
    		//我们这里最大的根节点ID是0，所以找出所有parent id为-1的节点，然后调用我们的递归算法
    		if(area.getParentId().equals(-1)){
    			optionList.add(recursionArea(area, areaList));
    		}
    	}
		redisService.set(Constants.AREA_CODE, gson.toJson(optionList));
		
		LOGGER.debug("Cache initialize end");
	}
	
	private AreaOptions recursionArea(UmsArea area, List<UmsArea> list) {
    	List<AreaOptions> childList = new ArrayList<>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
    	AreaOptions node = new AreaOptions();
    	node.setId(area.getId());
    	node.setName(area.getAreaName());
    	node.setLevel(area.getLevel());
    	
    	if(area.getParentId().equals(-1)) {
    		node.setPid(0);
    	} else {
    		node.setPid(area.getParentId());
    	}
     	for (UmsArea childArea : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
    	    if(childArea.getParentId().equals(area.getId())){
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
    	    	childList.add(recursionArea(childArea, list));
    	    }
    	}
     	
        // 当遍历完成，返回调用的节点
     	if(!childList.isEmpty()) {
     		node.setChildren(childList);
     	} else {
     		node.setChildren(null);
     	}
    	return node;
    }

}
