package com.iamberry.wechat.service.wechat;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.iamberry.wechat.core.entity.machineNumber.MachineNumber;
import com.iamberry.wechat.face.machineNumber.MachineNumberService;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.qrcode.Qrcode;
import com.iamberry.wechat.core.entity.qrcode.TemporaryQrcode;
import com.iamberry.wechat.core.entity.wx.ImageTextInfo;
import com.iamberry.wechat.core.entity.wx.ImageTextMore;
import com.iamberry.wechat.core.entity.wx.KeyWord;
import com.iamberry.wechat.core.entity.wx.MenuKeySet;
import com.iamberry.wechat.core.entity.wx.Status;
import com.iamberry.wechat.core.entity.wx.TextMessage;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.wechat.ImageTextInfoService;
import com.iamberry.wechat.face.wechat.ImageTextMoreService;
import com.iamberry.wechat.face.wechat.KeyWordService;
import com.iamberry.wechat.face.wechat.MenuKeySetService;
import com.iamberry.wechat.face.wechat.WeChatService;
import com.iamberry.wechat.service.MessageManager;
import com.iamberry.wechat.service.MessageUtil;
import com.iamberry.wechat.service.ShopUtil;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.QQFace;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.WeixinUtil;

/**
 * description ： wechat handler的核心服务类
 * @author 何秀刚
 * create date：2016年3月10日
 */
