package org.fouram.service;

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

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

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

@Service
public class SapEmployeeTimeService extends BaseService {

	@Autowired
	private RequestService requestService;
	@Autowired
	private WxUserService wxUserService;

	public String getUserIdList(List<String> sapUsers) {
		String userIds = "";
		for (String sapUser : sapUsers) {
			userIds += "'" + sapUser + "',";
		}
		return userIds;
	}

	@SuppressWarnings("unchecked")
	public void saveEmployeeTimes() throws Exception {
		List<String> userIds = wxUserService.selectAllUserIds();
		String url = "https://api15.sapsf.cn/odata/v2/EmployeeTime?$filter=userId in %s&$format=json";
		url = String.format(url, getUserIdList(userIds));
		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 externalCode = JsonNodeUtil.getValue(userNode, "externalCode");
				String lastModifiedDateTime = JsonNodeUtil.getValue(userNode, "lastModifiedDateTime");
				String loaActualReturnDate = JsonNodeUtil.getValue(userNode, "loaActualReturnDate");
				String createdDateTime = JsonNodeUtil.getValue(userNode, "createdDateTime");
				String timeType = JsonNodeUtil.getValue(userNode, "timeType");
				String loaExpectedReturnDate = JsonNodeUtil.getValue(userNode, "loaExpectedReturnDate");
				String flexibleRequesting = JsonNodeUtil.getValue(userNode, "flexibleRequesting");
				String timeRecordOrigin = JsonNodeUtil.getValue(userNode, "timeRecordOrigin");
				String mdfSystemRecordStatus = JsonNodeUtil.getValue(userNode, "mdfSystemRecordStatus");
				String custPeriod = JsonNodeUtil.getValue(userNode, "cust_period");
				String quantityInHours = JsonNodeUtil.getValue(userNode, "quantityInHours");
				String loaStartJobInfoId = JsonNodeUtil.getValue(userNode, "loaStartJobInfoId");
				String startDate = JsonNodeUtil.getValue(userNode, "startDate");
				String startDateTime = JsonNodeUtil.getTime(userNode, "startDate");
				String endDate = JsonNodeUtil.getValue(userNode, "endDate");
				String endDateTime = JsonNodeUtil.getTime(userNode, "endDate");
				String displayQuantity = JsonNodeUtil.getValue(userNode, "displayQuantity");
				String quantityInDays = JsonNodeUtil.getValue(userNode, "quantityInDays");
				String startTime = JsonNodeUtil.getValue(userNode, "startTime");
				String loaEndJobInfoId = JsonNodeUtil.getValue(userNode, "loaEndJobInfoId");
				String approvalStatus = JsonNodeUtil.getValue(userNode, "approvalStatus");
				String cancellationWorkflowRequestId = JsonNodeUtil.getValue(userNode, "cancellationWorkflowRequestId");
				String deductionQuantity = JsonNodeUtil.getValue(userNode, "deductionQuantity");
				String editable = JsonNodeUtil.getValue(userNode, "editable");
				String lastModifiedBy = JsonNodeUtil.getValue(userNode, "lastModifiedBy");
				String workflowRequestId = JsonNodeUtil.getValue(userNode, "workflowRequestId");
				String undeterminedEndDate = JsonNodeUtil.getValue(userNode, "undeterminedEndDate");
				String userId = JsonNodeUtil.getValue(userNode, "userId");
				String recurrenceGroup = JsonNodeUtil.getValue(userNode, "recurrenceGroup");
				String createdBy = JsonNodeUtil.getValue(userNode, "createdBy");
				String workflowInitiatedByAdmin = JsonNodeUtil.getValue(userNode, "workflowInitiatedByAdmin");
				String comment = JsonNodeUtil.getValue(userNode, "comment");
				String fractionQuantity = JsonNodeUtil.getValue(userNode, "fractionQuantity");
				String endTime = JsonNodeUtil.getValue(userNode, "endTime");
				String originalQuantityInDays = JsonNodeUtil.getValue(userNode, "originalQuantityInDays");

				if (selectById(externalCode) == null) {
					SapEmployeeTime employeeTime = SapEmployeeTime.builder().externalCode(externalCode)
							.lastModifiedDateTime(lastModifiedDateTime).loaActualReturnDate(loaActualReturnDate)
							.createdDateTime(createdDateTime).timeType(timeType)
							.loaExpectedReturnDate(loaExpectedReturnDate).flexibleRequesting(flexibleRequesting)
							.timeRecordOrigin(timeRecordOrigin).mdfSystemRecordStatus(mdfSystemRecordStatus)
							.custPeriod(custPeriod).quantityInHours(quantityInHours)
							.loaStartJobInfoId(loaStartJobInfoId).startDate(startDate).startDateTime(startDateTime)
							.endDate(endDate).endDateTime(endDateTime).displayQuantity(displayQuantity)
							.quantityInDays(quantityInDays).startTime(startTime).loaEndJobInfoId(loaEndJobInfoId)
							.approvalStatus(approvalStatus).cancellationWorkflowRequestId(cancellationWorkflowRequestId)
							.deductionQuantity(deductionQuantity).editable(editable).lastModifiedBy(lastModifiedBy)
							.workflowRequestId(workflowRequestId).undeterminedEndDate(undeterminedEndDate)
							.userId(userId).recurrenceGroup(recurrenceGroup).createdBy(createdBy)
							.workflowInitiatedByAdmin(workflowInitiatedByAdmin).comment(comment)
							.fractionQuantity(fractionQuantity).endTime(endTime)
							.originalQuantityInDays(originalQuantityInDays).build();

					saveOne(employeeTime);
				}
			}
		}

		// 更新所有未通过的为无效
		update("SapEmployeeTimeMapper.updateUnApprovedDelete", null);

		// 去除重复数据
		List<SapEmployeeTime> employeeTimes = (List<SapEmployeeTime>) findList("SapEmployeeTimeMapper.selectRepeat",
				null);
		Set<String> checkinDays = Sets.newHashSet();
		for (SapEmployeeTime sapCheck : employeeTimes) {
			if (!checkinDays.contains(sapCheck.getStartDate() + sapCheck.getUserId())) {
				checkinDays.add(sapCheck.getStartDate() + sapCheck.getUserId());
			} else {
				update("SapEmployeeTimeMapper.updateDeleteByCode", sapCheck);
			}
		}
	}

	public void saveOne(SapEmployeeTime employeeTime) throws Exception {
		save("SapEmployeeTimeMapper.saveOne", employeeTime);
	}

	public SapEmployeeTime selectById(String externalCode) throws Exception {
		return (SapEmployeeTime) findObject("SapEmployeeTimeMapper.selectById", externalCode);
	}

}
