package org.fouram.service;

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

import org.fouram.constants.WebConstants;
import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.core.util.JsonNodeUtil;
import org.fouram.core.util.Tools;
import org.fouram.entity.SapCertificates;
import org.fouram.entity.SapCourses;
import org.fouram.entity.SapEducation;
import org.fouram.entity.SapEmpEmployment;
import org.fouram.entity.SapEmpJob;
import org.fouram.entity.SapEmpJobRelationships;
import org.fouram.entity.SapInsideWorkExperience;
import org.fouram.entity.SapLanguages;
import org.fouram.entity.SapOutsideWorkExperience;
import org.fouram.entity.SapOverallPerformance;
import org.fouram.entity.SapPerEmail;
import org.fouram.entity.SapPerGlobalInfoCHN;
import org.fouram.entity.SapPerNationalId;
import org.fouram.entity.SapPerPerson;
import org.fouram.entity.SapPerPersonal;
import org.fouram.entity.SapPerPhone;
import org.fouram.entity.SapPerSocialAccount;
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;

@Service
public class SapReportService extends BaseService {

	@Autowired
	private RequestService requestService;

	@SuppressWarnings("unchecked")
	public List<SapUser> selectReportUserList() throws Exception {
		return (List<SapUser>) findList("SapUserMapper.selectReportUserList", null);
	}

	public void saveSapAllReportData() throws Exception {
		HttpHeaders headers = getHttpHeaders();
		List<SapUser> sapUsers = selectReportUserList();
		for (SapUser sapUser : sapUsers) {
			if (!WebConstants.NAME_MAP.containsKey(sapUser.getUserId())) {
				WebConstants.NAME_MAP.put(sapUser.getUserId(), sapUser.getName());
			}
		}
		// 基本信息 PerPerson
		this.saveSapPerPerson(headers, sapUsers);
		// 基本信息 PerPerson,PerPersonal
		this.saveSapPerPersonal(headers, sapUsers);
		// 个人信息 PerGlobalInfoCHN
		this.saveSapPerGlobalInfoCHN(headers, sapUsers);
		// 国家身份信息 PerNationalId
		this.saveSapPerNationalId(headers, sapUsers);
		// 邮件信息 PerEmail
		this.saveSapPerEmail(headers, sapUsers);
		// 通讯信息 PerPhone
		this.saveSapPerPhone(headers, sapUsers);
		// 社交账号 PerSocialAccount
		this.saveSapPerSocialAccount(headers, sapUsers);
		// 雇佣详细信息 EmpEmployment
		this.saveSapEmpEmployment(headers, sapUsers);
		// 组织以及职位信息 EmpJob
		this.saveSapEmpJob(headers, sapUsers);
		// 工作关系 EmpJobRelationships
		this.saveSapEmpJobRelationships(headers, sapUsers);
		// 先前工作经历 Background_OutsideWorkExperience
		this.saveSapOutsideWorkExperience(headers, sapUsers);
		// 公司内工作经历 Background_InsideWorkExperience
		this.saveSapInsideWorkExperience(headers, sapUsers);
		// 培训经历 Background_Courses
		this.saveSapCourses(headers, sapUsers);
		// 学历教育 Background_Education
		this.saveSapEducation(headers, sapUsers);
		// 证书 Background_Certificates
		this.saveSapCertificates(headers, sapUsers);
		// 语言能力 Background_Languages
		this.saveSapLanguages(headers, sapUsers);
		// 绩效历史 TrendData_SysOverallPerformance
		this.saveSapOverallPerformance(headers, sapUsers);
	}

	// 基本信息 PerPerson
	public void saveSapPerPerson(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerPerson", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerPerson?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");// 员工号
				String dateOfBirth = JsonNodeUtil.getValue(userNode, "dateOfBirth");// 出生日期
				String placeOfBirth = JsonNodeUtil.getValue(userNode, "placeOfBirth");// 籍贯
				String education = getLabelValue(JsonNodeUtil.getValue(userNode, "customString1"));// 最高学历
				SapPerPerson entity = SapPerPerson.builder().personId(personId).dateOfBirth(dateOfBirth)
						.placeOfBirth(placeOfBirth).education(education).build();
				save("SapReportMapper.saveSapPerPerson", entity);
			}
		}
	}