@Service
public class WeChatServiceImpl implements WeChatService {
	@Autowired
	private KeyWordService keyWordService;
	@Autowired
	private RatFWLogger inLongLogger;
	@Autowired
	private MenuKeySetService menuKeySetService;
	@Autowired
	private ImageTextInfoService imageTextInfoService;
	@Autowired
	private ImageTextMoreService imageTextMoreService;
	@Autowired
	private HomeService homeService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private WdRelationDao wdRelationDao;
	@Autowired
	private MachineNumberService machineNumberService;
	/**
	 * 处理微信发来的请求
	 * @param FromUserName
	 * @return
	 */
	@Override
	public String processRequest(String FromUserName, String ToUserName, String MsgType, String CreateTime, String Content, String Event, String Ticket, String EventKey) {
		// 创建Map，防止错误
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("FromUserName", FromUserName);
		requestMap.put("ToUserName", ToUserName);
		requestMap.put("MsgType", MsgType);
		requestMap.put("CreateTime", CreateTime);
		requestMap.put("Content", Content);
		requestMap.put("Event", Event);
		requestMap.put("Ticket", Ticket);
		requestMap.put("EventKey", EventKey);
		
		String respMessage = null;
		String fromUserName = null;// 发送方帐号(open_id)
		String toUserName = null;// 公众帐号
		long createTime = 0L;// 时间
		String msgType = null;// 消息类型
		try {
			// 默认返回的文本消息内容
			String respContent = "";
			// 解析参数
			fromUserName = requestMap.get("FromUserName");
			toUserName = requestMap.get("ToUserName");
			msgType = requestMap.get("MsgType");
			createTime = new Date().getTime();
			
			// 准备返回给微信服务器的文本消息对象
			TextMessage textMessage = new TextMessage();
			textMessage.setCreateTime(createTime);
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			
			//多客服处理
			String intxml = "<xml>"+
					"<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
					"<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" + 
					"<CreateTime>" + createTime + "</CreateTime>" +
					"<MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
			/*
			 * 各种消息处理 
			 */
			if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){	//文本消息
				String content = requestMap.get("Content").trim();//去空格
				if(!(content != null && !"".equals(content))) { // 消息为空的处理
					respContent = ResultInfo.messageIsNullResponseText;
				}

				if(QQFace.isQqFace(content)){// QQ表情的处理
					String xml = "<xml>"+
							"<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
							"<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" + 
							"<CreateTime>" + createTime + "</CreateTime>" +
							"<MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
					return xml;
				}

				if (content.startsWith(NameUtils.getConfig("PLACE_CODE_PREFIX"))) {// 激活码为“CODE”开头 则为代理商绑定	
					content = StringUtils.trim(content);
					respContent = bulidPlace(content, fromUserName);
				} else { 
					// 文本类型的消息处理
					Status status = messageHandler(content, requestMap, fromUserName, toUserName, createTime+"");
					if (status.isFlag()) {
						return respContent = status.getCountext();
					} else {
						respContent = status.getCountext();
					}
				}
			
			} else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){// 图片消息
				//转发到多客服系统
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {// 地理位置消息
				// 解析出地理位置消息
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {// 链接消息
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {// 音频消息
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				
				String eventType = requestMap.get("Event");// 事件类型
				String eventKey = requestMap.get("EventKey");
				if(eventType.equals("SCAN")){

					//扫描机器二维码返回跳转到完善信息页面
					if (eventKey.indexOf(ResultInfo.barCodePrefix) != -1) {
						Status status = scannQrcodeGiveGift(requestMap, fromUserName);
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();
					} else {
						// 已关注用户扫描二维码事件
						int flag = subUserScannQrcodeEvent(requestMap, fromUserName);
						if (flag == 1 ) {
						/*Status status = getCouponImgText(requestMap);
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();*/
							respContent = ResultInfo.subDefaultResponseText;
						} else if ( flag == 0){
							respContent = ResultInfo.subDefaultResponseText;
						} else if (flag == 4) {
							respContent = "欢迎您关注美国watero！您已享受购买水机终身优惠价3280元（普通会员销售价3680元)，并且购买即赠三年滤芯套装，快来购买吧！<a href=\"http://w.iamberry.com/watero/wechat/wxCart/goProductList\">点击购买</a>";
						} else {
							respContent = "欢迎您关注美国watero，恭喜您成为金牌会员。自己购买或者推荐朋友购买水机均将享受3280元优惠价，并免费赠送3年滤芯哦！点击菜单“分销中心-代理分销”可进入您的专属分销管理中心。";
						}
					}
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					// 订阅
					if(requestMap.get("Ticket") != null){

						//扫描机器二维码返回跳转到完善信息页面
						if (eventKey.indexOf(ResultInfo.barCodePrefix) != -1) {
							Status status = scannQrcodeSubGiveGift(requestMap, fromUserName);
							if (status.isFlag()) {
								return status.getCountext();
							}
							respContent = status.getCountext();
						} else {
							//未关注用户扫描二维码关注事件处理
							Status status = scannQRcodeSub(requestMap, fromUserName);
							if (status.isFlag()) {
								return status.getCountext();
							}
							respContent = status.getCountext();
						}
					} else {
						// 搜索公众号关注
						Status status = queryWechatSub(fromUserName, requestMap);
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();
					}
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消订阅
					
					unSubScribe(fromUserName);
					respContent = "Success";
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK) || eventType.equals("VIEW")) {
					// 自定义菜单点击事件
					Status status = clickWechatMenuEnent(requestMap);
					if (status.isFlag()) {
						return status.getCountext();
					}
					respContent = status.getCountext();
				}
			}
			// 回复文本消息
			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);
		} catch (Exception e) {
			inLongLogger.debug(this, e.getMessage());
			TextMessage textMessage = new TextMessage();
			textMessage.setCreateTime(createTime);
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setContent(ResultInfo.tryCatchDefaultResponseText);
			respMessage = MessageUtil.textMessageToXml(textMessage);
		}
		return respMessage;
	}

	/**
	 * 扫码进入赠送礼品信息页面（已关注）
	 * @param requestMap
	 */
	public Status scannQrcodeGiveGift(Map<String, String> requestMap, String fromUserName) {
		Status status = new Status();
		String senceid = requestMap.get("EventKey");//场景值
		senceid = senceid.replaceAll(ResultInfo.barCodePrefix,"");//替换标识前的字符串
        String str = bindingMachine(senceid, fromUserName);
        status.setCountext(str);
		status.setFlag(false);
		return status;
	}

	/**
	 * 扫码进入赠送礼品信息页面（未关注）
	 * @param requestMap
	 * @param fromUserName
	 */
	public Status scannQrcodeSubGiveGift(Map<String, String> requestMap, String fromUserName) {
		//赋值&更新数据
		Status status = new Status();
		Member member = refreshUserInfo(fromUserName);
		String senceid = requestMap.get("EventKey");//场景值
		senceid = senceid.replaceAll(ResultInfo.barCodePrefix,"");//替换标识前的字符串
		String str = bindingMachine(senceid, fromUserName);
		status.setCountext(str);
		status.setFlag(false);
		return status;
	}

	/**
	 * 上海tooth扫码绑定机器关系
	 * @param senceid
	 * @param fromUserName
	 * @return
	 */
	public String bindingMachine(String senceid, String fromUserName) {
		StringBuilder str = new StringBuilder();
		MachineNumber machineNumber = new MachineNumber();
		machineNumber.setNumberBarcode(senceid);
		//分页查询机器编号集合
		List<MachineNumber> numberList = machineNumberService.listMachineNumber(machineNumber);
		if (numberList == null && numberList.size() == 0) {
			str.append("该机器条形码有误，请重新扫描!");
		}
		MachineNumber machine = numberList.get(0);
		if (machine.getNumberOpenId() != null && !"".equals(machine.getNumberOpenId())) {
			str.append("该机器已绑定用户，不能重复绑定!");
			return str.toString();
		} else {
			machineNumber.setNumberOpenId(fromUserName);
			boolean flag = machineNumberService.updateNumber(machineNumber);
			if (flag) {
                str.append("Hi!欢迎您关注WaterO，现在完善购买信息，即赠送美国WaterO滤芯T1一个、美国WaterO滤芯T2一个，<a href=\"");
                str.append(NameUtils.getConfig("WECHAT_GO_PERSONAL_INFORMATION"));
                str.append(machine.getNumberId());
                str.append("\">立即完善>></a>");
				return str.toString();
			} else {
				str.append("绑定机器失败,请重新操作!");
				return str.toString();
			}
		}
	}
	
	/**
	 * 绑定代理商信息（激活 微信openid绑定商户）
	 * @param content
	 * @param fromUserName
	 * @return
	 */
	public String bulidPlace(String content, String fromUserName) {
		// 判断此代理商信息
		PlaceInfo info = placeInfoService.selectOnePlaceInfoByCode(content);
		if (info == null) {
			return ResultInfo.initPorxyErrorByCodeError;
		}
		if (info.getOpenid() != null) {
			return ResultInfo.initPorxyErrorByUseInit;
		}
		// 校验当前用户在商户表中 是否已经绑定过关系	<每个微信只能绑定一个商户>
		Integer palceId = placeInfoService.selectPlaceIdByOpenId(fromUserName);
		if (palceId != null) {
			return ResultInfo.initPorxyErrorByUseBuild;
		}
		
		// 绑定关系
		info.setOpenid(fromUserName);
		int count = placeInfoService.updateOpenidById(info);
		if (count < 1) {
			return ResultInfo.initPorxyErrorByCodeWrong;
		}
		
		// 判断当前代理商是否能产生二维码
		if (!(info.getHasQrcode()==1)) { // 不支持删除二维码的角色，到此为止
			String ruleStr = info.getRoleName();
			StringBuffer buffer = new StringBuffer(ResultInfo.initPorxySuccessPrifix);
			buffer.append(ruleStr).append(ResultInfo.initPorxySuccessSuffix);
			return buffer.toString();
		}
		String ruleStr = info.getRoleName();
		StringBuffer buffer = new StringBuffer(ResultInfo.initPorxySuccessPrifix);
		buffer.append(ruleStr).append(ResultInfo.initPorxySuccessSuffix);
		return buffer.toString();
		/*// 产生二维码
		QrcodeResult qrcodeResult = qrcodeService.applyPlaceQrcodeUrl(info.getId());
		if (qrcodeResult.isSuccess()) {
			String ruleStr = info.getRoleName();
			StringBuffer buffer = new StringBuffer(ResultInfo.initPorxySuccessPrifix);
			buffer.append(ruleStr).append(ResultInfo.initPorxySuccessSuffix);
			return buffer.toString();
		} else {
			return qrcodeResult.getQroceUrl();
		}*/
	}
	
	/**
	 * 已关注用户扫描二维码事件
	 * @param requestMap
	 * @param fromUserName
	 * @throws Exception 
	 */
	public int subUserScannQrcodeEvent(Map<String, String> requestMap, String fromUserName) throws Exception {
		String senceid = requestMap.get("EventKey");//已经关注用户扫描二维码触发事件：获取二维码场景值
		Member member = refreshUserInfo(fromUserName);
		// 是否更新数据
		boolean isNew = false;
		//没绑关系、没有来源、上线是代理商时的id为空、没有微代理层关系 时， 则可以绑定用户关系 
		if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1) {	
			isNew = true; 
		}
	/*	QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
		inLongLogger.info("为用户-->" + fromUserName + ",生成二维码:" + qr.getQroceUrl());*/
        return buildRelation(member, senceid, isNew);	//为用户绑定关系 
	}
	
	/**
	 * 未关注用户扫描二维码关注
	 * @param requestMap
	 * @param fromUserName
	 * @return
	 * @throws Exception
	 */
	public Status scannQRcodeSub(Map<String, String> requestMap, String fromUserName) throws Exception {
		// 解析场景值
		String senceid = requestMap.get("EventKey");//场景值
		//赋值&更新数据
		Member member = refreshUserInfo(fromUserName);
		// 是否更新数据
		boolean isNew = false;
	
		if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1) {
				isNew = true; 
		} 
		int isMessage = buildRelation(member, senceid, isNew);
		Status status = new Status();
        if (isMessage == 1) {//成功绑定关系 则推送优惠券图文
        	/*status = getCouponImgText(requestMap);*/
        	status.setFlag(false);
    		status.setCountext(ResultInfo.subDefaultResponseText);
        }else if(isMessage == 0){
        	/*  用在分享二维码页面  从未关注公众号的用户B，通过点击用户A分享的二维码，关系就已经绑定，但是仍需要推送优惠券图文
        	 * 故 判断A初始从未关注，而关系已经绑定，则推送优惠券 */
        	/*if(oldStatus == 1){
        		status = getCouponImgText(requestMap);
        	}else{
        		status.setFlag(false);
        		status.setCountext(ResultInfo.subDefaultResponseText);
        	}*/
        	status.setFlag(false);
    		status.setCountext(ResultInfo.subDefaultResponseText);
        } else if (isMessage == 4) {
        	status.setFlag(false);
        	status.setCountext("欢迎您关注美国watero！您已享受购买水机终身优惠价3280元（普通会员销售价3680元)，并且购买即赠三年滤芯套装，快来购买吧！<a href=\"http://w.iamberry.com/watero/wechat/wxCart/goProductList\">点击购买</a>");
		} else{
        	status.setFlag(false);
    		status.setCountext("欢迎您关注美国watero，恭喜您成为金牌会员。自己购买或者推荐朋友购买水机均将享受3280元优惠价，并免费赠送3年滤芯哦！点击菜单“分销中心-代理分销”可进入您的专属分销管理中心。");
        }
        /*QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
        inLongLogger.info("为用户-->" + fromUserName + ",生成二维码:" + qr.getQroceUrl());*/
		//返回数据
		return status;
	}

	/**
	 * 用户自己搜索微信公众号关注
	 * @param fromUserName
	 * @param requestMap
	 * @return
	 * @throws Exception 
	 */
	public Status queryWechatSub(String fromUserName, Map<String, String> requestMap) throws Exception {
		//赋值&更新数据
		refreshUserInfo(fromUserName);
		//memberDao.updateUserFlagByOpenId(fromUserName);		// 绑定用户关系
		/*QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
		if(qr != null ){
			inLongLogger.info("为用户-->" + fromUserName + ",生成二维结果成功！");
		}*/
		
		Status status = new Status();
		String respContent = ResultInfo.subDefaultResponseText;
		status.setCountext(respContent);
		return status;
	}
	
	/**
	 * 更新微信用户信息
	 * 2016年11月17日
	 */
	private Member refreshUserInfo(String openId){
		JSONObject jsonObject = WeixinUtil.getUserInfo(openId);
		String sex = jsonObject.getString("sex");//值为1时是男性，值为2时是女性，值为0时是未知
		String city = jsonObject.getString("city");
		String country = jsonObject.getString("country");
		String province = jsonObject.getString("province");
		String nickname = jsonObject.getString("nickname");
		String headimgurl = jsonObject.getString("headimgurl");
		try {
			nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			nickname = "";
			inLongLogger.error(this, e.getMessage());
		}
		Member member = homeService.selectMemberInfoByOpenId(openId);
		//赋值&更新会员数据
		if (member != null && member.getUserId() != null) {
			member.setUserOpenid(openId);
			member.setUserNickname(nickname);
			member.setUserSex(Integer.parseInt(sex));
			member.setUserAddr(country+"-"+province+"-"+city);
			member.setUserHead(headimgurl);
			//userIsBought 暂存旧的关注状态
			member.setUserIsBought(member.getUserStatus() == null ? 1 : member.getUserStatus());
			member.setUserStatus(2); // 已关注
			homeService.updateWechatMemberInfoByByOpenid(member);
		} else {
			member = new Member();
			member.setUserNickname(nickname);
			member.setUserSex(Integer.parseInt(sex));
			member.setUserAddr(country+"-"+province+"-"+city);
			member.setUserHead(headimgurl);
			member.setUserStatus(2); // 已关注
			member.setUserOpenid(openId);
			member.setUserIsBought(1);
			member.setUserIsFlag(1);
			homeService.insertMemberInfo(member);
		}
		return member;
	}

	//	/**
