package org.fouram.service;

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

import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.core.util.Base64Util;
import org.fouram.core.util.ConfConfig;
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);
	}

	private HttpHeaders getHttpHeaders() {
		HttpHeaders headers = new HttpHeaders();
		StringBuilder stringBuilder = new StringBuilder();
		String sapApiUser = ConfConfig.getConfigString("sapApi.user");
		String authorizationStr = stringBuilder.append("Basic ").append(Base64Util.encodeString(sapApiUser)).toString();
		headers.add("Authorization", authorizationStr);
		return headers;
	}

	public void saveAllReportData() throws Exception {
		HttpHeaders headers = getHttpHeaders();
		List<SapUser> sapUsers = selectReportUserList();
		String personIds = "";
		String userIds = "";
		for (SapUser sapUser : sapUsers) {
			personIds += "'" + sapUser.getPersonId() + "',";
			userIds += "'" + sapUser.getUserId() + "',";
		}
		this.saveOrUpdateBackgroundCertificates(headers, personIds, userIds);
		this.saveOrUpdateBackgroundCourses(headers, userIds);
		this.saveOrUpdateBackgroundEducation(headers, personIds, userIds);
		this.saveOrUpdateBackgroundInsideWorkExperience(headers, userIds);
		this.saveOrUpdateBackgroundLanguages(headers, personIds, userIds);
		this.saveOrUpdateTrendDataSysOverallPerformance(headers, personIds, userIds);
		this.saveOrUpdateBackgroundOutsideWorkExperience(headers, userIds);
		this.saveOrUpdateEmpEmployment(headers, personIds, userIds);
		this.saveOrUpdateEmpJob(headers, personIds, userIds);
		this.saveOrUpdateEmpJobRelationships(headers, userIds);
		this.saveOrUpdatePerEmail(headers, personIds, userIds);
		this.saveOrUpdatePerGlobalInfoCHN(headers, personIds, userIds);
		this.saveOrUpdatePerNationalId(headers, personIds, userIds);
		this.saveOrUpdatePerPerson(headers, personIds, userIds);
		this.saveOrUpdatePerPhone(headers, personIds, userIds);
		this.saveOrUpdatePerSocialAccount(headers, personIds, userIds);
	}

//	基本信息	PerPerson,PerPersonal
	public void saveOrUpdatePerPerson(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerPerson?$filter=personIdExternal in %s&$format=json&$expand=customString1Nav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();// 员工号
				String dateOfBirth = userNode.get("dateOfBirth").asText().trim();// 出生日期
				String placeOfBirth = userNode.get("placeOfBirth").asText().trim();// 籍贯
				String customString1Code = userNode.get("customString1Nav").get("externalCode").asText().trim();// 最高学历
			}
		}
		
		url = "https://api15.sapsf.cn/odata/v2/PerPersonal?$filter=personIdExternal in %s&$format=json&$expand=maritalStatusNav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String firstName = userNode.get("firstName").asText().trim();// 名字
				String lastName = userNode.get("lastName").asText().trim();// 姓氏
				String displayName = userNode.get("displayName").asText().trim();// 英文全名
				String formalName = userNode.get("formalName").asText().trim();// 全名
				String nationality = userNode.get("nationality").asText().trim();// 国籍
				String gender = userNode.get("gender").asText().trim();// 性别
				String maritalStatusCode = userNode.get("maritalStatusNav").get("externalCode").asText().trim();// 婚姻状况
				String firstNameAlt1 = userNode.get("firstNameAlt1").asText().trim();// 英文名
				String lastNameAlt1 = userNode.get("lastNameAlt1").asText().trim();// 英文姓
				String firstNameAlt2 = userNode.get("firstNameAlt2").asText().trim();// 拼音名
				String lastNameAlt2 = userNode.get("lastNameAlt2").asText().trim();// 拼音姓
			}
		}
	}

//	个人信息	PerGlobalInfoCHN
	public void saveOrUpdatePerGlobalInfoCHN(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerGlobalInfoCHN?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String genericNumber1Code = userNode.get("genericNumber1Nav").get("externalCode").asText().trim();// 户口类型
				String genericNumber4Code = userNode.get("genericNumber4Nav").get("externalCode").asText().trim();// 民族
				String customString6Code = userNode.get("customString6Nav").get("externalCode").asText().trim();// 政治面貌
				String customString1 = userNode.get("customString1").asText().trim();// 组织关系所在地
				String customString2 = userNode.get("customString2").asText().trim();// 社保所在地
			}
		}
	}

//	国家身份信息	PerNationalId
	public void saveOrUpdatePerNationalId(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerNationalId?$filter=personIdExternal in %s&$format=json&$expand=countryNav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String countryName = userNode.get("countryNav").get("territoryName").asText().trim();// 国家/地区 
				String cardType = userNode.get("cardType").asText().trim();// 国民身份证类型 
				String nationalId = userNode.get("nationalId").asText().trim();// 国民身份证 
			}
		}
	}

