package com.yonge.toolset.thirdparty.message;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.yonge.toolset.thirdparty.entity.SysEmail;
import com.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.thirdparty.message.provider.*;

@Component
public class MessageSenderPluginContext implements ApplicationContextAware {

	public SysEmail sysEmail = new SysEmail();

	public enum MessageSender {

		JIGUANG("PUSH"), MOXINGTONG("SMS"), SHIYUAN("SMS"), YIMEI("SMS"), AWSMS("SMS"), EMAIL("EMAIL");

		/**
		 * 发送模式（SMS,PUSH,EMAIL）
		 */
		private String sendMode;

		private MessageSender(String sendMode) {
			this.sendMode = sendMode;
		}

		public String getSendMode() {
			return sendMode;
		}
	}

	private MessageSenderPlugin messageSenderPlugin;

	private ApplicationContext applicationContext;

	private final Map<String, String> mapper = new HashMap<String, String>() {
		private static final long serialVersionUID = -3964872523891264522L;
		{
			put(StringUtils.lowerCase(JiguangPushPlugin.getName()), StringUtils.uncapitalize(JiguangPushPlugin.class.getSimpleName()));
			put(StringUtils.lowerCase(MOxintongSMSPlugin.getName()), StringUtils.uncapitalize(MOxintongSMSPlugin.class.getSimpleName()));
			put(StringUtils.lowerCase(ShiyuanSMSPlugin.getName()), StringUtils.uncapitalize(ShiyuanSMSPlugin.class.getSimpleName()));
			put(StringUtils.lowerCase(YimeiSmsPlugin.getName()), StringUtils.uncapitalize(YimeiSmsPlugin.class.getSimpleName()));
			put(StringUtils.lowerCase(AwSmsPlugin.getName()), StringUtils.uncapitalize(AwSmsPlugin.class.getSimpleName()));
			put(StringUtils.lowerCase(CommEmailPlugin.getName()), StringUtils.uncapitalize(CommEmailPlugin.class.getSimpleName()));
		}
	};

	/**
	 * 发送消息至目的地
	 * @param messageSender 消息发送方
	 * @param subject 消息主题
	 * @param content 消息内容
	 * @param receiver 收件人
	 * @param url 链接地址
	 * @return 是否发送成功
	 * @throws IOException
	 */
	public String send(MessageSender messageSender, String subject, String content, String receiver, String url, String jpushType,String sound,String channelId) throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(5);
		CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
			messageSenderPlugin = getMessageSenderPlugin(messageSender);
			try {
				messageSenderPlugin.send(subject, content, receiver, url, jpushType,sound,channelId);
			} catch (Exception e) {
				e.printStackTrace();
				return e.getMessage();
			}
			return "";
		},executor);
		executor.shutdown();
		return future.join();
	}

	/**
	 * 批量发送消息至目的地
	 * @param messageSender 消息发送方
	 * @param subject 消息主题
	 * @param content 消息内容
	 * @param receivers 收件人列表
	 * @param url 链接地址
	 * @return 是否发送成功
	 * @throws IOException
	 */
	public String batchSend(MessageSender messageSender, String subject, String content, String[] receivers, String url, String jpushType,String sound,String channelId) throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(5);
		CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
			messageSenderPlugin = getMessageSenderPlugin(messageSender);
			try {
				messageSenderPlugin.batchSend(subject, content, receivers, url, jpushType,sound,channelId);
			} catch (Exception e) {
				e.printStackTrace();
				return e.getMessage();
			}
			return "";
		},executor);
		executor.shutdown();
		return future.join();
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	private MessageSenderPlugin getMessageSenderPlugin(MessageSender messageSender) {
		String beanId = mapper.get(StringUtils.lowerCase(messageSender.name()));

		if (StringUtils.isBlank(beanId)) {
			throw new ThirdpartyException("消息提供方:{}不存在", beanId);
		}
		MessageSenderPlugin messageSenderPlugin = applicationContext.getBean(beanId, MessageSenderPlugin.class);
		injectEmailAttribute(messageSenderPlugin);
		return messageSenderPlugin;
	}

	private void injectEmailAttribute(MessageSenderPlugin messageSenderPlugin) {
		if (messageSenderPlugin.getClass() == CommEmailPlugin.class) {
			CommEmailPlugin commEmailPlugin = (CommEmailPlugin) messageSenderPlugin;
			commEmailPlugin.setHostName(sysEmail.getHostName());
			commEmailPlugin.setSmtpPort(sysEmail.getSmtpPort());
			commEmailPlugin.setUserName(sysEmail.getUserName());
			commEmailPlugin.setPassword(sysEmail.getPassword());
			commEmailPlugin.setFrom(sysEmail.getFrom());
			commEmailPlugin.setFromName(sysEmail.getFromName());
		}
	}

}
