package org.fouram.service;

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

import org.fouram.core.base.service.BaseService;
import org.fouram.core.plugin.weixin.cp.util.WXCpUserUtil;
import org.fouram.entity.WxDepart;
import org.fouram.entity.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpUser;

@Service
public class WxUserService extends BaseService {

	@Autowired
	private WxDepartService wxDepartService;

	private Map<Long, List<WxDepart>> userDepartMap = Maps.newHashMap();

	public void saveUsers() throws Exception {
		update("WxUserMapper.updateAllDelete", null);
		
		List<WxCpUser> users = WXCpUserUtil.listAllUser();
		List<WxDepart> departs = null;
		WxUser wxUser = null;
		WxUser dbUser = null;
		String userId = null;
		for (WxCpUser user : users) {
			userId = user.getUserId();
			wxUser = WxUser.builder().userId(userId).name(user.getName()).departId(user.getDepartIds()[0]).build();
			departs = getUserDepart(wxUser.getDepartId());
			if (departs.size() > 0) {
				wxUser.setFirstDepartName(departs.get(0).getName());
				wxUser.setFirstDepartId(departs.get(0).getId());
			}
			if (departs.size() > 1) {
				wxUser.setSecondDepartName(departs.get(1).getName());
				wxUser.setSecondDepartId(departs.get(1).getId());
			}
			dbUser = selectById(userId);
			if (dbUser == null) {
				save("WxUserMapper.save", wxUser);
			} else {
				wxUser.setUserId(dbUser.getUserId());
				update("WxUserMapper.update", wxUser);
			}
		}
	}

	public WxUser selectById(String userId) throws Exception {
		return (WxUser) findObject("WxUserMapper.selectById", userId);
	}

	private List<WxDepart> getUserDepart(Long departId) throws Exception {
		if (!userDepartMap.containsKey(departId)) {
			userDepartMap.put(departId, wxDepartService.findParentList(departId));
		}
		return userDepartMap.get(departId);
	}
	
	@SuppressWarnings("unchecked")
	public List<String> selectAllUserIds() throws Exception {
		return (List<String>) findList("WxUserMapper.selectAllUserIds", null);
	}
	
	public static void main(String[] args) {
		try {
			System.out.println(WXCpUserUtil.listAllUser().size());
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}
}