//	 * 用户自己关注事件 返回数据
//	 * @param requestMap
//	 * @return
//	 * @throws Exception
//	 */
//	public Status subUserReturnString(Map<String, String> requestMap) throws Exception {
//		Status status = new Status();
//		List<ImageTextMore> imagetextMoreList = null;
//		int couponImgTextId = systemService.selectOneShopRuleById(113).getRuleNum().intValue(); //100元优惠券图文id
//		ImageTextInfo imageTextInfo = imageTextInfoService.findImageTextInfoById(Long.valueOf(couponImgTextId));
//		String respContent = ResultInfo.subDefaultResponseText;
//		if(imageTextInfo != null) {
//			//判断是否多图文
//			if("2".equals(imageTextInfo.getImageTextType())){
//				imagetextMoreList = imageTextMoreService.findImageTextmore(imageTextInfo.getImageTextNo());
//			}
//			try {
//				respContent = MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			status.setFlag(true);
//		}else{
//			status.setFlag(false);
//		}
//		status.setCountext(respContent);
//		return status;
//	}
	

	/**
	 * 绑定关系
	 * @param member	当前用户
	 * @param senceid	二维码场景值	
	 * 					两种：1.代理商的永久二维码 <格式:qrscene_QR***>	
	 * 						2.微代理的临时二维码 <格式:qrscene_***>
	 * 					其中 *** 是二维码表（或是临时二维码表）id
	 * @param isNew		是否更新关系
	 * @return	0：默认	1：绑定成功		2：金牌会员	
	 */
	public int buildRelation(Member member,String senceid,boolean isNew){
		
		int isMessage = 0;
		if (senceid != null && senceid.length() >= 8) {
			senceid = senceid.substring(8, senceid.length());//qrscene_
		}
		
		String regex = "^\\d+$";
        if(senceid.matches(regex)) {
        	//微代理的二维码
        	Integer qrcodeId = Integer.parseInt(senceid);
        	TemporaryQrcode tempQrcoude = temporaryQrcodeService.getTempQrcodeById(qrcodeId);
        	if (isNew) {
        		// 此二维码对应关系存在，并且openid不能是自己
	        	if (tempQrcoude != null && !tempQrcoude.getQrOpenid().equals(member.getUserOpenid())) {
	        		member.setUserResType(2);
	        		//二维码用户信息
	        		Member dealer = homeService.selectMemberInfoByOpenId(tempQrcoude.getQrOpenid());

	        		boolean isFlag = ShopUtil.isFlag(dealer);	//二维码用户可否发展下线
	        		if(isFlag){	//绑定关系
	        			if(dealer.getUserDealers() != null){
	        				member.setUserDealers(dealer.getUserDealers()); // 代理商关系直接copy
	        			}
	        			if(dealer.getTemplateId() != null){
	        				member.setTemplateId(dealer.getTemplateId());
	        			}
	        			homeService.updateUserResAndTypeByOpenid(member); // 更新
	        			wdRelationDao.insertWdrelation(dealer,member);		//插入微代理层关系
	        			isMessage = 0;
	        		}
	        	}
        	}
        }else{	
        	// 线下代理
        	Integer qrcodeId = Integer.parseInt(senceid.replaceAll("QR", ""));
        	Qrcode qrcode = qrcodeService.selectQrcodeByQrcodeId(qrcodeId);
        	
        	inLongLogger.info("线下代理:" + isNew + ", qrcodeID:" + qrcodeId + "," + qrcode);
        	// 无论邦不绑定关系，都要对二维码的扫描次数设置
    		if (isNew) {
	        	// 此二维码对应关系存在，并且openid不能是自己
    			
	        	if (qrcode != null) {
 
	        		// 查询发展金牌会员的placeID
	        		int goldPlaceId = systemService.selectOneShopRuleById(206).getRuleNum().intValue();
	        		
	        		// PlaceID
	        		int placeId = Integer.parseInt(qrcode.getQrcodeReplaceOpenid());
	        		
	        		inLongLogger.info("goldPlace:" + goldPlaceId + ", " + placeId + " " + (goldPlaceId ==placeId));
	        		
	        		// 判断是否为特定的金牌会员
	        		if (placeId == goldPlaceId) {
	        			// 是发展金牌会员的特定placeID
	        			
	        			// 判断是否为发展金牌会员的时间
	        			try {
							long activeEndDate = DateTimeUtil.pasreStringToLong("2016-12-30 23:59:59", null);
							if (new Date().getTime() <= activeEndDate) {
								// 判断当前OpenID是否绑定已经成为金牌会员
			        			Integer info = placeInfoMapper.selectPlaceIdByOpenId(member.getUserOpenid());
			        			
			        			inLongLogger.info("当前用户:" + info);
			        			if (info == null) {
			        				/**可以成为金牌会员,并且金牌会员一旦生成，不允许改变*/
			        				inLongLogger.info("可以成为金牌会员");

				        			// 生成金牌会员、包括二维码
			        				PlaceInfo parentInfo = placeInfoMapper.selectPlaceInfobyId(Integer.parseInt(qrcode.getQrcodeReplaceOpenid()));
			        				PlaceInfo nowPlaceInfo = new PlaceInfo();
			        				nowPlaceInfo.setName("IAMBERRY");
			        				nowPlaceInfo.setUserName("金牌会员");
			        				nowPlaceInfo.setAddr("深圳市");
			        				nowPlaceInfo.setTel("18000000000");
				        			nowPlaceInfo.setAmount(0);
				        			// 自动激活当前用户
				        			nowPlaceInfo.setOpenid(member.getUserOpenid());
				        			nowPlaceInfo.setRoleId(systemService.selectOneShopRuleById(207).getRuleNum().intValue());
				        			nowPlaceInfo.setPlacePid(placeId);
				        			nowPlaceInfo.setHasQrcode(2);
				        			nowPlaceInfo.setTemplateId(parentInfo.getTemplateId());
				        			nowPlaceInfo.setAreaName("深圳");
				        			nowPlaceInfo.setPlaceInfoStus(1);
				        			placeInfoService.addOne(nowPlaceInfo);
				        			if (nowPlaceInfo.getId() != 0) {
				        				qrcodeService.applyPlaceQrcodeUrl(nowPlaceInfo.getId());
				        			}
				        			
				        			// 自动将当前用户绑定到金牌会员下
			        				member.setUserDealers(nowPlaceInfo.getPlaceIds()); // bilud顶级代理商关系
		        					member.setTemplateId(nowPlaceInfo.getTemplateId());
		        					member.setUserResType(3);
		    	        			member.setUserIsFlag(2);			// 关系绑定
					        		homeService.updateUserResAndTypeByOpenid(member); // 更新
					        		// 清除wd的数据
					        		wdRelationDao.updateStatus(member.getUserOpenid());
					        		isMessage = 3;
			        			}
							}
						} catch (ParseException e) {}
	        		} else {
	        			// 不是发展特定的金牌会员的placeID
	        			PlaceInfo info = placeInfoMapper.selectPlaceInfobyId(Integer.parseInt(qrcode.getQrcodeReplaceOpenid()));
	        			if (info.getHasQrcode() == 2) {
	        				if (info != null) {
		        				member.setUserDealers(info.getPlaceIds()); // bilud顶级代理商关系
	        					member.setTemplateId(info.getTemplateId());
		        			}
		        			member.setUserResType(3);
			        		homeService.updateUserResAndTypeByOpenid(member); // 更新
			        		
			        		// 清除wd的数据
			        		wdRelationDao.updateStatus(member.getUserOpenid());
			        		if(info.getTemplateId() != 23){//美容师下线不回复优惠券
		        				isMessage = 0;
		        			}
			        		
			        		// 如果是金牌会员的二维码，那么回复：欢迎您关注美国watero！您已享受购买水机终身优惠价3280元（普通会员销售价3680元)，并且购买即赠三年滤芯套装，快来购买吧！点击购买
			        		if (info.getRoleId() == systemService.selectOneShopRuleById(207).getRuleNum().intValue()) {
			        			isMessage = 4;
			        		}
	        			}
	        		}
	        	}
    		}
        	qrcode.setQrcodeId(qrcodeId);
        	qrcode.setQrcodeScannNum(1);
        	qrcode.setQrcodeSubNum(1);
    		qrcodeService.updateQRcodeScannNumAndSubNum(qrcode);
        }
		return isMessage;
	}
	/**
	 * 用户取消关注时的事件
	 * @param fromUserName
	 */
	public void unSubScribe(String fromUserName) {
		try {
			// 更新用户状态
			homeService.updateMemberStatusByOpenId(fromUserName);
			// 更新渠道二维码信息,如果有
			// qrcodeService.updateQRcodeStatusByUserOpenid(fromUserName);
			// 待确认，是否微代理一旦取消关注就自动回收微代理的资格?
		} catch (Exception e) {
			inLongLogger.error(this, e.getMessage());
		}
	}
	
	/**
	 * 自定义菜单点击事件
	 * @param requestMap
	 * @return
	 * @throws Exception 
	 */
	public Status clickWechatMenuEnent(Map<String, String> requestMap) throws Exception {
		Status status = new Status();
		// 事件KEY值,与创建自定义菜单时指定的KEY值对应 
        String eventKey = requestMap.get("EventKey").trim();
        //保存消息记录
		MenuKeySet menuKeySet = menuKeySetService.selectByPubNoAndKeyWord(NameUtils.getConfig("pubNo"), eventKey);
		String respContent = ResultInfo.subDefaultResponseText;
		if(menuKeySet != null){
			if("1".equals(menuKeySet.getReType())){	   //文本
				respContent = menuKeySet.getRefText();
			}else if("2".equals(menuKeySet.getReType())){//图文
				List<ImageTextMore> imagetextMoreList = null;
				ImageTextInfo imageTextInfo = imageTextInfoService.findImageTextInfoById(Long.parseLong(menuKeySet.getRefImageTextId()));
				if(imageTextInfo != null) {
					//判断是否多图文
					if("2".equals(imageTextInfo.getImageTextType())){
						imagetextMoreList = imageTextMoreService.findImageTextmore(imageTextInfo.getImageTextNo());
					}
					status.setFlag(true);
					respContent = MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
				}
			}
		}
		status.setCountext(respContent);
		return status;
	}
	/**
	 * 获取优惠券图文 扫码绑定关系后推送给用户
	 * @param requestMap
	 * @return
	 */