//	邮件信息	PerEmail
	public void saveOrUpdatePerEmail(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerEmail?$filter=personIdExternal in %s&$format=json&$expand=emailTypeNav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String emailTypeCode = userNode.get("emailTypeNav").get("externalCode").asText().trim();// 电子邮件类型 
				String emailAddress = userNode.get("emailAddress").asText().trim();// 电子邮件地址 
				String isPrimary = userNode.get("isPrimary").asText().trim();// 主要 
			}
		}

	}

//	通讯信息	PerPhone
	public void saveOrUpdatePerPhone(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerPhone?$filter=personIdExternal in %s&$format=json&$expand=phoneTypeNav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String phoneTypeCode = userNode.get("phoneTypeNav").get("externalCode").asText().trim();//电话类型	
				String phoneNumber = userNode.get("phoneNumber").asText().trim();//电话号码	
				String isPrimary = userNode.get("isPrimary").asText().trim();//主要	
			}
		}
	}

//	社交账号	PerSocialAccount
	public void saveOrUpdatePerSocialAccount(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/PerSocialAccount?$filter=personIdExternal in %s&$format=json&$expand=domainNav";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				String domainCode = userNode.get("domainNav").get("externalCode").asText().trim();//微信
				String imId = userNode.get("imId").asText().trim();//微信号
			}
		}
	}

