package com.palmnest.service.wechat.impl;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.InMessage;
import com.palmnest.application.bean.NewsOutMessage;
import com.palmnest.application.bean.OutMessage;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.EmojiFilterUtils;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.dao.estateserve.ScMenueventDao;
import com.palmnest.dao.estateserve.ScReceiverecordDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.model.estateserve.*;
import com.palmnest.service.AsynchronousDataService;
import com.palmnest.service.Executable;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.EventMsgManager;
import com.palmnest.service.wechat.ReplayContentManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 接收事件消息处理
 *
 * @author yubing
 * @date 2015-04-07
 */
@Slf4j
@Component("eventMsgManager")
public class EventMsgManagerImpl implements EventMsgManager {


	private String webUrl = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");

	@Autowired
	private PublicNoManager         publicNoManager;
	@Autowired
	private PropertyManager         propertyManager;
	@Autowired
	private ReplayContentManager    replayContentManager;
	@Autowired
	private WeChatApiManager        weChatApiManager;
	@Autowired
	private ScMenueventDao          scMenueventDao;
	@Autowired
	private ScReceiverecordDao      scReceiverecordDao;
	@Autowired
	private ScWxuserDao             scWxuserDao;
	//线程异步处理数据Serveice
	@Autowired
	private AsynchronousDataService asynchronousDataService;

