package com.artfess.bpm.plugin.task.tasknotify.helper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.artfess.base.feign.ApplicationFeignService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.artfess.base.exception.RequiredException;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.jms.JmsActor;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.ArrayUtil;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.JsonUtil;
import org.springframework.stereotype.Service;

import com.artfess.base.jms.Notice;
import com.artfess.base.jms.NoticeMessageType;
import com.artfess.base.util.AppUtil;
import com.artfess.bpm.plugin.core.util.UserAssignRuleQueryHelper;
import com.artfess.bpm.plugin.task.tasknotify.def.model.NotifyItem;

import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.bpm.util.MessageUtil;
import com.artfess.uc.api.model.IUser;

import javax.annotation.Resource;

@Service
public class NotifyHelper {

    @Resource
    UCFeignService ucFeignService;

	public void notify(NotifyItem notifyItem,String typeKey,Map<String,Object> vars) throws Exception{
		List<IUser> pluginUsers = UserAssignRuleQueryHelper.queryUsersWithExtract(notifyItem.getUserAssignRules(),vars);
		notify(pluginUsers, notifyItem.getMsgTypes(),typeKey , vars);
	}
	
	/**
	 * 向指定的接收人发送消息
	 * @param receiverUsers
	 * @param typeKey
	 * @param recevierType
	 * @param msgTypeKeys
	 * @param templateVars 
	 * void
	 */
	public void notify(List<IUser> receiverUsers,List<String> msgTypeKeys,String typeKey,Map<String,Object> vars) throws Exception{
		IUser sender = ContextUtil.getCurrentUser();
		NoticeMessageType[] messageTypes = MessageUtil.parseNotifyType(msgTypeKeys);
		String[] receivers = MessageUtil.parseAccountOfUser(receiverUsers);
		Notice notice = new Notice();
		//设置为使用模板
		notice.setUseTemplate(true);
		notice.setMessageTypes(messageTypes);
		notice.setSender(sender.getAccount());
		notice.setTemplateType(typeKey);
		notice.setVars(vars);

        List<JsonNode> receiveUsers = new ArrayList<>();
		String[] receiverAccounts = ArrayUtil.unique(receivers);
		for(String account : receiverAccounts) {
			JsonNode receiver = ucFeignService.loadUserByUsername(account);
			if(BeanUtils.isEmpty(receiver)){
				CommonResult<JsonNode> userById = ucFeignService.getUserById(account);
				if(userById.getState()) {
					receiver = userById.getValue();
				}
			}
			if(BeanUtils.isNotEmpty(receiver)) {
				receiveUsers.add(receiver);
			}
		}

        if(receiveUsers.size()==0) {
            throw new RequiredException("The accounts of 'receivers' in 'Notice' can not find the match user, so we did not send the message.");
        }
        List<JmsActor> receives = new ArrayList<>();
        for(JsonNode user : receiveUsers) {
            receives.add(convertUserObject2JmsActor(user));
        }
        notice.setReceiver(receives);

		ApplicationFeignService applicationFeignService = AppUtil.getBean(ApplicationFeignService.class);
		applicationFeignService.sendNoticeToQueue(notice);
	}

    /**
     * 转换IUser对象为JmsActor
     * @param jsonNode
     * @return
     */
    public JmsActor convertUserObject2JmsActor(JsonNode jsonNode) {
        if(BeanUtils.isEmpty(jsonNode) || !jsonNode.isObject()) return null;
        ObjectNode userNode = (ObjectNode)jsonNode;
        String userId = JsonUtil.getString(userNode, "userId");
        String account = JsonUtil.getString(userNode, "account");
        String fullname = JsonUtil.getString(userNode, "fullname");
        String email = JsonUtil.getString(userNode, "email");
        String mobile = JsonUtil.getString(userNode, "mobile");
        String weixin = JsonUtil.getString(userNode, "weixin");
        String clientId = JsonUtil.getString(userNode, "clientId");
        String clientToken = JsonUtil.getString(userNode, "clientToken");
        return new JmsActor(userId, account, fullname, email, mobile,weixin,clientId,clientToken);
    }
}