//	雇佣详细信息	EmpEmployment
	public void saveOrUpdateEmpEmployment(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/EmpEmployment?$filter=personIdExternal in %s&$format=json";
		url = String.format(url, personIds);
		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 = userNode.get("personIdExternal").asText().trim();
				//最近一次入职日期
				//首次工作日期
				//进入集团日期
				//公司
				//司龄计算日
				//社会工龄
				//司龄（最近入职）
				//离职日期
				//离职原因
				//可以再雇佣
				//工资单结束日期
				//最后工作日期
				//最后结薪日期
				//福利结算日期
				//离职详细原因
			}
		}
	}

	// 组织以及职位信息 EmpJob
	public void saveOrUpdateEmpJob(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/EmpJob?$filter=userId in %s&$format=json&$expand=positionNav";
		url = String.format(url, personIds);
		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 = userNode.get("userId").asText().trim();
				String jobTitle = userNode.get("jobTitle").asText().trim();// 职位
				String positionEntryDate = userNode.get("positionEntryDate").asText().trim();// 就职日期
				String personId = userNode.get("personIdExternal").asText().trim();// 在职时间
				String companyName = userNode.get("companyNav").get("name").asText().trim();// 公司
//				String personId = userNode.get("personIdExternal").asText().trim();// 业务单元
//				String personId = userNode.get("personIdExternal").asText().trim();// 部门
//				String personId = userNode.get("personIdExternal").asText().trim();// 团队
//				String personId = userNode.get("personIdExternal").asText().trim();// 小组
//				String personId = userNode.get("personIdExternal").asText().trim();// 工作地点
//				String managerId = userNode.get("managerId").asText().trim();// TODO直线经理
//				String personId = userNode.get("personIdExternal").asText().trim();// 职务分类
//				String personId = userNode.get("personIdExternal").asText().trim();// 标准职务名称
//				String personId = userNode.get("personIdExternal").asText().trim();// 员工性质
//				String personId = userNode.get("personIdExternal").asText().trim();// 标准职务名称
//				String personId = userNode.get("personIdExternal").asText().trim();// 员工性质
//				String personId = userNode.get("personIdExternal").asText().trim();// 职级
//				String personId = userNode.get("personIdExternal").asText().trim();// 是否管理层
			}
		}
	}

	// 工作关系 EmpJobRelationships
	public void saveOrUpdateEmpJobRelationships(HttpHeaders headers, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/EmpJobRelationships?$filter=userId in %s&$format=json&$expand=relationshipTypeNav,relUserNav";
		url = String.format(url, userIds);
		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 = userNode.get("userId").asText().trim();
				String relationshipTypeCode = userNode.get("relationshipTypeNav").get("externalCode").asText().trim();// 关系类型
				String relUserName = userNode.get("relUserNav").get("lastName").asText().trim()
						+ userNode.get("relUserNav").get("firstName").asText().trim();// 姓名
			}
		}
	}

	// 先前工作经历 Background_OutsideWorkExperience
	public void saveOrUpdateBackgroundOutsideWorkExperience(HttpHeaders headers, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_OutsideWorkExperience?$filter=userId in %s&$format=json";
		url = String.format(url, userIds);
		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 = userNode.get("userId").asText().trim();
				String startDate = userNode.get("startDate").asText().trim(); // 开始日期
				String endDate = userNode.get("endDate").asText().trim();// 结束日期
				String employer = userNode.get("employer").asText().trim();// 曾工作公司名称
				String businessType = userNode.get("businessType").asText().trim();// 公司所在地
				String startTitle = userNode.get("startTitle").asText().trim();// 所在部门
				String custom1 = userNode.get("custom1").asText().trim();// 职位
				String custom2 = userNode.get("custom2").asText().trim();// 离职原因
				String custom3 = userNode.get("custom3").asText().trim();// 直接上司姓名
				String custom4 = userNode.get("custom4").asText().trim();// 联系方式
			}
		}
	}

	// 公司内工作经历 Background_InsideWorkExperience
	public void saveOrUpdateBackgroundInsideWorkExperience(HttpHeaders headers, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_InsideWorkExperience?$filter=userId in %s&$format=json";
		url = String.format(url, userIds);
		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 = userNode.get("userId").asText().trim();
				String startDate = userNode.get("startDate").asText().trim();// 开始日期
				String endDate = userNode.get("endDate").asText().trim();// 结束日期
				String title = userNode.get("title").asText().trim();// 职务
				String department = userNode.get("department").asText().trim();// 部门
			}
		}
	}

	// 培训经历 Background_Courses
	public void saveOrUpdateBackgroundCourses(HttpHeaders headers, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_Courses?$filter=userId in %s&$format=json&$expand=custom3Nav,lengthNav";
		url = String.format(url, userIds);
		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 = userNode.get("userId").asText().trim();
				String course = userNode.get("course").asText().trim();// 课程名称
				String institution = userNode.get("institution").asText().trim();// 开始日期
				String instructionType = userNode.get("instructionType").asText().trim();// 结束日期
				String lengthCode = userNode.get("lengthNav").get("externalCode").asText().trim();// 培训类型
				String custom9 = userNode.get("custom9").asText().trim();// 培训地点
				String custom1 = userNode.get("custom1").asText().trim();// 历时
				String custom2 = userNode.get("custom2").asText().trim();// 培训结果
				String custom3Code = userNode.get("custom3Nav").get("externalCode").asText().trim();// 是否有证书
				String custom4 = userNode.get("custom4").asText().trim();// 培训服务期到期时间
				String custom7 = userNode.get("custom7").asText().trim();// 备注
			}
		}
	}

	// 学历教育 Background_Education
	public void saveOrUpdateBackgroundEducation(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_Education?$filter=userId in %s&$format=json";
		url = String.format(url, personIds);
		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 = userNode.get("userId").asText().trim();
				String startDate = userNode.get("startDate").asText().trim();// 开始日期
				String endDate = userNode.get("endDate").asText().trim();// 结束日期
				String school = userNode.get("school").asText().trim();// 院校
				String major = userNode.get("major").asText().trim();// 专业
				String degree = userNode.get("degree").asText().trim();// 学历
				String custom1 = userNode.get("custom1").asText().trim();// 学位
			}
		}
	}

	// 证书 Background_Certificates
	public void saveOrUpdateBackgroundCertificates(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_Certificates?$filter=userId in %s&$format=json";
		url = String.format(url, personIds);
		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 = userNode.get("userId").asText().trim();
				String name = userNode.get("name").asText().trim();// 证书/执照
				String description = userNode.get("description").asText().trim();// 描述
				String institution = userNode.get("institution").asText().trim();// 证书颁发机构
				String startDate = userNode.get("startDate").asText().trim();// 证书颁发日期
				String endDate = userNode.get("endDate").asText().trim();// 证书到期日期
			}
		}
	}

	// 语言能力 Background_Languages
	public void saveOrUpdateBackgroundLanguages(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/Background_Languages?$filter=userId in %s&$format=json&$expand=languageNav,speakingProfNav,readingProfNav,writingProfNav";
		url = String.format(url, personIds);
		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 = userNode.get("userId").asText().trim();
				String languageCode = userNode.get("languageNav").get("externalCode").asText().trim();// 语言
				String speakingProfCode = userNode.get("speakingProfNav").asText().trim();// 口语能力
				String readingProfCode = userNode.get("readingProfNav").asText().trim();// 阅读能力
				String writingProfCode = userNode.get("writingProfNav").asText().trim();// 书写能力
			}
		}
	}

	// 绩效历史 TrendData_SysOverallPerformance
	public void saveOrUpdateTrendDataSysOverallPerformance(HttpHeaders headers, String personIds, String userIds) {
		String url = "https://api15.sapsf.cn/odata/v2/TrendData_SysOverallPerformance?$filter=userId in %s&$format=json";
		url = String.format(url, personIds);
		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 = userNode.get("userId").asText().trim();
				String startDate = userNode.get("startDate").asText().trim(); // 起始日期
				String endDate = userNode.get("endDate").asText().trim();// 结束日期
				String module = userNode.get("module").asText().trim(); // 模块
				String name = userNode.get("name").asText().trim(); // 名称
				String description = userNode.get("description").asText().trim();// 描述
			}
		}
	}
}
