package org.fouram.service;

import java.util.List;

import org.fouram.core.base.service.BaseService;
import org.fouram.core.util.DateUtil;
import org.fouram.core.util.LoggerUtil;
import org.fouram.entity.SapUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TaskService extends BaseService {

	@Autowired
	private SapUserService sapUserService;

	public void syncWeixinUser() {
		LoggerUtil.info("同步开始->" + DateUtil.getTime());
		try {
			// 更新数据删除
			sapUserService.updateAllDelete();
			// 接口获取所有有效数据，保存或者更新delFlag=0
			List<SapUser> getSapUsers = sapUserService.getSapUsers();
			LoggerUtil.info("接口获取所有有效数据->" + getSapUsers.size());
			for (SapUser sapUser : getSapUsers) {
				SapUser sapUserDb = sapUserService.selectOne(sapUser.getUserId());
				if (sapUserDb == null) {
					sapUserService.saveOneAndSyncWX(sapUser);
				} else {
					if (!isEquals(sapUserDb, sapUser)) {
						sapUserService.updateOneAndSyncWX(sapUser);
					}else {
						sapUserService.updateEnable(sapUser.getUserId());
					}
				}
			}
			// 查询未更新delFlag数据对应企业微信账号
			List<SapUser> deleteSapUsers = sapUserService.selectDeleteList();
			LoggerUtil.info("SAP删除数据->" + deleteSapUsers.size());
//			for(SapUser sapUser : deleteSapUsers) {
//				WXCpUserUtil.delete(sapUser.getPersonId());
//			}
			// 部分数据插入微信未成功，处理数据后，重新插入
			List<SapUser> unSyncSapUsers = sapUserService.selectUnSyncList();
			LoggerUtil.info("部分未成功插入数据->" + unSyncSapUsers.size());
			for (SapUser sapUser : unSyncSapUsers) {
				sapUserService.updateOneAndSyncWX(sapUser);
			}
		} catch (Exception e) {
			LoggerUtil.error(e);
		}
		LoggerUtil.info("同步结束->" + DateUtil.getTime());
	}

	private boolean isEquals(SapUser sapUserDb, SapUser sapUser) {
		if (sapUserDb.toCompareString().equals(sapUser.toCompareString())) {
			return true;
		}
		return false;
	}
}
