package org.fouram.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.entity.SapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.Maps;

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

@Service
public class SapPersonalService extends BaseService {

	@Autowired
	private RequestService requestService;

	public List<SapUser> setGender(List<SapUser> sapUsers) {
		String personIds = "";
		Map<String, List<SapUser>> map = Maps.newHashMap();
		for (SapUser sapUser : sapUsers) {
			personIds += "'" + sapUser.getPersonId() + "',";
			if (null == map.get(sapUser.getPersonId())) {
				map.put(sapUser.getPersonId(), new ArrayList<>());
			}
			map.get(sapUser.getPersonId()).add(sapUser);
		}
		String url = "https://api15.sapsf.cn/odata/v2/PerPersonal?$filter=personIdExternal in " + personIds
				+ "&$format=json";
		JsonNode node = requestService.getForObject(url, getHttpHeaders());
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = userNode.get("personIdExternal").asText().trim();
				String gender = userNode.get("gender").asText().trim();
				List<SapUser> sapUserList = map.get(personId);
				sapUserList.forEach(row -> {
					row.setGender("M".equals(gender) ? Gender.MALE.getGenderName() : Gender.FEMALE.getGenderName());
				});
			}
		}
		return sapUsers;
	}
}
