package com.iamberry.wechat.service.wechat;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.iamberry.wechat.tools.WeixinUtil;
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.QrcodeResult;
import com.iamberry.wechat.core.entity.qrcode.TemporaryQrcode;
import com.iamberry.wechat.core.entity.relationship.WdRelation;
import com.iamberry.wechat.core.entity.wx.FirstJoinKey;
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.member.MemberService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.face.relationship.WdRelationService;
import com.iamberry.wechat.face.wechat.FirstJoinKeyService;
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.home.dao.HomeServiceDao;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.member.dao.MemberDao;
import com.iamberry.wechat.service.qrcode.dao.QrcodeDao;
import com.iamberry.wechat.service.relationship.Dao.WdRelationDao;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.QQFace;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * description ： wechat handler的核心服务类
 * @author 何秀刚
 * create date：2016年3月10日
 */
@Service
public class WeChatServiceImpl implements WeChatService {
	
	@Autowired
	private KeyWordService keyWordService;
	

	private WeixinUtil weixinUtil;
	
	@Autowired
	private RatFWLogger inLongLogger;
	
	@Autowired
	private MenuKeySetService menuKeySetService;
	
	@Autowired
	private ImageTextInfoService imageTextInfoService;
	
	@Autowired
	private ImageTextMoreService imageTextMoreService;
	
	@Autowired
	private FirstJoinKeyService firstJoinKeyService;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private QrcodeService qrcodeService;

	@Autowired
	private QrcodeDao qrcodeDao;

	@Autowired
	private HomeServiceDao homeServiceDao;
	
	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	
	@Autowired
	private PlaceInfoService placeInfoService;
	
	@Autowired
	private MemberDao memberDao;
	
	@Autowired
	private DealerRelationService dealerRelationService;
	