// 基本信息	PerPerson,PerPersonal
	public void saveSapPerPersonal(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerPersonal", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerPersonal?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String firstName = JsonNodeUtil.getValue(userNode, "firstName");// 名字
				String lastName = JsonNodeUtil.getValue(userNode, "lastName");// 姓氏
				String displayName = JsonNodeUtil.getValue(userNode, "displayName");// 英文全名
				String formalName = JsonNodeUtil.getValue(userNode, "formalName");// 全名
				String nationality = JsonNodeUtil.getValue(userNode, "nationality");// 国籍
				String gender = JsonNodeUtil.getValue(userNode, "gender");// 性别
				String maritalStatus = getLabelValue(JsonNodeUtil.getValue(userNode, "maritalStatus"));// 婚姻状况
				String firstNameAlt1 = JsonNodeUtil.getValue(userNode, "firstNameAlt1");// 英文名
				String lastNameAlt1 = JsonNodeUtil.getValue(userNode, "lastNameAlt1");// 英文姓
				String firstNameAlt2 = JsonNodeUtil.getValue(userNode, "firstNameAlt2");// 拼音名
				String lastNameAlt2 = JsonNodeUtil.getValue(userNode, "lastNameAlt2");// 拼音姓
				SapPerPersonal entity = SapPerPersonal.builder().personId(personId).firstName(firstName)
						.lastName(lastName).displayName(displayName).formalName(formalName).nationality(nationality)
						.gender(gender).maritalStatus(maritalStatus).firstNameAlt1(firstNameAlt1)
						.lastNameAlt1(lastNameAlt1).firstNameAlt2(firstNameAlt2).lastNameAlt2(lastNameAlt2).build();
				save("SapReportMapper.saveSapPerPersonal", entity);
			}
		}
	}

// 个人信息	PerGlobalInfoCHN
	public void saveSapPerGlobalInfoCHN(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerGlobalInfoCHN", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerGlobalInfoCHN?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String householdRegistrationType = getLabelValue(JsonNodeUtil.getValue(userNode, "genericNumber1"));// 户口类型
				String nation = getLabelValue(JsonNodeUtil.getValue(userNode, "genericNumber4"));// 民族
				String politicalOutlook = getLabelValue(JsonNodeUtil.getValue(userNode, "customString6"));// 政治面貌
				String orgRelationshipLocation = JsonNodeUtil.getValue(userNode, "customString1");// 组织关系所在地
				String socialSecurityLocation = getLabelValue(JsonNodeUtil.getValue(userNode, "customString2"));// 社保所在地
				SapPerGlobalInfoCHN entity = SapPerGlobalInfoCHN.builder().personId(personId)
						.householdRegistrationType(householdRegistrationType).nation(nation)
						.politicalOutlook(politicalOutlook).orgRelationshipLocation(orgRelationshipLocation)
						.socialSecurityLocation(socialSecurityLocation).build();
				save("SapReportMapper.saveSapPerGlobalInfoCHN", entity);
			}
		}
	}

// 国家身份信息	PerNationalId
	public void saveSapPerNationalId(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerNationalId", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerNationalId?$filter=personIdExternal in %s&$format=json&$expand=countryNav";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String countryName = JsonNodeUtil.getValue(userNode, "countryNav", "territoryName");// 国家/地区
				String cardType = JsonNodeUtil.getValue(userNode, "cardType");// 国民身份证类型
				String nationalId = JsonNodeUtil.getValue(userNode, "nationalId");// 国民身份证
				SapPerNationalId entity = SapPerNationalId.builder().personId(personId).countryName(countryName)
						.cardType(cardType).nationalId(nationalId).build();
				save("SapReportMapper.saveSapPerNationalId", entity);
			}
		}
	}

// 邮件信息	PerEmail
	public void saveSapPerEmail(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerEmail", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerEmail?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String emailType = getLabelValue(JsonNodeUtil.getValue(userNode, "emailType"));// 电子邮件类型
				String emailAddress = JsonNodeUtil.getValue(userNode, "emailAddress");// 电子邮件地址
				String isPrimary = JsonNodeUtil.getValue(userNode, "isPrimary");// 主要
				SapPerEmail entity = SapPerEmail.builder().personId(personId).emailType(emailType)
						.emailAddress(emailAddress).isPrimary(isPrimary).build();
				save("SapReportMapper.saveSapPerEmail", entity);
			}
		}

	}

// 通讯信息	PerPhone
	public void saveSapPerPhone(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerPhone", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerPhone?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String phoneType = getLabelValue(JsonNodeUtil.getValue(userNode, "phoneType"));// 电话类型
				String phoneNumber = JsonNodeUtil.getValue(userNode, "phoneNumber");// 电话号码
				String isPrimary = JsonNodeUtil.getValue(userNode, "isPrimary");// 主要
				SapPerPhone entity = SapPerPhone.builder().personId(personId).phoneNumber(phoneNumber)
						.phoneType(phoneType).isPrimary(isPrimary).build();
				save("SapReportMapper.saveSapPerPhone", entity);
			}
		}
	}

