package org.fouram.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.fouram.core.base.service.BaseService;
import org.fouram.core.plugin.weixin.cp.util.WXCpMessageUtil;
import org.fouram.core.plugin.weixin.cp.util.WXCpUserUtil;
import org.fouram.core.util.DateUtil;
import org.fouram.core.util.LoggerUtil;
import org.fouram.entity.SapUser;
import org.fouram.enums.DelFlagEnum;
import org.fouram.enums.SapUserResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import me.chanjar.weixin.cp.bean.WxCpUser;

@Service
public class SyncSapUserToWxService extends BaseService {

	@Autowired
	private SapUserService sapUserService;

	@Transactional
	public void execute() throws Exception {
		// 1.更新所有数据无效
		sapUserService.updateAllDelFlag(DelFlagEnum.UNABLE.getCode());
		// 2.保存SAP用户数据
		sapUserService.saveOrUpdateSapUsers();
		// 3.根据SAP用户数据情况更新result字段
		sapUserService.updateResultByCondition();
		// 4.更新用户头像
		this.updateAvatar();
		// 5.发送禁用企业微信账号信息
		this.sendQuitUserMsg();

		// 部分数据插入微信未成功，处理数据后，重新插入
		List<SapUser> unSyncSapUsers = sapUserService.selectUnSyncList();
		LoggerUtil.info("部分未成功插入数据->" + unSyncSapUsers.size());
		for (SapUser sapUser : unSyncSapUsers) {
			sapUserService.updateSyncWxResult(sapUser.getPersonId());
		}
		LoggerUtil.info("同步结束->" + DateUtil.getTime());
	}

	// 更新用户头像
	private void updateAvatar() throws Exception {
		List<SapUser> successUsers = sapUserService.selectListByResult(SapUserResultEnum.SUCCESS.getCode());
		for (SapUser sapUser : successUsers) {
			WxCpUser user = WXCpUserUtil.getById(sapUser.getPersonId());
			if (user != null && StringUtils.isNotBlank(user.getAvatar())) {
				sapUser.setAvatar(user.getAvatar());
				sapUserService.updateAvatar(sapUser);
			}
		}
	}

	// 发送禁用企业微信账号信息
	private void sendQuitUserMsg() throws Exception {
		List<SapUser> unableSapUsers = sapUserService.selectListByDelFlag(DelFlagEnum.UNABLE.getCode());
		if (unableSapUsers.size() > 0) {
			WXCpMessageUtil.sendQuitUserMsg("离职用户" + unableSapUsers.size() + "个，请确认");
		}
	}
}
