package org.fouram.service;

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

import org.apache.commons.lang3.StringUtils;
import org.fouram.core.base.service.BaseService;
import org.fouram.core.base.service.RequestService;
import org.fouram.core.plugin.weixin.cp.util.WXCpUserUtil;
import org.fouram.core.util.Base64Util;
import org.fouram.core.util.ConfConfig;
import org.fouram.core.util.Tools;
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.Lists;

@Service
public class SapUserService extends BaseService {

	@Autowired
	private SapOrgService sapOrgService;
	@Autowired
	private RequestService requestService;
	@Autowired
	private SapPersonalService sapPersonalService;

	private static boolean isTestWXSync = true;

	public List<SapUser> getSapUsers() throws Exception {
		HttpHeaders headers = getHttpHeaders();
		String userUrl = "https://api15.sapsf.cn/odata/v2/User?$filter=status in 'active'&$format=json&$expand=personKeyNav";
		// get
		JsonNode node = requestService.getForObject(userUrl, headers);
		List<SapUser> sapUsers = Lists.newArrayList();
		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();
				// 去除非员工账号和测试数据
				if (!userId.startsWith("Test")) {
					String username = userNode.get("username").asText().trim();
					String name = userNode.get("lastName").asText().trim() + userNode.get("firstName").asText().trim();
					String position = userNode.get("jobCode").asText().trim();
					String formatPosition = formatLastCode(position).trim();
					String mobile = userNode.get("cellPhone").asText().trim();
					String businessPhone = userNode.get("businessPhone").asText().trim();
					String formatMobile = formatMobile(mobile).trim();
					String email = userNode.get("email").asText().trim();
					String personId = null;
					JsonNode personKeyNav = userNode.get("personKeyNav");
					if (personKeyNav != null && personKeyNav.get("personIdExternal") != null) {
						personId = personKeyNav.get("personIdExternal").asText().trim();
					}
					// 手机号码脱敏
//					if (StringUtils.isNotBlank(formatMobile) && formatMobile.length() == 11) {
//						formatMobile = formatMobile.substring(0, 8) + "999";
//					} else {
//						formatMobile = "";
//					}
					// 员工信息
					SapUser sapUser = SapUser.builder().userId(userId).personId(personId).username(username).name(name)
							.position(position).formatPosition(formatPosition).mobile(mobile).formatMobile(formatMobile)
							.businessPhone(businessPhone).formatBusinessPhone(businessPhone).email(email)
							.formatEmail(email).isPrimary(userId.equals(personId)).build();
					sapUsers.add(sapUser);
				}
			}
		}
		// 获取用户对应机构
		sapUsers = sapOrgService.setOrg(headers, sapUsers);
		// 获取用户对应性别
		sapUsers = sapPersonalService.setGender(headers, sapUsers);
		return sapUsers;
	}

	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;
	}

	private String formatLastCode(String str) {
		str = str.replace(" ", "");
		if (str.endsWith(")")) {
			return str.substring(0, str.lastIndexOf("("));
		}
		return str;
	}

	private String formatMobile(String mobile) {
		return mobile.replace(" ", "").replace("(86)", "").replace("（86）", "");
	}

	public void saveOneAndSyncWX(SapUser entity) throws Exception {
		entity.setCreateDate(new Date());
		entity.setDelFlag(false);
		save("SapUserMapper.saveOne", entity);
		// 更新同步企业微信备注
		updateWXResult(entity.getPersonId());
	}

	public void updateEnable(String userId) throws Exception {
		SapUser entity = SapUser.builder().userId(userId).delFlag(false).build();
		update("SapUserMapper.updateDelFlag", entity);
	}

	public void updateOneAndSyncWX(SapUser entity) throws Exception {
		entity.setDelFlag(false);
		update("SapUserMapper.updateOne", entity);
		// 更新同步企业微信备注
		updateWXResult(entity.getPersonId());
	}

	public void updateWXResult(String personId) throws Exception {
		String result = createOrUpdateWXUser(personId);
		SapUser entity = SapUser.builder().personId(personId).result(result).build();
		update("SapUserMapper.updateResult", entity);
	}

	private String createOrUpdateWXUser(String personId) throws Exception {
		// 测试
		if (isTestWXSync) {
			return "Success";
		}
		System.out.println(personId);
		List<SapUser> sapUsers = selectListByPersonId(personId);
		SapUser wxSapUser = sapUsers.get(0);
		String[] firstOrgList = new String[sapUsers.size()];
		String[] secondOrgList = new String[sapUsers.size()];
		String[] thirdOrgList = new String[sapUsers.size()];
		String[] fourthOrgList = new String[sapUsers.size()];
		for (int i = 0; i < sapUsers.size(); i++) {
			SapUser sapUser = sapUsers.get(i);
			String checkResult = checkSapUser(sapUser);
			if (StringUtils.isNotBlank(checkResult)) {
				return checkResult;
			}
			firstOrgList[i] = sapUser.getFirstOrg();
			secondOrgList[i] = sapUser.getSecondOrg();
			thirdOrgList[i] = sapUser.getThirdOrg();
			fourthOrgList[i] = sapUser.getFourthOrg();
		}
		return WXCpUserUtil.createOrUpdate(personId, wxSapUser.getName(), firstOrgList, secondOrgList, thirdOrgList,
				fourthOrgList, wxSapUser.getFormatPosition(), wxSapUser.getFormatMobile(), wxSapUser.getGender(),
				wxSapUser.getFormatEmail(), wxSapUser.getFormatBusinessPhone());
	}

	public String checkSapUser(SapUser sapUser) {
		if (Tools.isEmpty(sapUser.getPersonId())) {
			return "员工ID为空";
		} else if (Tools.isEmpty(sapUser.getFirstOrg())) {
			return "一级组织为空";
		}
		return null;
	}

	public SapUser selectOne(String userId) throws Exception {
		return (SapUser) findObject("SapUserMapper.selectOne", userId);
	}

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

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

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

	public void updateAllDelete() throws Exception {
		update("SapUserMapper.updateAllDelete", null);
	}

	public static void main(String[] args) {
		StringBuilder stringBuilder = new StringBuilder();
		String sapApiUser = "API01@cmccoltd:cmccoltd123";
		String authorizationStr = stringBuilder.append("Basic ").append(Base64Util.encodeString(sapApiUser)).toString();
		System.out.println(authorizationStr);
	}
}
