package org.fouram.service;

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

import org.apache.commons.lang3.StringUtils;
import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.core.util.UUIDUtil;
import org.fouram.entity.SapOrg;
import org.fouram.entity.SapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

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

@Service
public class SapOrgService extends BaseService {

	@Autowired
	private RequestService requestService;

	// FOCompany->FOBusinessUnit->FODivision->FODepartment->cust_orgunit4/cust_org4
	private Map<String, String> getOrgMap(HttpHeaders headers, String entityName) throws Exception {
		String url = "https://api15.sapsf.cn/odata/v2/" + entityName + "?$format=json";
		JsonNode node = requestService.getForObject(url, headers);
		Map<String, String> empInfo = Maps.newHashMap();
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String externalCode = userNode.get("externalCode").asText().trim();
				String externalName = null;
				if (userNode.get("externalName") != null) {
					externalName = userNode.get("externalName").asText().trim();
				} else if (userNode.get("name") != null) {
					externalName = userNode.get("name").asText().trim();
				} else {
					externalName = userNode.get("externalName_zh_CN").asText().trim();
				}
				empInfo.put(externalCode, externalName);
				saveOrUpdateSapOrg(externalCode, externalName, entityName);
			}
		}
		return empInfo;
	}

	public SapOrg selectOne(String sapCode, String orgLevel) throws Exception {
		SapOrg sapOrg = SapOrg.builder().orgLevel(orgLevel).sapCode(sapCode).build();
		return (SapOrg) findObject("SapOrgMapper.selectOne", sapOrg);
	}

	private void saveOrUpdateSapOrg(String sapCode, String sapName, String orgLevel) throws Exception {
		SapOrg sapOrg = selectOne(sapCode, orgLevel);
		if (sapOrg != null) {
			sapOrg.setSapName(sapName);
			update("SapOrgMapper.updateSapName", sapOrg);
		} else {
			sapOrg = SapOrg.builder().id(UUIDUtil.get32UUID()).sapCode(sapCode).sapName(sapName).orgLevel(orgLevel)
					.build();
			save("SapOrgMapper.saveOne", sapOrg);
		}
	}

	public List<SapUser> setOrg(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		Map<String, String> businessUnitMap = getOrgMap(headers, "FOBusinessUnit");
		Map<String, String> divisionMap = getOrgMap(headers, "FODivision");
		Map<String, String> departmentMap = getOrgMap(headers, "FODepartment");
		Map<String, String> orgunit4Map = getOrgMap(headers, "cust_org4");// cust_orgunit4/cust_org4

		// 根据机构名称变化更新微信部门名称

		String userIds = "";
		Map<String, SapUser> map = Maps.newHashMap();
		for (SapUser sapUser : sapUsers) {
			userIds += "'" + sapUser.getUserId() + "',";
			map.put(sapUser.getUserId(), sapUser);
		}
		String empUrl = "https://api15.sapsf.cn/odata/v2/EmpJob?$filter=userId in " + userIds + "&$format=json";
		JsonNode node = requestService.getForObject(empUrl, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = userNode.get("userId").asText().trim();
				SapUser sapUser = map.get(userId);
				String businessUnitCode = userNode.get("businessUnit").asText().trim();
				String divisionCode = userNode.get("division").asText().trim();
				String departmentCode = userNode.get("department").asText().trim();
				String orgunit4Code = userNode.get("customString19").asText().trim();
				if (StringUtils.isNotBlank(businessUnitCode)) {
					sapUser.setFirstOrg(businessUnitMap.get(businessUnitCode));
				}
				if (StringUtils.isNotBlank(divisionCode)) {
					sapUser.setSecondOrg(divisionMap.get(divisionCode));
				}
				if (StringUtils.isNotBlank(departmentCode)) {
					sapUser.setThirdOrg(departmentMap.get(departmentCode));
				}
				if (StringUtils.isNotBlank(orgunit4Code)) {
					sapUser.setFourthOrg(orgunit4Map.get(orgunit4Code));
				}
			}
		}
		return sapUsers;
	}
}