	/*
	 * 关注事件
	 * (non-Javadoc)
	 * @see com.palmnest.service.wechat.EventMsgManager#subscribe(com.palmnest.bean.InMessage)
	 */
	@Override
	public OutMessage subscribe(InMessage msg) {
		//保存用户关注事件
		WxFocusevent event = new WxFocusevent();
		event.setDevelopId(msg.getToUserName());
		event.setOpenId(msg.getFromUserName());
		event.setCreateTime(new Date());
		event.setEventType(msg.getEvent());
		propertyManager.saveModel(event);

		//保存用户消息接收记录信息
		WxReceiverecord record = getScReceiverecord(msg, Constants.InFo_TYPE_EVENT);
		record.setEventType(Constants.Event_TYPE_SUBSCRIBE);
		record.setEventId(event.getId());
		propertyManager.saveModel(record);

		//保存用户微信信息
		WxUser wxuser = new WxUser();
		wxuser.setDevelopId(msg.getToUserName());
		wxuser.setOpenId(msg.getFromUserName());
		wxuser.setSubscribeTime(new Date());
		wxuser.setIsSubscribe(msg.getEvent());

		WxPublicno publicno = publicNoManager.getByDevelopId(msg.getToUserName());
		wxuser.setAccountType(publicno.getServiceType());  //根据微信开发号判断业主、员工，默认是业主

		WxUser u = scWxuserDao.getScWxuserByOpenId(wxuser.getOpenId());
		if (u != null) {
			//更新微信用户信息
			u.setSubscribeTime(wxuser.getSubscribeTime());
			u.setAccountType(wxuser.getAccountType());
			u.setIsSubscribe(wxuser.getIsSubscribe());
			scWxuserDao.updateObj(u);
		} else {
			try {
				UserInfo userinfo = weChatApiManager.getUserInfo(wxuser.getDevelopId(), wxuser.getOpenId());
				if (userinfo != null) {
					if (StringUtils.isNotEmpty(userinfo.getNickname())) {
						String nickName = StringFilter(EmojiFilterUtils
								.filterEmoji(userinfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
						wxuser.setNickName(nickName);
					} else {
						wxuser.setNickName("微信用户");
					}
					wxuser.setCity(userinfo.getCity());
					wxuser.setCountry(userinfo.getCountry());
					wxuser.setProvince(userinfo.getProvince());
					wxuser.setLanguage(userinfo.getLanguage());
					wxuser.setHeadimgUrl(userinfo.getHeadimgurl());
					wxuser.setIsBinding(Constants.UNBINDING);
					scWxuserDao.saveObj(wxuser);
				} else {
					scWxuserDao.saveObj(wxuser);
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("subscribe weChatApiManager.getUserInfo() method occur error.{}", e.getCause(), e.getMessage());
			}
		}

		//返回消息模板
		OutMessage objOut = replayContentManager.queryReplayContent(msg.getEvent(), msg.getToUserName());
		if (objOut instanceof NewsOutMessage) {
			NewsOutMessage out = (NewsOutMessage) objOut;
			for (int i = 0; i < out.getArticles().size(); i++) {
				String url = out.getArticles().get(i).getUrl();
				if (url.contains("?")) {
					url = url + "&openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
				} else {
					url = url + "?openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
				}
				out.getArticles().get(i).setUrl(url);
			}
			return out;
		} else {
			return objOut;
		}
	}

	/*
	 *  取消关注
	 *  (non-Javadoc)
	 * @see com.palmnest.service.wechat.EventMsgManager#unsubscribe(com.palmnest.bean.InMessage)
	 */
	@Override
	public OutMessage unsubscribe(InMessage msg) {
		//保存用户取消关注事件
		final WxFocusevent event = new WxFocusevent();
		event.setDevelopId(msg.getToUserName());
		event.setOpenId(msg.getFromUserName());
		event.setCreateTime(new Date());
		event.setEventType(msg.getEvent());
		//更新用户微信信息
		final WxUser wxuser = new WxUser();
		wxuser.setDevelopId(msg.getToUserName());
		wxuser.setOpenId(msg.getFromUserName());
		wxuser.setIsSubscribe(msg.getEvent());
		wxuser.setUnSubscribeTime(new Date());
		//保存用户消息接收记录信息
		final WxReceiverecord record = getScReceiverecord(msg, Constants.InFo_TYPE_EVENT);
		record.setEventType(Constants.Event_TYPE_SUBSCRIBE);

		asynchronousDataService.store(new Executable() {
			@Override
			public Void execute() {
				propertyManager.saveModel(event);
				record.setEventId(event.getId());
				propertyManager.saveModel(record);

				WxUser u = scWxuserDao.getScWxuserByOpenId(wxuser.getOpenId());
				if (u != null) {
					u.setIsSubscribe(wxuser.getIsSubscribe());
					u.setUnSubscribeTime(new Date());
					scWxuserDao.updateObj(u);
				}
				return null;
			}
		});
		return null;
	}

	@Override
	public OutMessage SCAN(InMessage msg) {

		return null;
	}

	/*
	 * 获取用户地理位置
	 */
	@Override
	public OutMessage LOCATION(InMessage msg) {
		WxPublicno publicno = publicNoManager.getByDevelopId(msg.getToUserName());
		//客户 (更新客户经纬度地理位置信息)
		if (Constants.AccountType_USER.equals(publicno.getServiceType())) {
			/*AppUser appuser=appUserDao.getAppUser(msg.getToUserName(), msg.getFromUserName());
			if(appuser!=null){
				//appUserDao.updateObj(appuser);
			}*/
		}
		return null;
	}

	/**
	 * click 事件处理逻辑
	 */
	@Override
	public OutMessage CLICK(InMessage msg) {
		OutMessage out = null;
		//eventKey 包含V1003 放行，不进行绑定验证
		if (msg.isBindFlag()) {
			WxMenuevent event = new WxMenuevent();
			event.setDevelopId(msg.getToUserName());
			event.setOpenId(msg.getFromUserName());
			event.setCreateTime(new Date());
			event.setEventType(msg.getEvent());
			event.setEventKey(msg.getEventKey());
			//保存用户消息接收记录信息
			WxReceiverecord record = getScReceiverecord(msg, Constants.InFo_TYPE_EVENT);
			record.setEventType(Constants.Event_TYPE_MENU);
			
			/*asynchronousDataService.store(new Executable() {
				@Override
				public Void execute() {
					ScMenuevent new_event=scMenueventDao.saveMenuevent(event);
					record.setEventId(new_event.getFocusEventId());
					scReceiverecordDao.saveReceiverecord(record);
					
					//员工-我要接单
					if("VEMP100_1".equals(event.getEventKey())){
						//TODO 更改员工状态
						EstateStaff staff=appUserDao.getEstateStaff(event.getDevelopId(),event.getOpenId());
						if(staff!=null){
							log.info("VEMP100_1,staff's id:"+staff.getStaffId());
							staff.setJobStatus(1);
							appUserDao.updateModel(staff);
							
							//TODO 调用获取工单接口 
							orderDistributeManager.saveSystemPushStaffTask(null);
						}
					}
					//员工-暂不接单
					else if("VEMP100_2".equals(event.getEventKey())){
						//TODO 更改员工状态
						EstateStaff staff=appUserDao.getEstateStaff(event.getDevelopId(),event.getOpenId());
						staff.setJobStatus(0);
						appUserDao.updateModel(staff);;
					}
					return null;
				}
			});*/
			WxMenuevent new_event = scMenueventDao.saveMenuevent(event);
			record.setEventId(new_event.getId());
			scReceiverecordDao.saveReceiverecord(record);

			//员工-我要接单
			if ("VEMP100_1".equals(event.getEventKey())) {
				//TODO 更改员工状态
			}
			//员工-暂不接单
			else if ("VEMP100_2".equals(event.getEventKey())) {
				//TODO 更改员工状态
			}

			out = replayContentManager.queryReplayContent(msg.getEventKey(), msg.getToUserName());
			if (out instanceof NewsOutMessage) {
				NewsOutMessage newsOut = (NewsOutMessage) out;
				for (int i = 0; i < newsOut.getArticles().size(); i++) {
					String url = newsOut.getArticles().get(i).getUrl();
					if (url.contains("?")) {
						url = url + "&openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
					} else {
						url = url + "?openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
					}
					newsOut.getArticles().get(i).setUrl(url);
				}
				return newsOut;
			}
		} else {
			//未绑定
			try {
				//msg.setEventKey("unbind");
				out = replayContentManager.queryReplayContent(msg.getEventKey(), msg.getToUserName());
				if (out instanceof NewsOutMessage) {
					NewsOutMessage outObj = (NewsOutMessage) out;
					for (int i = 0; i < outObj.getArticles().size(); i++) {
						String url = outObj.getArticles().get(i).getUrl();
						if (url.contains("?")) {
							url = url + "&openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
						} else {
							url = url + "?openId=" + msg.getFromUserName() + "&developId=" + msg.getToUserName();
						}
						outObj.getArticles().get(i).setUrl(url);
					}
					return outObj;
				}
			} catch (Exception e) {
				log.error("CLICK occour error. {} ", e, e.getMessage());
			}
		}
		return out;
	}

	@Override
	public String VIEW(InMessage msg) {
		return null;
	}

	@Override
	public String TEMPLATESENDJOBFINISH(InMessage msg) {

		return null;
	}

	public WxReceiverecord getScReceiverecord(InMessage msg, String infoType) {
		//保存用户消息接收记录信息
		WxReceiverecord record = new WxReceiverecord();
		record.setDevelopId(msg.getToUserName());
		record.setOpenId(msg.getFromUserName());
		record.setInfoType(infoType);
		record.setCreateTime(new Date());
		return record;
	}

	public static String StringFilter(String str) {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String  regEx  = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p      = Pattern.compile(regEx);
		Matcher m      = p.matcher(str);
		String  result = m.replaceAll("").trim();
		System.out.println("result:" + result);
		return result;
	}
}