	@Autowired
	private WdRelationService wdRelationService;
	
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private WdRelationDao wdRelationDao;
	/**
	 * 处理微信发来的请求
	 * @param request
	 * @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.PLACE_CODE_PREFIX)) {// 代理商绑定	

					content = StringUtils.trim(content);
					
					respContent = bulidPlace(content, fromUserName);
//System.out.println("代理商绑定-回复信息：" + respContent);
					
				} else { 
					// 文本类型的消息处理
					Status status = messageHandler(content, requestMap, fromUserName, toUserName, createTime+"");
//System.out.println("文本消息-回复信息：" + status.getCountext());
					if (status.isFlag()) {
						return respContent = status.getCountext();
					} else {
						respContent = status.getCountext();
					}
				}
			
			} else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){// 图片消息
				//respContent = ResultInfo.imageMessageResponseText;
				//转发到多客服系统
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {// 地理位置消息
				
				// 解析出地理位置消息
//				String x = requestMap.get("Location_X");
//				String y = requestMap.get("Location_Y");
//				String location = x + "," + y;
				//respContent = ResultInfo.locationMessageResponseText;
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {// 链接消息
				
				//respContent = ResultInfo.linkMessageResponseText;
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {// 音频消息
				
				//respContent = ResultInfo.videoMessageResponseText;
				return intxml;
			} else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				
				String eventType = requestMap.get("Event");// 事件类型
				String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
				if(eventType.equals("SCAN")){ // 已关注用户扫描二维码事件
					boolean flag = subUserScannQrcodeEvent(requestMap, fromUserName);
					if (flag) {
						Status status = getCouponImgText(requestMap);
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();
					} else {
						respContent = ResultInfo.subDefaultResponseText;
					}
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
					
					if(requestMap.get("Ticket") != null){
						//扫描二维码关注事件处理
						Status status = scannQRcodeSub(requestMap, fromUserName);
//System.out.println(" 用户扫描二维码-回复信息：" + status.getCountext());
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();
					} else {
						// 搜索公众号关注
						Status status = queryWechatSub(fromUserName, requestMap);
//System.out.println("搜索公众号关注-回复信息：" + status.getCountext());
						if (status.isFlag()) {
							return status.getCountext();
						}
						respContent = status.getCountext();
					}
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅
					
					unSubScribe(fromUserName);
					respContent = "Success";
//System.out.println("取消关注-回复信息：" + respContent);
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK) || eventType.equals("VIEW")) {
					
					// 自定义菜单点击事件
					Status status = clickWechatMenuEnent(requestMap);
					if (status.isFlag()) {
						return status.getCountext();
					}
					respContent = status.getCountext();
//System.out.println("自定义菜单点击事件-回复信息：" + respContent);
				}
			}
			// 回复文本消息
			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);
		} catch (Exception e) {
			e.printStackTrace();
			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);
		}
//System.out.println("start-回复信息：" + respMessage);
		return respMessage;
	}
	
	/**
	 * 已关注用户扫描二维码事件
	 * @param requestMap
	 * @param fromUserName
	 * @throws Exception 
	 */
	public boolean subUserScannQrcodeEvent(Map<String, String> requestMap, String fromUserName) throws Exception {
		String senceid = requestMap.get("EventKey");//已经关注用户扫描二维码触发事件：获取场景值
		// 获取用户信息
		JSONObject jsonObject = weixinUtil.getUserInfo(fromUserName);
		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");
		nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
		Member member = homeService.selectMemberInfoByOpenId(fromUserName);
		// 是否更新数据
		boolean isNew = false;
		//赋值&更新会员数据
		if (member != null && member.getUserId() != null) {
			member.setUserOpenid(fromUserName);
			member.setUserNickname(nickname);
			member.setUserSex(Integer.parseInt(sex));
			member.setUserAddr(country+"-"+province+"-"+city);
			member.setUserHead(headimgurl);
			member.setUserStatus(2); // 已关注
			homeService.updateWechatMemberInfoByByOpenid(member);
			//没绑关系、没有来源、上线是代理商时的id为空、没有微代理层关系 时， 则可以绑定用户关系 
			if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1
					&& member.getUserResType().intValue() == 1 && member.getUserDealers() == null) {
				WdRelation selectWdr = new WdRelation();
				selectWdr.setOpenid(member.getUserOpenid());
				List<WdRelation> list = wdRelationDao.getWdRelationByWd(selectWdr);
				if(list != null && list.size() < 1){	//若已经存在关系则不绑定
					isNew = true;
				}
			}
		} 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(fromUserName);
			homeService.insertMemberInfo(member);
			isNew = true; // 更新
		}
		QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
		inLongLogger.info("为用户-->" + member.getUserNickname() 
				+ ",openid:" + fromUserName + ",生成二维结果:" + qr.getQroceUrl());
        return buildRelation(member, senceid, isNew);	//为用户绑定关系
	}
	
	/**
	 * 用户关注事件返回数据
	 * @param requestMap
	 * @return
	 * @throws Exception
	 */
	public Status subUserReturnString(Map<String, String> requestMap) throws Exception {
		Status status = new Status();
		FirstJoinKey firstJoinKey = firstJoinKeyService.getBywxpublicNO(NameUtils.pubNo);
		String respContent = ResultInfo.subDefaultResponseText;
		if(firstJoinKey != null) {
			if(firstJoinKey.getReMessageType().equals("2")) { // 图文信息
				//根据ID获取图文信息
				List<ImageTextMore> imagetextMoreList = null;
				ImageTextInfo imageTextInfo = imageTextInfoService.findImageTextInfoById(firstJoinKey.getImageTextNo());
				if(imageTextInfo != null) {//判断是否为多图文
					if("2".equals(imageTextInfo.getImageTextType())){//判断是否多图文
						imagetextMoreList = imageTextMoreService.findImageTextmore(imageTextInfo.getImageTextNo());
					}
					respContent = MessageManager.getImageTextInfo(requestMap, imageTextInfo, imagetextMoreList);
					status.setFlag(true);
					status.setCountext(respContent);
					return status;
				}
			} else {
				// 非图文，回复文字内容
				respContent = firstJoinKey.getReText();
			}
		}
		status.setCountext(respContent);
		return status;
	}
	
	/**
	 * 未关注用户扫描二维码关注
	 * @param requestMap
	 * @param fromUserName
	 * @return
	 * @throws Exception
	 */
	public Status scannQRcodeSub(Map<String, String> requestMap, String fromUserName) throws Exception {
		// 解析场景值
		String senceid = requestMap.get("EventKey");//场景值
//		inLongLogger.info("-----------场景值-----inLongLogger.info------------>>" + senceid);
		
		// 第一步：获取用户信息
		JSONObject jsonObject = weixinUtil.getUserInfo(fromUserName);
		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");
		nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
		//赋值&更新数据
		Member member = homeService.selectMemberInfoByOpenId(fromUserName);
		int oldStatus = member.getUserStatus().intValue(); 
		// 是否更新数据
		boolean isNew = false;
		//赋值&更新会员数据
		if (member != null && member.getUserId() != null) {
			member.setUserOpenid(fromUserName);
			member.setUserNickname(nickname);
			member.setUserSex(Integer.parseInt(sex));
			member.setUserAddr(country+"-"+province+"-"+city);
			member.setUserHead(headimgurl);
			member.setUserStatus(2); // 已关注
			homeService.updateWechatMemberInfoByByOpenid(member);
			//没绑关系、没有来源、上线是代理商时的id为空、没有微代理层关系 时， 则可以绑定用户关系 
			if (member.getUserIsFlag() != null && member.getUserIsFlag().intValue() == 1
					&& member.getUserResType().intValue() == 1 && member.getUserDealers() == null) {
				WdRelation selectWdr = new WdRelation();
				selectWdr.setOpenid(member.getUserOpenid());
				List<WdRelation> list = wdRelationDao.getWdRelationByWd(selectWdr);
				if(list != null && list.size() < 1){	//若已经存在关系则不绑定
					isNew = true;
				}
			}
		} 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(fromUserName);
			homeService.insertMemberInfo(member);
			isNew = true; // 更新
		}
		
		boolean isMessage = buildRelation(member, senceid,isNew);
		Status status = new Status();
        if (isMessage) {
        	status = getCouponImgText(requestMap);
        }else{
        	if(oldStatus == 1){
        		status = getCouponImgText(requestMap);
        	}else{
        		status.setFlag(false);
        		status.setCountext(ResultInfo.subDefaultResponseText);
        	}
        }
        QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
        inLongLogger.info("为用户-->" + member.getUserNickname() 
				+ ",openid:" + fromUserName + ",生成二维结果:" + qr.getQroceUrl());
		//返回数据
		return status;
	}
	
	/**
	 * 绑定关系
	 * @param member	当前用户
	 * @param senceid	二维码场景值	
	 * 					两种：1.代理商的永久二维码 <格式:qrscene_QR***>	
	 * 						2.微代理的临时二维码 <格式:qrscene_***>
	 * 					其中 *** 是二维码表（或是临时二维码表）id
	 * @param isNew		是否更新关系
	 * @return
	 */
	public boolean buildRelation(Member member,String senceid,boolean isNew){
		boolean isMessage = false;
		if (senceid != null && senceid.length() >= 8) {
			senceid = senceid.substring(8, senceid.length());//qrscene_
		}
		
		String regex = "^\\d+$";
//		inLongLogger.info("--------- senceid.matches(regex) ------>>" + senceid.matches(regex));
//		inLongLogger.info("--------- isNew ------>>" + isNew);
        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())) {
	        		boolean flag = false;
	        		member.setUserResType(2);
	        		Member dealer = homeService.selectMemberInfoByOpenId(tempQrcoude.getQrOpenid());
//	        		inLongLogger.info("-----------------------------微代理---父级信息------>>" + dealer);
	        		if(dealer.getUserDealers() != null){
	        			member.setUserDealers(dealer.getUserDealers()); // 代理商关系直接copy
	        		}
	        		if(dealer.getTemplateId() != null){
	        			member.setTemplateId(dealer.getTemplateId());
	        		}
	        		homeService.updateUserResAndTypeByOpenid(member); // 更新
	        		
	        		flag = insertWdrelation(dealer,member);		//插入微代理层关系
//	        		inLongLogger.info("----微代理的二维码-------插入微代理层关系-----flag------>>" + flag);
	        		isMessage = true;
	        	}
        	}
        }else{	// 线下代理
        	Integer qrcodeId = Integer.parseInt(senceid.replaceAll("QR", ""));
        	Qrcode qrcode = qrcodeService.selectQrcodeByQrcodeId(qrcodeId);
        	// 无论邦不绑定关系，都要对二维码的扫描次数设置
    		if (isNew) {
	        	// 此二维码对应关系存在，并且openid不能是自己
	        	if (qrcode != null && !qrcode.getQrcodeReplaceOpenid().equals(member.getUserOpenid())) {
//	        		boolean flag = false;
        			PlaceInfo info = placeInfoMapper.selectPlaceInfobyId(Integer.parseInt(qrcode.getQrcodeReplaceOpenid()));
//        			inLongLogger.info("--------------info.getPlaceIds()---------------->>>>" + info.getPlaceIds());
        			if (!member.getUserOpenid().equals(info.getOpenid())) {
        				if (info != null) {
	        				member.setUserDealers(info.getPlaceIds()); // bilud顶级代理商关系
        					member.setTemplateId(info.getTemplateId());
	        			}
	        			member.setUserResType(3);
		        		homeService.updateUserResAndTypeByOpenid(member); // 更新
		        		isMessage = true;
        			}
//        			inLongLogger.info("----线下代理-------插入微代理层关系-----flag------>>" + flag);
	        	}
    		}
        	qrcode.setQrcodeId(qrcodeId);
        	qrcode.setQrcodeScannNum(1);
        	qrcode.setQrcodeSubNum(1);
    		qrcodeService.updateQRcodeScannNumAndSubNum(qrcode);
        }
        // 绑定用户关系
		memberDao.updateUserFlagByOpenId(member.getUserOpenid());
		return isMessage;
	}
	
	/**
	 * 获取优惠券图文 扫码绑定关系后推送给用户
	 * @param requestMap
	 * @return
	 */
	private Status getCouponImgText(Map<String, String> requestMap){
		Status status = new Status();
		List<ImageTextMore> imagetextMoreList = null;
		int couponImgTextId = 0;
		String openId = requestMap.get("FromUserName");
		Member member = memberService.getMemberByUserOpenId(openId);
		if (member.getUserResType() == 3) {
			couponImgTextId = systemService.selectOneShopRuleById(107).getRuleNum().intValue(); //699元商品图文id
		} else {
			couponImgTextId = systemService.selectOneShopRuleById(106).getRuleNum().intValue(); //30元优惠券图文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 fromUserName
	 * @param requestMap
	 * @return
	 * @throws Exception 
	 */
	public Status queryWechatSub(String fromUserName, Map<String, String> requestMap) throws Exception {
		// 第一步：获取用户信息
		JSONObject jsonObject = weixinUtil.getUserInfo(fromUserName);
		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");
		nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
		//赋值 & 更新数据
		//赋值&更新数据
		Member member = homeService.selectMemberInfoByOpenId(fromUserName);
		//赋值&更新会员数据
		if (member != null && member.getUserId() != null) {
			member.setUserOpenid(fromUserName);
			member.setUserNickname(nickname);
			member.setUserSex(Integer.parseInt(sex));
			member.setUserAddr(country+"-"+province+"-"+city);
			member.setUserHead(headimgurl);
			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(fromUserName);
			homeService.insertMemberInfo(member);
		}
//		memberDao.updateUserFlagByOpenId(fromUserName);		// 绑定用户关系
		QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(fromUserName);//为用户生成二维码
		inLongLogger.info("为用户-->" + member.getUserNickname() 
				+ ",openid:" + fromUserName + ",生成二维结果:" + qr.getQroceUrl());		//返回数据
		return subUserReturnString(requestMap);
	}
	
	/**
	 * 用户取消关注时的事件
	 * @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();
//        String menuId = null;
//        if("VIEW".equals(requestMap.get("Event"))){
//        	MenuInfoService menuService = new MenuInfoService();
//        	menuId = menuService.doFindByUrl(toUserName, eventKey);
//		}
        //保存消息记录
		MenuKeySet menuKeySet = menuKeySetService.selectByPubNoAndKeyWord(NameUtils.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 content
	 * @param fromUserName
	 * @return
	 */
	public String bulidPlace(String content, String fromUserName) {
		
		// 判断此代理商信息
		PlaceInfo info = homeService.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 = homeService.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);
//System.out.println("*******************************************="+ruleStr);
//System.out.println("*******************************************="+buffer);
			return buffer.toString();
		}
		
		// 产生二维码
		QrcodeResult qrcodeResult = qrcodeService.applyPlaceQrcodeUrl(info.getId());
		if (qrcodeResult.isSuccess()) {
			//String ruleStr = StaticCacheMemory.proxyRule.get(info.getPlaceRole());
			String ruleStr = info.getRoleName();
			StringBuffer buffer = new StringBuffer(ResultInfo.initPorxySuccessPrifix);
			buffer.append(ruleStr).append(ResultInfo.initPorxySuccessSuffix);
			return buffer.toString();
		} else {
			return qrcodeResult.getQroceUrl();
		}
	}
	
	/***
	 * 消息处理
	 * @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);
		
//System.out.println("文字内容:" + content);
		
		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;
	}
	
	/**
	 * 插入微代理层级	
	 * 2016年7月4日
	 * @param fatherMember
	 * @param member
	 */
	public boolean insertWdrelation(Member fatherMember,Member member){
		if(fatherMember == null || StringUtils.isEmpty(fatherMember.getUserOpenid())
				|| member == null || StringUtils.isEmpty(member.getUserOpenid())){
			return false;
		}
		WdRelation selectWdr = new WdRelation();
		selectWdr.setOpenid(member.getUserOpenid());
		selectWdr.setWdFirst(fatherMember.getUserId());
		List<WdRelation> list = wdRelationService.getWdRelationByWd(selectWdr);
		if(list != null && list.size() > 0){	//若已经存在改上级的关系 则不添加
			return false;
		}
		WdRelation newWdr = new WdRelation();
		newWdr.setOpenid(member.getUserOpenid());
		inLongLogger.info("----------父级userinfo---------->>>" + fatherMember.toString());
		WdRelation fatherWR = wdRelationService.getWdRelationByOpenid(fatherMember.getUserOpenid());
		newWdr.setWdFirst(fatherMember.getUserId());
		newWdr.setWdCount(1);
		if(fatherWR != null && fatherWR.getWdFirst() != null){
			newWdr.setWdSecond(fatherWR.getWdFirst());
			newWdr.setWdCount(2);
		}
		if(fatherWR != null && fatherWR.getWdSecond() != null){
			newWdr.setWdThird(fatherWR.getWdSecond());
			newWdr.setWdCount(3);
		}
		if(fatherWR != null && fatherWR.getWdThird() != null){
			newWdr.setWdFourth(fatherWR.getWdThird());
			newWdr.setWdCount(4);
		}
		
		Integer i = wdRelationService.insertWdRelation(newWdr);
		inLongLogger.info("-------------------Integer i = wdRelationService.insertWdRelation(wr)-----i->>" + i);
		if(i > 0 ){
			return true;
		}else{
			return false;
		}
	}
}