package org.fouram.service;

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

import org.fouram.constants.WebConstants;
import org.fouram.core.base.service.BaseService;
import org.fouram.core.plugin.weixin.cp.util.WXCpDepartUtil;
import org.fouram.core.util.TreeUtil;
import org.fouram.entity.WxDepart;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import me.chanjar.weixin.cp.bean.WxCpDepart;

@Service
public class WxDepartService extends BaseService {

	public void saveDeparts() throws Exception {
		List<WxCpDepart> departs = WXCpDepartUtil.getAllChildDeparts(WebConstants.TOP_DEPART);
		for (WxCpDepart depart : departs) {
			if(selectById(depart.getId()) == null) {
				save("WxDepartMapper.save", depart);
			}
		}
	}
	
	public List<WxDepart> findParentList(Long id) throws Exception {
		List<WxDepart> wxDeparts = new ArrayList<>();
		Collections.reverse(findParent(wxDeparts, id));
		return wxDeparts;
	}
	
	private List<WxDepart> findParent(List<WxDepart> wxDeparts, Long id) throws Exception {
		WxDepart wxDepart = selectById(id);
		if(wxDepart != null){
			wxDeparts.add(wxDepart);
			if (!WebConstants.TOP_DEPART.equals(wxDepart.getParentId())) {
				findParent(wxDeparts, wxDepart.getParentId());
			}
		}
		return wxDeparts;
	}
	
	public WxDepart selectById(Long id) throws Exception {
		return (WxDepart) findObject("WxDepartMapper.selectById", id);
	}
	
	@SuppressWarnings("unchecked")
	public List<WxDepart> selectChildrenByParentId(Long id) throws Exception {
		return (List<WxDepart>) findList("WxDepartMapper.selectChildrenByParentId", id);
	}

	public Object findDepartJSON() throws Exception {
		List<WxDepart> result = Lists.newArrayList();
		List<WxDepart> departs = selectChildrenByParentId(WebConstants.TOP_DEPART);
		departs.forEach(depart -> result.add(depart));
		for(WxDepart depart : departs) {
			selectChildrenByParentId(depart.getId()).forEach(dept -> result.add(dept));
		}
		return TreeUtil.buildTreeSimple(result);
	}
}
