package org.security.flow.business.delegate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.security.desk.feign.IXYunClient;
import org.security.desk.xyun.res.MsgResponseBody;
import org.security.flow.core.enums.CandidateTypeEnum;
import org.security.system.user.feign.IUserClient;
import org.security.system.user.vo.UserVO;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.core.tool.utils.StringPool;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: qxqx
 * @Create: 2022/9/15
 * @Description:
 */
@Slf4j
@Data
@Component
public class NoticeDelegate implements JavaDelegate {

	private Expression noticeType;
	private Expression msg;

	@Override
	public void execute(DelegateExecution execution) {
		log.info(">>>>>>>>>>>> 知会消息开始");
		String typeStr;
		try {
			typeStr = (String) noticeType.getValue(execution);
		} catch (NullPointerException e) {
			log.warn(">>>>>>>>>>>> 未设置知会角色");
			return;
			// log.error(">>>>>>>>>>>> 未设置知会角色");
			// throw new ServiceException("未设置知会角色！");
		}
		String message;
		try {
			message = (String) msg.getValue(execution);
		} catch (NullPointerException e) {
			log.warn(">>>>>>>>>>>> 未设置知会消息！");
			return;
			// log.error(">>>>>>>>>>>> 未设置知会消息！");
			// throw new ServiceException("未设置知会消息！");
		}
		log.info(">>>>>>>>>>>> 知会角色为：" + typeStr);
		String[] types = typeStr.split(StringPool.COMMA);
		if (types.length < 1) {
			log.warn(">>>>>>>>>>>> 未设置知会角色");
			return;
			// throw new ServiceException("未设置知会角色");
		}
		for (int i = 0; i < types.length; i++) {
			if (!CandidateTypeEnum.getValues().contains(types[i])) {
				log.warn(">>>>>>>>>>>> 不支持的知会人配置：" + types[i] + "");
				return;
				// throw new ServiceException("不支持的知会人配置：" + types[i] + "");
			}
		}

		Long userId = AuthUtil.getUserId();
		if (Func.isNull(userId)) {
			log.warn(">>>>>>>>>>>> 获取当前登录用户失败");
			// throw new ServiceException("获取当前登录用户失败");
		}
		List<UserVO> noticeUsers = new ArrayList<>();
		IUserClient userClient = SpringUtil.getBean(IUserClient.class);
		for (int i = 0; i < types.length; i++) {
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.HEAD_LEADER) {
				noticeUsers.addAll(getUsers(userClient.headLeaders(userId), CandidateTypeEnum.HEAD_LEADER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.HEAD_SEC_LEADER) {
				noticeUsers.addAll(getUsers(userClient.headSecLeaders(userId), CandidateTypeEnum.HEAD_SEC_LEADER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.HEAD_SAFER) {
				noticeUsers.addAll(getUsers(userClient.headSafers(userId), CandidateTypeEnum.HEAD_SAFER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.BRANCH_LEADER) {
				noticeUsers.addAll(getUsers(userClient.branchLeaders(userId), CandidateTypeEnum.BRANCH_LEADER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.BRANCH_SAFER) {
				noticeUsers.addAll(getUsers(userClient.branchSafers(userId), CandidateTypeEnum.BRANCH_SAFER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.SUB_LEADER) {
				noticeUsers.addAll(getUsers(userClient.subLeaders(userId), CandidateTypeEnum.SUB_LEADER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.SUB_SAFER) {
				noticeUsers.addAll(getUsers(userClient.subSafers(userId), CandidateTypeEnum.SUB_SAFER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.DEPT_LEADER) {
				noticeUsers.addAll(getUsers(userClient.deptLeaders(userId), CandidateTypeEnum.DEPT_LEADER.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.HEAD_SEC_CENTER_ALL) {
				noticeUsers.addAll(getUsers(userClient.headSecCenterAll(), CandidateTypeEnum.HEAD_SEC_CENTER_ALL.getName()));
			}
			if (CandidateTypeEnum.fromValue(types[i]) == CandidateTypeEnum.BRANCH_SEC_CENTER_ALL) {
				noticeUsers.addAll(getUsers(userClient.branchSecCenterAll(), CandidateTypeEnum.BRANCH_SEC_CENTER_ALL.getName()));
			}
		}

		String userStr = StringUtils.join(noticeUsers.stream().map(UserVO::getCode).collect(Collectors.toList()), ",");
		IXYunClient xYunClient = SpringUtil.getBean(IXYunClient.class);
		R<MsgResponseBody> msgRes = xYunClient.sendMessageToXYun(userStr, message);
		if (!msgRes.isSuccess()) {
			log.warn(">>>>>>>>>>>> 知会失败，请稍后再试！");
			return;
			// throw new ServiceException("知会失败，请稍后再试！");
		}
		MsgResponseBody data = msgRes.getData();
		execution.setVariable(execution.getCurrentActivityId(), data.getSourceMsgId());
	}

	private List<UserVO> getUsers(R<List<UserVO>> res, String userTypeMsg) {
		if (!res.isSuccess()) {
			log.warn(">>>>>>>>>>>> 查找用户类型“" + userTypeMsg + "”失败！");
			return new ArrayList<>();
			// throw new ServiceException("查找用户类型“" + userTypeMsg + "”失败！");
		}
		log.info(">>>>>>>>>>>> 获取到用户类型为“" + userTypeMsg + "”的以下用户");
		log.info(">>>>>>>>>>>> " + StringUtils.join(res.getData().stream().map(userVO -> userVO.getName()).collect(Collectors.toList()), "、"));
		return res.getData();
	}
}