//	private Status getCouponImgText(Map<String, String> requestMap){
//		Status status = new Status();
//		List<ImageTextMore> imagetextMoreList = null;
//		int couponImgTextId = 0;
//		couponImgTextId = systemService.selectOneShopRuleById(110).getRuleNum().intValue(); //400元商品图文id
//		ImageTextInfo imageTextInfo = imageTextInfoService.findImageTextInfoById(Long.valueOf(couponImgTextId));
//		String respContent = ResultInfo.subDefaultResponseText;
//		if(imageTextInfo != null) {
//			//判断是否多图文
//			if("2".equals(imageTextInfo.getImageTextType())){
//				imagetextMoreList = imageTextMoreService.findImageTextmore(imageTextInfo.getImageTextNo());
//			}
//			try {
//				respContent = MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			status.setFlag(true);
//		}else{
//			status.setFlag(false);
//		}
//		status.setCountext(respContent);
//		return status;
//	}
	/***
	 * 消息处理
	 * @param content
	 * @param requestMap
	 * @param fromUserName
	 * @param toUserName
	 * @param createTime
	 * @return
	 */
	public Status messageHandler(String content, Map<String, String> requestMap, String fromUserName, String toUserName, String createTime) {
		Status status = new Status();
		status.setCountext(ResultInfo.messageDefaultResponseText);
		status.setFlag(true);
		KeyWord keyword = keyWordService.getByKeyWord(content);//是否命中关键字
		if(keyword != null) {//判断是否存在关键字回复
			if("1".equals(keyword.getReType())) {//文本
				status.setCountext(keyword.getRefText());
				status.setFlag(false);
			} else if("2".equals(keyword.getReType())){//图文
				List<ImageTextMore> imagetextMoreList = null;
				ImageTextInfo imageTextInfo = imageTextInfoService.findImageTextInfoById(keyword.getRefImageTextId());
				if(imageTextInfo != null) {//判断是否为多图文
					if("2".equals(imageTextInfo.getImageTextType())){//判断是否多图文
						imagetextMoreList = imageTextMoreService.findImageTextmore(imageTextInfo.getImageTextNo());
					}
					try {
						String s = MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
						status.setCountext(s);
						status.setFlag(true);
						return status;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} else { // 如果没有命中关键字，直接接入到客服
			String xml = "<xml>"+
					"<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
					"<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" + 
					"<CreateTime>" + createTime + "</CreateTime>" +
					"<MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>";
			status.setCountext(xml);
			status.setFlag(true);
		}
		return status;
	}
	
}