package cn.myapps.runtime.notice;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;

import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.common.auth.IUser;
import cn.myapps.common.util.SequenceException;
import cn.myapps.common.util.SpringApplicationContextUtil;
import cn.myapps.conf.NoticeApi;
import cn.myapps.runtime.dynaform.document.model.IDocument;
import cn.myapps.runtime.workflow.notification.ejb.SendMode;
import cn.myapps.util.ProcessFactory;
import cn.myapps.util.sequence.Sequence;
import net.sf.json.JSONObject;

/**
 * 站内短信发送模版
 * 
 * @author Tom
 * 
 */
public class PersonalMessageMode implements SendMode {

//	private static final Logger LOG = LoggerFactory.getLogger(PersonalMessageMode.class);

	/**
	 * 根据文档获取链接
	 * 
	 * @param document
	 * @return
	 */
	private String getLinkParamsByDocument(IDocument document) {

		JSONObject handleUrl = new JSONObject();
		handleUrl.put("_docid", document.getId());
		handleUrl.put("_formid", document.getFormid());
		handleUrl.put("application", document.getApplicationid());
		handleUrl.put("mode", "personalMessageMode");
		return handleUrl.toString();
	}

	/**
	 * 根据文档获取事项提醒标题
	 * 
	 * @param document
	 * @return
	 */
	private String getContentsByCondition(IDocument document, String subject, int subjectType, String summary,
			IUser user) {

		StringBuffer sb = new StringBuffer();
		// 主题 //
		sb.append("<span class='notice_type' type='" + subjectType + "'></span>");
		// 处理人
		if (user != null) {
			sb.append("<span class='notice_actor'>" + user.getName() + "</span>");
		} else {
			sb.append("<span class='notice_actor'></span>");
		}
		// 动作
//		sb.append("<span class='notice_flowType'>" + flowTypeMessage + "</span>");
		// 审批单
		sb.append("<span class='notice_flow'>审批单</span>");
		String formname;
		try {
			formname = document.getFormname();
			// 备注
			sb.append("<span class='notice_summary'>"
//					+ (StringUtil.isBlank(form.getDiscription()) ? form.getName() : form.getDiscription()) + "-"
					+ formname + "-" + summary + "</span>");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	@Override
	public boolean send(String subject, int subjectType, String summary, IUser responsible, IDocument document,
			IUser webUser) {
		try {
			Notice notice = new Notice();
			notice.setId(Sequence.getSequence());
			notice.setSubjectType(subjectType);
			notice.setCreateTime(new Date());
			notice.setDomainid(document.getDomainid());
			String linkParams = getLinkParamsByDocument(document);
			notice.setLinkParams(linkParams);// 链接
			String warpSummary = getContentsByCondition(document, subject, subjectType, summary, webUser);
//		String module = document.getForm().getModule().getName();
			String module = document.getFormname();
			notice.setModule(module); // 功能模块
			notice.setRead(false);
			notice.setSummary(warpSummary);
			notice.setToUserId(responsible.getId());

			JSONObject content = new JSONObject();
			content.put("content", summary);
			content.put("event", subject);
			content.put("type", subjectType);
			notice.setContent(content.toString());

			NoticeApi noticeApi = SpringApplicationContextUtil.getBean(NoticeApi.class);
			noticeApi.createNotice(notice);
			Notification notification = new Notification();

			notification.setSender(webUser.getName());
			notification.setSenderId(webUser.getId());
			notification.setReceiverId(responsible.getId());
			notification.setMessageId(notice.getId());
			notification.setMessageType(notice.getSubjectType());
			notification.setModule(module);
			notification.setLinkParams(notice.getLinkParams());
			notification.setDomainid(webUser.getDomainid());
			notification.setSummary(summary);
			notification.setCreateTime(notice.getCreateTime());

			noticeApi.createNotification(notification);
		} catch (SequenceException e) {
			e.printStackTrace();
		}

		return true;
	}

	public void sendMessageToUser(String userId, String receiverid,String title, String content) throws Exception{
		NoticeApi noticeApi = SpringApplicationContextUtil.getBean(NoticeApi.class);
		noticeApi.createMessage(receiverid,title,content,userId);
	}

	public void sendMessageToDeptUser(String departmentid, String title,String content, String userId) throws Exception{
		UserProcess us = (UserProcess) ProcessFactory.createProcess(UserProcess.class);
		UserVO user = (UserVO) us.doView(userId);
		HashSet<String> receiverId =  new HashSet<String>();
		HashSet<String> receiverDeptId =  new HashSet<String>();
		Collection<UserVO> _users = us.queryByDepartment(departmentid);
		NoticeApi noticeApi = SpringApplicationContextUtil.getBean(NoticeApi.class);
		receiverDeptId.add(departmentid);
		//添加用户
		for(UserVO u : _users){
			receiverId.add(u.getId());
		}

		String _receiverId = "";
		String _receiverDeptId = "";

		if(!receiverId.isEmpty()){
			_receiverId = receiverId.toString().substring(1, receiverId.toString().length()-1);
			_receiverDeptId = receiverDeptId.toString().substring(1, receiverDeptId.toString().length()-1);
		}else{
			_receiverId = "";
			_receiverDeptId = "";
		}

		noticeApi.createMessage(_receiverId,title,content,userId);
	}

	public void sendMessageToRoleUser(String roleId, String title,String content, String userId) throws Exception{
		UserProcess us = (UserProcess) ProcessFactory.createProcess(UserProcess.class);
		UserVO user = (UserVO) us.doView(userId);
		HashSet<String> receiverId =  new HashSet<String>();
		HashSet<String> receiverDeptId =  new HashSet<String>();
		Collection<UserVO> _users = us.queryByRole(roleId);
		NoticeApi noticeApi = SpringApplicationContextUtil.getBean(NoticeApi.class);
		//添加用户
		for(UserVO u : _users){
			receiverId.add(u.getId());
		}

		String _receiverId = "";

		if(!receiverId.isEmpty()){
			_receiverId = receiverId.toString().substring(1, receiverId.toString().length()-1);
		}else{
			_receiverId = "";
		}

		noticeApi.createMessage(_receiverId,title,content,userId);
	}
}