// 社交账号	PerSocialAccount
	public void saveSapPerSocialAccount(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapPerSocialAccount", null);

		String url = "https://api15.sapsf.cn/odata/v2/PerSocialAccount?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String domain = getLabelValue(JsonNodeUtil.getValue(userNode, "domain"));// 微信
				String imId = JsonNodeUtil.getValue(userNode, "imId");// 微信号
				SapPerSocialAccount entity = SapPerSocialAccount.builder().personId(personId).domain(domain).imId(imId)
						.build();
				save("SapReportMapper.saveSapPerSocialAccount", entity);
			}
		}
	}

// 雇佣详细信息	EmpEmployment
	public void saveSapEmpEmployment(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapEmpEmployment", null);

		String url = "https://api15.sapsf.cn/odata/v2/EmpEmployment?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, getPersonIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String personId = JsonNodeUtil.getValue(userNode, "personIdExternal");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate");// 最近一次入职日期
				String firstDateWorked = JsonNodeUtil.getValue(userNode, "firstDateWorked");// 首次工作日期
				String originalStartDate = JsonNodeUtil.getValue(userNode, "originalStartDate");// 进入集团日期
				String seniorityDate = JsonNodeUtil.getValue(userNode, "seniorityDate");// 司龄起始日期
				String socialServiceAge = JsonNodeUtil.getValue(userNode, "customDouble1");// 社会工龄
				String seniority = JsonNodeUtil.getValue(userNode, "customDouble2");// 司龄（最近入职）
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 离职日期
				String okToRehire = JsonNodeUtil.getValue(userNode, "okToRehire");// 可以再雇佣
				String salaryEndDate = JsonNodeUtil.getValue(userNode, "salaryEndDate");// 最后结薪日期
				String benefitsEndDate = JsonNodeUtil.getValue(userNode, "benefitsEndDate");// 福利结算日期
				String leavingReason = getLabelValue(JsonNodeUtil.getValue(userNode, "customString16"));// 离职详细原因
				SapEmpEmployment entity = SapEmpEmployment.builder().personId(personId).startDate(startDate)
						.firstDateWorked(firstDateWorked).originalStartDate(originalStartDate)
						.seniorityDate(seniorityDate).socialServiceAge(socialServiceAge).seniority(seniority)
						.endDate(endDate).okToRehire(okToRehire).salaryEndDate(salaryEndDate)
						.benefitsEndDate(benefitsEndDate).leavingReason(leavingReason).build();
				save("SapReportMapper.saveSapEmpEmployment", entity);
			}
		}
	}

	// 组织以及职位信息 EmpJob
	public void saveSapEmpJob(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapEmpJob", null);

		String url = "https://api15.sapsf.cn/odata/v2/EmpJob?$filter=userId in %s&$format=json"
				+ "&$expand=positionNav,companyNav,businessUnitNav,divisionNav,departmentNav,customString19Nav,locationNav,jobCodeNav";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String positionName = JsonNodeUtil.getValue(userNode, "positionNav", "externalName_zh_CN");// 职位
				String positionEntryDate = JsonNodeUtil.getValue(userNode, "positionEntryDate");// 就职日期
				String companyName = JsonNodeUtil.getValue(userNode, "companyNav", "name");// 公司
				String businessUnitName = JsonNodeUtil.getValue(userNode, "businessUnitNav", "name");// 业务单元
				String divisionName = JsonNodeUtil.getValue(userNode, "divisionNav", "name");// 部门
				String departmentName = JsonNodeUtil.getValue(userNode, "departmentNav", "name");// 团队
				String teamName = JsonNodeUtil.getValue(userNode, "customString19Nav", "externalName_zh_CN");// 小组
				String locationName = JsonNodeUtil.getValue(userNode, "locationNav", "name");// 工作地点
				String managerId = JsonNodeUtil.getValue(userNode, "managerId");// 直线经理
				String managerName = WebConstants.NAME_MAP.get(managerId);// 直线经理
				String jobCodeName = JsonNodeUtil.getValue(userNode, "jobCodeNav", "name");// 职务分类
				String jobTitle = JsonNodeUtil.getValue(userNode, "jobTitle");// 标准职务名称
				String rank = getLabelValue(JsonNodeUtil.getValue(userNode, "customString2"));// 职级
				String managementOrNot = getLabelValue(JsonNodeUtil.getValue(userNode, "customString4"));// 是否管理层
				SapEmpJob entity = SapEmpJob.builder().userId(userId).positionName(positionName)
						.positionEntryDate(positionEntryDate).companyName(companyName)
						.businessUnitName(businessUnitName).divisionName(divisionName).departmentName(departmentName)
						.teamName(teamName).locationName(locationName).managerId(managerId).managerName(managerName)
						.jobCodeName(jobCodeName).jobTitle(jobTitle).rank(rank).managementOrNot(managementOrNot)
						.build();
				save("SapReportMapper.saveSapEmpJob", entity);
			}
		}
	}

	// 工作关系 EmpJobRelationships
	public void saveSapEmpJobRelationships(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapEmpJobRelationships", null);

		String url = "https://api15.sapsf.cn/odata/v2/EmpJobRelationships?$filter=userId in %s&$format=json&$expand=relUserNav";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String relationshipType = getLabelValue(JsonNodeUtil.getValue(userNode, "relationshipType"));// 关系类型
				String relUserName = JsonNodeUtil.getValue(userNode, "relUserNav", "lastName")
						+ JsonNodeUtil.getValue(userNode, "relUserNav", "firstName");// 姓名
				SapEmpJobRelationships entity = SapEmpJobRelationships.builder().userId(userId)
						.relationshipType(relationshipType).relUserName(relUserName).build();
				save("SapReportMapper.saveSapEmpJobRelationships", entity);
			}
		}
	}

	// 先前工作经历 Background_OutsideWorkExperience
	public void saveSapOutsideWorkExperience(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapOutsideWorkExperience", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_OutsideWorkExperience?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate"); // 开始日期
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 结束日期
				String employer = JsonNodeUtil.getValue(userNode, "employer");// 曾工作公司名称
				String businessType = JsonNodeUtil.getValue(userNode, "businessType");// 公司所在地
				String department = JsonNodeUtil.getValue(userNode, "startTitle");// 所在部门
				String position = JsonNodeUtil.getValue(userNode, "custom1");// 职位
				String leavingReason = JsonNodeUtil.getValue(userNode, "custom2");// 离职原因
				String immediateSupervisorName = JsonNodeUtil.getValue(userNode, "custom3");// 直接上司姓名
				String contactInformation = JsonNodeUtil.getValue(userNode, "custom4");// 联系方式
				SapOutsideWorkExperience entity = SapOutsideWorkExperience.builder().userId(userId).startDate(startDate)
						.endDate(endDate).employer(employer).businessType(businessType).department(department)
						.position(position).leavingReason(leavingReason)
						.immediateSupervisorName(immediateSupervisorName).contactInformation(contactInformation)
						.build();
				save("SapReportMapper.saveSapOutsideWorkExperience", entity);
			}
		}
	}

	// 公司内工作经历 Background_InsideWorkExperience
	public void saveSapInsideWorkExperience(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapInsideWorkExperience", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_InsideWorkExperience?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate");// 开始日期
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 结束日期
				String title = JsonNodeUtil.getValue(userNode, "title");// 职务
				String department = JsonNodeUtil.getValue(userNode, "department");// 部门
				SapInsideWorkExperience entity = SapInsideWorkExperience.builder().userId(userId).startDate(startDate)
						.endDate(endDate).title(title).department(department).build();
				save("SapReportMapper.saveSapInsideWorkExperience", entity);
			}
		}
	}

	// 培训经历 Background_Courses
	public void saveSapCourses(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapCourses", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_Courses?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String course = JsonNodeUtil.getValue(userNode, "course");// 课程名称
				String startDate = JsonNodeUtil.getValue(userNode, "institution");// 开始日期
				String endDate = JsonNodeUtil.getValue(userNode, "instructionType");// 结束日期
				String type = getLabelValue(JsonNodeUtil.getValue(userNode, "length"));// 培训类型
				String place = JsonNodeUtil.getValue(userNode, "custom9");// 培训地点
				String duration = JsonNodeUtil.getValue(userNode, "custom1");// 历时
				String result = JsonNodeUtil.getValue(userNode, "custom2");// 培训结果
				String certificateOrNot = getLabelValue(JsonNodeUtil.getValue(userNode, "custom3"));// 是否有证书
				String dueTime = JsonNodeUtil.getValue(userNode, "custom4");// 培训服务期到期时间
				String remark = JsonNodeUtil.getValue(userNode, "custom7");// 备注
				SapCourses entity = SapCourses.builder().userId(userId).course(course).startDate(startDate)
						.endDate(endDate).type(type).place(place).duration(duration).result(result)
						.certificateOrNot(certificateOrNot).dueTime(dueTime).remark(remark).build();
				save("SapReportMapper.saveSapCourses", entity);
			}
		}
	}

	// 学历教育 Background_Education
	public void saveSapEducation(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapEducation", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_Education?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate");// 开始日期
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 结束日期
				String school = JsonNodeUtil.getValue(userNode, "school");// 院校
				String major = JsonNodeUtil.getValue(userNode, "major");// 专业
				String degree = getLabelValue(JsonNodeUtil.getValue(userNode, "degree"));// 学历
				String qualification = getLabelValue(JsonNodeUtil.getValue(userNode, "custom1"));// 学位
				SapEducation entity = SapEducation.builder().userId(userId).startDate(startDate).endDate(endDate)
						.school(school).major(major).degree(degree).qualification(qualification).build();
				save("SapReportMapper.saveSapEducation", entity);
			}
		}
	}

	// 证书 Background_Certificates
	public void saveSapCertificates(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapCertificates", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_Certificates?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String name = JsonNodeUtil.getValue(userNode, "name");// 证书/执照
				String description = JsonNodeUtil.getValue(userNode, "description");// 描述
				String institution = JsonNodeUtil.getValue(userNode, "institution");// 证书颁发机构
				String startDate = JsonNodeUtil.getValue(userNode, "startDate");// 证书颁发日期
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 证书到期日期
				SapCertificates entity = SapCertificates.builder().userId(userId).name(name).description(description)
						.institution(institution).startDate(startDate).endDate(endDate).build();
				save("SapReportMapper.saveSapCertificates", entity);
			}
		}
	}

	// 语言能力 Background_Languages
	public void saveSapLanguages(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapLanguages", null);

		String url = "https://api15.sapsf.cn/odata/v2/Background_Languages?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String language = getLabelValue(JsonNodeUtil.getValue(userNode, "language"));// 语言
				String speakingProf = getLabelValue(JsonNodeUtil.getValue(userNode, "speakingProf"));// 口语能力
				String readingProf = getLabelValue(JsonNodeUtil.getValue(userNode, "readingProf"));// 阅读能力
				String writingProf = getLabelValue(JsonNodeUtil.getValue(userNode, "writingProf"));// 书写能力
				SapLanguages entity = SapLanguages.builder().userId(userId).language(language)
						.speakingProf(speakingProf).readingProf(readingProf).writingProf(writingProf).build();
				save("SapReportMapper.saveSapLanguages", entity);
			}
		}
	}

	// 绩效历史 TrendData_SysOverallPerformance
	public void saveSapOverallPerformance(HttpHeaders headers, List<SapUser> sapUsers) throws Exception {
		delete("SapReportMapper.deleteSapOverallPerformance", null);

		String url = "https://api15.sapsf.cn/odata/v2/TrendData_SysOverallPerformance?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIds(sapUsers));
		JsonNode node = requestService.getForObject(url, headers);
		if (node != null) {
			Iterator<JsonNode> iterator = node.get("d").get("results").elements();
			while (iterator.hasNext()) {
				JsonNode userNode = iterator.next();
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate"); // 起始日期
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");// 结束日期
				String module = JsonNodeUtil.getValue(userNode, "module"); // 模块
				String name = JsonNodeUtil.getValue(userNode, "name"); // 名称
				String description = JsonNodeUtil.getValue(userNode, "description");// 描述
				SapOverallPerformance entity = SapOverallPerformance.builder().userId(userId).startDate(startDate)
						.endDate(endDate).module(module).name(name).description(description).build();
				save("SapReportMapper.saveSapOverallPerformance", entity);
			}
		}
	}

	public String getLabelValue(String optionId) {
		if (Tools.isEmpty(optionId)) {
			return "";
		}
		if (WebConstants.LABEL_MAP.containsKey(optionId)) {
			return WebConstants.LABEL_MAP.get(optionId);
		} else {
			String value = "";
			try {
				String url = "https://api15.sapsf.cn/odata/v2/PicklistLabel(locale='zh_CN',optionId=" + optionId
						+ ")?$format=json";
				JsonNode node = requestService.getForObject(url, getHttpHeaders());
				value = JsonNodeUtil.getValue(node, "d", "label");
			} catch (Exception e) {
			}
			WebConstants.LABEL_MAP.put(optionId, value);
			return value;
		}
	}
}
