package com.yifu.cloud.plus.v1.yifu.social.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysUsersVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.social.config.WxConfig;
import com.yifu.cloud.plus.v1.yifu.social.mapper.TSocialWarnMapper;
import com.yifu.cloud.plus.v1.yifu.social.service.TSocialWarnService;
import com.yifu.cloud.plus.v1.yifu.social.vo.TSocialAlert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author hgw
 * @description 派单办理失败的，推送企微
 * @date 2025-8-1 15:23:16
 */
@Service
public class TSocialWarnServiceImpl extends ServiceImpl<TSocialWarnMapper, TSocialAlert> implements TSocialWarnService {
	@Autowired
	private UpmsDaprUtils upmsDaprUtils;
	@Autowired
	private WxConfig wxConfig;

	/**
	 * @Description: 10点推送企微消息——派单办理失败
	 * @Author: hgw
	 * @Date: 2025/8/1 15:11
	 * @return: void
	 **/
	@Override
	public void pushSocialAlertToWx() {
		try {
			// TODO - 逻辑待产品梳理清楚，sql待完善
			List<TSocialAlert> list = baseMapper.getSocialAlertToWx();
			String userIds;
			if (Common.isNotKong(list)) {
				userIds = list.stream().map(TSocialAlert::getCreateBy).distinct().collect(Collectors.joining(","));
				// 获取在用账号信息
				Map<String, SysUser> inUseUserMap = this.getInUseUserByIds(userIds);
				if (inUseUserMap != null && !inUseUserMap.isEmpty()) {
					// 离职人员
					StringBuilder liZhiUserName = new StringBuilder();
					SysUser user;
					Map<String, String> pushMap = new HashMap<>();
					StringBuilder content;
					for (TSocialAlert vo : list) {
						user = inUseUserMap.get(vo.getCreateBy());
						if (user == null || Common.isEmpty(user.getWxMessage())) {
							if (Common.isNotNull(liZhiUserName)) {
								liZhiUserName.append("、");
							}
							liZhiUserName.append(vo.getCreateName());
						} else {
							content = new StringBuilder("当前存在");
							if (vo.getSocialNum() > 0) {
								content.append("社保派单失败数量：").append(vo.getSocialNum());
								if (vo.getFundNum() > 0) {
									content.append("，公积金派单失败数量：").append(vo.getFundNum());
								}
							} else if (vo.getFundNum() > 0) {
								content.append("公积金派单失败数量：").append(vo.getFundNum());
							}
							content.append("<br/>请及时至HRO系统进行处理。");
							pushMap.put(user.getWxMessage(), content.toString());
						}
					}
					// 离职的人，发给陈红：
					if (Common.isNotNull(liZhiUserName)) {
						// 陈红的 user.getWxMessage()
						pushMap.put("66870fa57d72637233f81f1e0b26311e", "申请人" + liZhiUserName
								+ "状态异常，当前存在社保派单失败、公积金派单失败。请及时至HRO系统进行处理。");
					}
					//开始推送信息到企业微信
					if (Common.isNotKong(pushMap)) {
						pushMap.forEach((k, v) -> {
							sendMessageToWx(k, v);
						});
					}
				}
			}
		} catch (Exception e) {
			log.error("推送社保办理失败信息到企业微信异常", e);
		}
	}

	/**
	 * @Description 获取在用账号信息
	 * @Date 2025-8-1 11:50:06
	 **/
	private Map<String, SysUser> getInUseUserByIds(String userIds) {
		Map<String, SysUser> userMap = null;
		if (Common.isNotKong(userIds)) {
			R<SysUsersVo> res = upmsDaprUtils.getInUseUserByIds(userIds);
			if (Common.isNotNull(res) && Common.isNotNull(res.getData()) && Common.isNotNull(res.getData().getUserList())) {
				userMap = res.getData().getUserList();
			}
		}
		return userMap;
	}

	//发送企业微信待办
	private void sendMessageToWx(String useruserWx, String content) {
		if (Common.isEmpty(useruserWx) || Common.isEmpty(content)) {
			return;
		}
		StringBuilder sendUser = null;
		if (Common.isNotKong(useruserWx)) {
			sendUser = new StringBuilder(useruserWx);
		}
		if (sendUser != null) {
			RestTemplate restTemplate = new RestTemplate();
			Map<String, Object> requestMap = new HashMap<>();
			Map<String, Object> textcard = new HashMap<>();
			textcard.put("title", "派单办理失败提醒");
			textcard.put("url", String.format(SecurityConstants.WX_GET_MESSAGE_AUTH_URL, wxConfig.getCorpid(), wxConfig.getDomainName() + "/auth/oauth/wxLogin", "66"));
			textcard.put("description", content);
			requestMap.put("touser", sendUser);
			requestMap.put("agentid", wxConfig.getAgentid());
			requestMap.put("msgtype", "textcard");
			requestMap.put("textcard", textcard);
			// 必须加上header说明
			if (!wxConfig.sendTextCard(restTemplate, requestMap)) {
				wxConfig.sendTextCard(restTemplate, requestMap);
			}
		}
	}
}