package com.wechat.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.nutz.lang.random.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wechat.common.Constants;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.MailUtil;
import com.wechat.common.utils.StringsUtils;
import com.wechat.common.utils.Time2Now;
import com.wechat.dao.AreaDao;
import com.wechat.dao.HotelUserRecievedCVRedisDao;
import com.wechat.dao.InvitationCountRedisDao;
import com.wechat.dao.MakeSureFriendshipRedisDao;
import com.wechat.dao.MdeActivityCategoryDao;
import com.wechat.dao.MdeAdImagesDao;
import com.wechat.dao.MdeDepartmentDao;
import com.wechat.dao.MdeFriendRelationDao;
import com.wechat.dao.MdeHotelCompanyDao;
import com.wechat.dao.MdeInformationDao;
import com.wechat.dao.MdeJobAdvertisedDao;
import com.wechat.dao.MdeLoginHisDao;
import com.wechat.dao.MdePositionDao;
import com.wechat.dao.MdeSchoolInfoDao;
import com.wechat.dao.MdeTrendsDao;
import com.wechat.dao.MdeUserDao;
import com.wechat.dao.TrendCommentInfoRedisDao;
import com.wechat.global.CustomException;
import com.wechat.global.base.BaseService;
import com.wechat.global.base.dao.RedisWithExpiryTimeDao;
import com.wechat.global.base.dao.RedisWithExpiryTimeIntegerDao;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeBoleInfo;
import com.wechat.model.dbEntity.MdeDepartment;
import com.wechat.model.dbEntity.MdeFriendRelation;
import com.wechat.model.dbEntity.MdeInformation;
import com.wechat.model.dbEntity.MdeJobAdvertised;
import com.wechat.model.dbEntity.MdeLoginHis;
import com.wechat.model.dbEntity.MdePosition;
import com.wechat.model.dbEntity.MdeTrends;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.dbEntity.MdeUserCv;
import com.wechat.model.dto.AdImageDto;
import com.wechat.model.dto.JobAdvertisedListDto;
import com.wechat.model.dto.TalentRetrievalDto;
import com.wechat.model.dto.UserInfoResp;
import com.wechat.model.dto.UserSimple;
import com.wechat.model.dto.WorkDateDto;
import com.wechat.model.dto.WxUserInfoDto;
import com.wechat.model.requestDto.AdReq;
import com.wechat.model.requestDto.JobCollectionReq;
import com.wechat.model.requestDto.TrendCommentInfo;
import com.wechat.model.responseDto.ContactUserInfoResp;
import com.wechat.model.responseDto.DPResp;
import com.wechat.model.responseDto.HotelInvitationInfoResp;
import com.wechat.model.responseDto.LVResp;
import com.wechat.model.responseDto.PhoneCodeResp;
import com.wechat.model.responseDto.ResultEntity;

@Service
public class CommonService extends BaseService {

	@Value("#{configProperties['hotel.recommentHotels.limitSize']}")
	private int recommentHotelsLimitSize;

	@Value("#{configProperties['hotel.similarHotels.limitSize']}")
	private int similarHotelLimitSize;

	@Value("#{configProperties['job.recommendJobs.limitSize']}")
	private int recommentJobsLimitSize;

	@Value("#{configProperties['user.maybeFriends.limitSize']}")
	private int maybeFriendsLimitSize;
	
	@Value("#{configProperties['user.superiorTalenRetrieval.limitSize']}")
	private int superiorTalenRetrievalLimit;
	
	@Value("#{configProperties['user.recommentTalenRetrieval.limitSize']}")
	private int recommentTalenRetrievalLimit;

	@Value("#{configProperties['url.base']}")
	private String domainUrl;

	@Resource
	private MdeTrendsDao trendsDao;

	@Resource
	private MdeJobAdvertisedDao jobAdvertisedDao;

	@Resource
	private MdeInformationDao informationDao;

	@Resource
	private TrendCommentInfoRedisDao trendCommentInfoRedisDao;

	@Resource
	private MdeUserDao userDao;

	@Resource
	private MdeHotelCompanyDao hotelCompanyDao;

	@Resource
	private MdeAdImagesDao adImages;

	@Resource
	private RedisWithExpiryTimeDao redisDao;
	
	@Resource
	private RedisWithExpiryTimeIntegerDao redisIntegerDao;
	
	@Autowired
	private InvitationCountRedisDao invitationCountRedisDao;

	@Resource
	private MdeFriendRelationDao friendRelationDao;

	@Resource
	private MdeDepartmentDao departmentDao;

	@Resource
	private MdePositionDao positionDao;

	@Resource
	private HotelUserRecievedCVRedisDao hotelUserRecievedCVRedisDao;

	@Resource
	private SysDictService sysDictService;

	@Resource
	private MakeSureFriendshipRedisDao friendshipRedisDao;
	
	@Resource
	private MdeSchoolInfoDao schoolInfoDao;
	
	@Resource
	private MdeActivityCategoryDao actCategoryDao;
	
	@Autowired
	private MdeLoginHisDao loginHisDao;
	
	@Autowired
	private AreaDao areaDao;

	@Autowired
	private WeiXinService weiXinService;
	
	@Resource
	private MailUtil mailUtil;
	
	@Value("#{configProperties['token.expire.minute']}")
	private int tokenExpireTime;

	/**
	 * 获取用户信息-不含openid等敏感信息
	 * @param userCode
	 * @return
	 */
	public MdeUser getUserInfo(String userCode) {
		return addDomainUrl2UserImg(userDao.getInfoById(userCode));
	}
	public MdeUser getUserInfoWithLang(String userCode,String lang) {
		MdeUser mdeuser = addDomainUrl2UserImg(userDao.getInfoByIdWithLang(userCode,lang));
		if (mdeuser.getFirstWork() != null)
		{
			long workdays = DateUtils.getDaySub(mdeuser.getFirstWork(),new Date());
			mdeuser.setExperience((int) (workdays/365));
		}
		return mdeuser;
	}
	/**
	 * 获取用户敏感字段
	 * @param userCode
	 * @return
	 */
	public MdeUser getUserSensitiveInfo(String userCode) {
		return userDao.getUserSensitiveInfo(userCode);
	}

	/**
	 * 短信码验证
	 * @param code
	 * @param userName
	 * @return
	 */
	public boolean validateCode(String code, String userName) {
		boolean flag = false;
		String vCode = redisDao.select(userName);
		if (StringsUtils.isNotEmpty(code) && StringsUtils.isEqual(code, vCode)) {
			flag = true;
		}
		return flag;
	}
	
	

	/**
	 * 获取可能认识的人 (算法, 具体功能延迟做,可先调用)
	 * @param lang 
	 * @param identityFlag 
	 * @return
	 */
	public List<MdeUser> getMaybeFriends(String userCode, String identityFlag, String lang) {
		List<MdeUser> list = null;
		// 个人用户
		if(identityFlag.equals("0")) {
			list = userDao.getMaybeFriendsOfPerson(userCode,lang, maybeFriendsLimitSize);
		}
		// 企业用户
		else {
			MdeUser user = userDao.getInfoById(userCode);
			list = userDao.getMaybeFriendsOfEnterprise(userCode,user.getName(),user.getForeignName(),lang, maybeFriendsLimitSize);
		}
		if (list == null)
			list = new ArrayList<MdeUser>();
		return addDomainUrl2UserImg(list);// 图片 拼接主域名
	}

	/**
	 * （已登录）
	 * 获取优选职位 (算法, 具体功能延迟做,可先调用) 
	 * @return
	 */
	public List<MdeJobAdvertised> getRecommentJobs() {
		return addDomainUrl2JobAdvertisedImg(jobAdvertisedDao.getRecommentJobs(recommentJobsLimitSize));
	}

	/**
	 * 获取优选职位(未登录)
	 * @param lang
	 * @return
	 */
	public List<MdeJobAdvertised> getNotLoginRecommentJobs() {
		List<MdeJobAdvertised> list = null;
		int count = jobAdvertisedDao.getNotLoginRecommentJobsCount();
		if (count > 50) {
			 list = jobAdvertisedDao.getNotLoginRecommentJobsRandJoin(recommentJobsLimitSize);
		} else {
			list = 	jobAdvertisedDao.getNotLoginRecommentJobsRand(recommentJobsLimitSize);
		}
		return list;
	}

	/**
	 * 获取推荐人才  (算法, 具体功能延迟做,可先调用)
	 * @return
	 */
	public List<MdeUser> getRecommentPeople(String userCode) {
		List<MdeUser> list = userDao.getRecommentPeople(userCode,recommentTalenRetrievalLimit);
		if (list == null)
			list = new ArrayList<MdeUser>();
		return addDomainUrl2UserImg(list);// 图片拼接主域名
	}
	
	/**
	 * 获取相似酒店 (算法, 具体功能延迟做,可先调用)
	 * @return
	 */
	public List<MdeUser> getSimilarHotel(String userCode) {
		List<MdeUser> list = userDao.getSimilarHotel(userCode, similarHotelLimitSize);
		if (list == null)
			list = new ArrayList<MdeUser>();
		return addDomainUrl2UserImg(list);
	}

	/**
	 * 获取推荐酒店 (未登录)  
	 * @param userCode
	 * @param lang
	 * @param positionRecommentHotelsPageSize
	 * @return
	 */
	public List<MdeUser> getNotLoginRecommentHotels() {
		List<MdeUser> list = null;
		int recommentHotelsCount = userDao.getRecommentHotelsCount(); // 推荐酒店数量
		if (recommentHotelsCount > 50) {
			 list = userDao.getRecommentHotelsJoinRand(recommentHotelsLimitSize);
		} else {
			list = userDao.getRecommentHotelsRand(recommentHotelsLimitSize);
		}
		return addDomainUrl2UserImg(list);
	}

	/**
	 * 获取推荐酒店 (已登录)
	 * @param userCode
	 * @param lang
	 * @param positionRecommentHotelsPageSize
	 * @return
	 */
	public List<MdeUser> getRecommentHotels() {
		List<MdeUser>list = userDao.getRecommentHotelsRand(recommentHotelsLimitSize);
		return addDomainUrl2UserImg(list);
	}
	
	/**
	 * 获取热门信息
	 * @param userCode 可为空
	 */
	public List<MdeInformation> getInformationsOfZixun(String userCode) {
		List<MdeInformation> list = null;
		if(StringsUtils.isEmpty(userCode)) {
			list = informationDao.hotInformations(Constants.INFORMATION_ZIXUN,0);
		}else {
			list = informationDao.hotInformations(Constants.INFORMATION_ZIXUN,userCode,0);
		}
		if (list == null)
			list = new ArrayList<MdeInformation>();
		return list;// 图片拼接主域名
	}
	
	/**
	 * 获取所有广告资讯
	 * @param userCode 可为空
	 * @param index 第几条数据
	 * @return
	 */
	public List<MdeInformation> getAllInformationsOfAd() {
		List<MdeInformation> list = null;
		list = informationDao.allHotInformations(Constants.INFORMATION_GUANGGAO);
		
		if (list == null)
			{list = new ArrayList<MdeInformation>();}
		return list;// 图片拼接主域名
	}
	
	/**
	 * 获取广告资讯
	 * @param userCode 可为空
	 * @param index 第几条数据
	 * @return
	 */
	public List<MdeInformation> getInformationsOfAd(String userCode,Integer index) {
		List<MdeInformation> list = null;
		if(StringsUtils.isEmpty(userCode)) {
			list = informationDao.hotInformations(Constants.INFORMATION_GUANGGAO,index-1);
		}else {
			list = informationDao.hotInformations(Constants.INFORMATION_GUANGGAO,userCode,index-1);
		}
		if (list == null)
		{
			list = new ArrayList<MdeInformation>();
		}
		return list;// 图片拼接主域名
	}
	/**
	 * 获取广告资讯
	 * @param userCode 可为空
	 * @param index 第几条数据
	 * @return
	 */
	public List<MdeInformation> getInformationsById(String userCode,String infoId) {
		List<MdeInformation> list = informationDao.getInformationsById(infoId);
		if (list == null)
			list = new ArrayList<MdeInformation>();
		return addDomainUrl2InfomationImg(list);// 图片拼接主域名
	}

	/**
	 * 评论的动态信息存入Redis数据库中
	 * @param userCode  被评论的动态信息所属人
	 * @param info 动态信息内容
	 * @param userCode 当前 评论者的userCode
	 */
	public void insertCommentedTrendsInfo(TrendCommentInfo info) {
		MdeTrends trends = trendsDao.getInfoById(info.getTrendId());
		ArrayList<TrendCommentInfo> list = trendCommentInfoRedisDao
				.selectMessageInfo("commentedTrendsInfo_" + info.getUserCode());
		if (list == null) {
			list = new ArrayList<TrendCommentInfo>();
			list.add(info);
		}else {
			Iterator<TrendCommentInfo> it = list.iterator();
			while(it.hasNext()){
				TrendCommentInfo info_ = it.next();
			    if(info_.getTrendId() == info.getTrendId()){
			        it.remove();
			    }
			}
			list.add(info);
		}
		// 补充 动态信息
		info.setTrends(trends);
		try {
			trendCommentInfoRedisDao.updateMessageInfo("commentedTrendsInfo_" + info.getUserCode(), list);
			redisDao.insert("commentedTrendsInfoCount_" + info.getUserCode(), list.size() + "");
		} catch (Exception e) {
			throw new CustomException(InfoMsg.ERROR_INSERT_REDIS_ERROR);
		}
	}

	/**
	 * 获取被好友评论的动态信息
	 * @return
	 */
	public List<TrendCommentInfo> getCommentedTrendsInfo(String userCode) {
		List<TrendCommentInfo> list = trendCommentInfoRedisDao.selectMessageInfo("commentedTrendsInfo_" + userCode);
		if (list == null)
			list = new ArrayList<TrendCommentInfo>();
		return addDomainUrl2TrendCommentInfoImg(list);// 图片拼接主域名
	}
	

	/**
	 * 获取被好友评论的动态信息 数量
	 * @return
	 */
	public int getCommentedTrendsInfoCounts(String userCode) {
		String count = redisDao.select("commentedTrendsInfoCount_" + userCode);
		if (StringsUtils.isEmpty(count))
			count = "0";
		return Integer.parseInt(count);
	}
	
	/**
	 * 清除 被好友评论的动态信息(全部)
	 * @param userCode
	 */
	public void resetCommentedTrendsInfo(String userCode) {
		trendCommentInfoRedisDao.deleteMessageInfo("commentedTrendsInfo_" + userCode);
		redisDao.delete("commentedTrendsInfoCount_" + userCode);
	}
	/**
	 * 清除 被好友评论的动态信息(单个)
	 * @param userCode
	 */
	public void resetCommentedTrendsInfo(String userCode, Long trendId) {
		ArrayList<TrendCommentInfo> list = (ArrayList<TrendCommentInfo>) getCommentedTrendsInfo(userCode);
		Iterator<TrendCommentInfo> it = list.iterator();
		while(it.hasNext()){
			TrendCommentInfo info_ = it.next();
		    if(info_.getTrendId() == trendId){
		        it.remove();
		    }
		}
		try {
			trendCommentInfoRedisDao.updateMessageInfo("commentedTrendsInfo_" + userCode, list);
			redisDao.insert("commentedTrendsInfoCount_" + userCode, list.size() + "");
		} catch (Exception e) {
			throw new CustomException(InfoMsg.ERROR_INSERT_REDIS_ERROR);
		}
	}

	/**
	 * 获取酒店(职位)邀请信息 数量
	 * @param userCode
	 * @return
	 */
	public int getRecievedHotelInvationInfoCounts(String userCode) {
		 List<String> list = invitationCountRedisDao.selectInvitationCount("invitationInfoCount_" + userCode);
		if (CollectionUtils.isNotEmpty(list)) {
			return list.size();
		}
		return 0;
	}

	/**
	 * 清除企业邀请记录
	 * @param userCode
	 * @return
	 */
	public void deleteHotelInvationInfoCounts(String userCode) {
		invitationCountRedisDao.deleteInvitation("invitationInfoCount_"+userCode);
	}
	
	/**
	 * 获取酒店(职位)邀请信息 
	 * @param userCode
	 * @return
	 */
	public ArrayList<String> getRecievedHotelInvationInfo(String userCode) {
		ArrayList<String> list = invitationCountRedisDao.selectInvitationCount("invitationInfoCount_" + userCode);
		 if (CollectionUtils.isEmpty(list)) {
			 return new ArrayList<String>();
		 }
		return list;
	}
	
	/**
	 * 更新酒店邀请用户投递简历数量
	 * @param list jobId 职位Id
	 * @param userCode
	 */
	public void updateUserInvatedCvCount(String userCode,ArrayList<String> list) {
		// 邀请数量+1 存入redis
		invitationCountRedisDao.insertInvitation("invitationInfoCount_" + userCode, list);
	}

	/**
	 * 广告位id(字典表维护)[1-PC登录页（背景）；2-PC登录页（轮播）；3-PC主页(顶部)；4-PC主页(右侧1)；5-PC主页(右侧2)；6-PC职位页（顶部）；
	 * 7-PC人才页（顶部）；8-PC职位详情页（底部）；9-PC个人中心页（顶部）；10-PC套餐页（顶部）；11-PC人脉页（左侧）；
	 * 21-手机登录页（背景)22-动态页（头部轮播))；23-职位页（头部轮播)；24-人才页（头部轮播)]
	 * @param openId 广告位 例如: Constants.PC_LOGIN_BG
	 * @return
	 */
	public List<AdImageDto> getAdImages(String typeId) {
		List<AdImageDto> list = adImages.getAdImagesByadPosition(typeId);
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setImageUrl(addDomain(list.get(i).getImageUrl()));
		}
		return list;
	}
	
	public AdImageDto getAdImage(String typeId) {
		List<AdImageDto> list = adImages.getAdImagesByadPosition(typeId);
		AdImageDto adDto = new AdImageDto();
		if(list.size() > 0) {
			adDto=list.get(0);
			adDto.setImageUrl(addDomain(adDto.getImageUrl()));
		}
		return adDto;
	}
	
	/**
	 * 记录广告浏览历史
	 * @param adReq
	 * @return
	 */
	public Integer lookOverAd(AdReq adReq) {
//		AdRecordDto dto = new AdRecordDto();
		return null;
	}
	/**
	 * 获取部门职位 说明 有几个职位没有归属到部门 全部放在其他部门里面 部门id 为 0
	 * @param lang
	 * @return
	 */
	public String getDepartmentsAndPositions(String lang) {
		List<MdeDepartment> departs = departmentDao.getDepartments();
		List<MdePosition> positions = positionDao.getAllPositions();
		List<DPResp> list = new ArrayList<DPResp>();
		for (MdeDepartment dep : departs) {
			// 遍历删除,除去已经筛选出来的职位
			Iterator<MdePosition> iterator = positions.iterator();
			DPResp res = null;
			if (dep.getDepdId() != 0) {
				if (lang.equalsIgnoreCase("en")) {
					res = new DPResp(dep.getDepdNameEn(), dep.getDepdId());
				} else {
					res = new DPResp(dep.getDepdNameCn(), dep.getDepdId());
				}
			}
			while (iterator.hasNext()) {
				MdePosition p = iterator.next();
				if (p.getDepdId() == 0 && dep.getDepdId().intValue() == p.getDepdId().intValue()) {
					if (lang.equalsIgnoreCase("en")) {
						list.add(new DPResp(p.getPositionNameEn(), p.getPositionId()));
					} else {
						list.add(new DPResp(p.getPositionNameCn(), p.getPositionId()));
					}
					iterator.remove();// 使用迭代器的删除方法删除
				} else if (dep.getDepdId().intValue() == p.getDepdId().intValue()) {
					if (lang.equalsIgnoreCase("en")) {
						res.getChildren().add(new DPResp(p.getPositionNameEn(), p.getPositionId()));
					} else {
						res.getChildren().add(new DPResp(p.getPositionNameCn(), p.getPositionId()));
					}
					iterator.remove();// 使用迭代器的删除方法删除
				}
			}
			if (dep.getDepdId() != 0) list.add(res);
		}
		// 去除结果集中 children 为空的数据
		String string = JSONArray.toJSONString(list, true);
		string = string.replaceAll("\n", "");
		string = string.replaceAll("\t", "");
		string = string.replaceAll("\"children\":\\[\\],", "");
		return string;
	}

	
	/**
	 * 获取交友信息 - 申请人信息
	 * @param userCode
	 * @return
	 */
	public List<MdeFriendRelation> getFriendInvitation(String userCode) {
		List<MdeFriendRelation> list = friendRelationDao.getBriefInfoOfFriendInvitation(userCode);
		if(list == null) {
			list = new ArrayList<MdeFriendRelation>();
		}
		return addDomainUrl2FriendRelationImg(list);
	}
	
	/**
	 * 新增 酒店收到的投递简历信息
	 * @param hotelUserCode
	 * @param collection
	 */
	public void insertHotelUserRecievedCv(String hotelUserCode, JobCollectionReq collection) {
		// 更新酒店收到的投递简历数量
		int count = getHotelUserRecievedCVCount(hotelUserCode);
		// 更新酒店收到的投递简历信息
		ArrayList<JobCollectionReq> list = getHotelUserRecievedCV(hotelUserCode);
		list.add(collection);
		try {
			hotelUserRecievedCVRedisDao.updateMessageInfo("hotelUserRecievedCV_" + hotelUserCode, list);
			redisDao.insert("hotelUserRecievedCVCount_" + hotelUserCode, (count + 1) + "");
		} catch (Exception e) {
			throw new CustomException(InfoMsg.ERROR_INSERT_REDIS_ERROR);
		}
	}
	
	
	/**
	 * 获取酒店收到的投递简历信息
	 * @param userCode
	 * @return
	 */
	public ArrayList<JobCollectionReq> getHotelUserRecievedCV(String userCode) {
		ArrayList<JobCollectionReq> recievedCvList = 
				hotelUserRecievedCVRedisDao.selectMessageInfo("hotelUserRecievedCV_" + userCode);
		if (recievedCvList == null)
			recievedCvList = new ArrayList<JobCollectionReq>();
		return addDomainUrl2JobCollectionReqImg(recievedCvList);
	}

	/**
	 * 获取酒店收到的投递简历信息数量
	 * @param userCode
	 * @return
	 */
	public int getHotelUserRecievedCVCount(String userCode) {
		String count = redisDao.select("hotelUserRecievedCVCount_" + userCode);
		if (StringsUtils.isEmpty(count))
			count = "0";
		return Integer.parseInt(count);
	}
	/**
	 * 删除酒店收到的投递简历信息
	 * @param comUserCode 企业code
	 * @return
	 */
	public void deleteUserCvMessage(int comUserCode) {
		hotelUserRecievedCVRedisDao.deleteMessageInfo("hotelUserRecievedCV_" + comUserCode);
	}

	/**
	 * 获取当前登录用户的userCode
	 * @param req
	 * @param resp
	 * @return
	 */
	public String getUserCode(HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		if (cookies == null)
			return null;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(Constants.TOKEN_USER_ID)) {
				try {
					return cookie.getValue();
				} catch (Exception e) {
					throw new CustomException(InfoMsg.ERROR_PARAM_CONVERSION_ERROR);
				}
			}
		}
		return null;
	}
	
	 /**
     * 获取当前登录用户的身份标识[0-个人；1-企业]
     * @param req
     * @param resp
     * @return
     */
    public String getIdentityFlag(HttpServletRequest req) {
        String identityFlag = getStrFromToken(req, Constants.TOKEN_IDENTITY_FLAG);
        return identityFlag;
    }
    
	 /**
     * 获取当前登录用户的注册时间
     * @param req
     * @param resp
     * @return
     */
    public Date getUserCreatDate(HttpServletRequest req) {
    	String restStr = getStrFromToken(req, Constants.TOKEN_CREATDATE);
    	Date creatDate = null;
    	if(!StringsUtils.isEmpty(restStr))
    	{
    		creatDate = DateUtils.stringToDate(restStr);
    	}

        return creatDate;
    }
    
    
	 /**
     * 从token中解密信息
     * @param req
     * @param key
     * @return
     */
    public String getStrFromToken(HttpServletRequest req, String key) {
    	String result = "";
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
        	// 获取token
            String token = null;
            for (Cookie cookie : cookies) {
                if (Constants.TOKEN_COOKIE_NAME.equals(cookie.getName())) {
                    token = cookie.getValue();
                    // jwt解密
                    DecodedJWT jwt = null;
                    try {
                        JWTVerifier verifier = JWT.require(Algorithm.HMAC512(Constants.TOKEN_KEY)).build();
                        jwt = verifier.verify(token);
                        Map<String, Claim> map = jwt.getClaims();
                        result = map.get(key).asString();
                    } catch (Exception e) {
                    	log.error("*********token解密出错！！！***************",e);
                    }
                }
            }
        }
        
        return result;
    }

	/**
	 * 获取用户语言 zh(中文) en(英文)
	 * @param req
	 * @return
	 */
	public String getLanguage(HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		String lang = Constants.LANG_CN;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equalsIgnoreCase(Constants.LANGUAGE)) {
					lang = cookie.getValue();
				}
			}
			if(StringsUtils.isEmpty(lang)) {
				lang = Constants.LANG_CN;
			}
		}
		return lang;
	}

	/**
	 * 根据类型获取字典数据
	 * @param type
	 * @return
	 */
	public List<DPResp> getDictByType(String type,String lang) {
		return sysDictService.getDictByType(type,lang);
	}
	
	public List<DPResp> getDictByType(String type,HttpServletRequest req) {
		return sysDictService.getDictByType(type,getLanguage(req));
	}
	
	/**
	 * 获取电话国际区号
	 * @param type
	 * @return
	 */
	public List<PhoneCodeResp> getPhoneCode(String type,String lang) {
		return sysDictService.getPhoneCode(type,lang);
	}
	
	/**
	 * 获取学校列表
	 * @param type
	 * @return
	 */
	public List<LVResp> getSchoolList(String lang) {
		return schoolInfoDao.getSchoolList(lang);
	}
	
	/**
	 * 保存同意好友申请
	 * @param userCode 申请人 
	 * @param userCode2 被申请人
	 */
	public void setConfirmedFriendship(String userCode, String userCode2) {
		MdeUser user = getUserInfo(userCode2);
		ArrayList<UserSimple> confirmedFriends = friendshipRedisDao.select("friendshipConfirmed_" + userCode);
		if (confirmedFriends == null) {
			confirmedFriends = new ArrayList<UserSimple>();
		}
		UserSimple us = new UserSimple();
		us.setName(user.getName());
		us.setUserCode(user.getUserCode());
		us.setHeadPortrait(user.getHeadPortrait());
		us.setDate(DateUtils.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		confirmedFriends.add(us);
		friendshipRedisDao.insert("friendshipConfirmed_" + userCode, confirmedFriends);
	}

	/**
	 * 获取同意好友申请
	 * @param userCode
	 * @return
	 */
	public ArrayList<UserSimple> getConfirmedFriendship(String userCode) {
		return friendshipRedisDao.select("friendshipConfirmed_" + userCode);
	}
	/**
	 * 删除 同意好友申请
	 * @param currentUserCode 当前操作者code
	 * @param userCode 
	 */
	public void deleteComfirmedFriendship(String currentUserCode, String userCode) {
		ArrayList<UserSimple> list = getConfirmedFriendship(currentUserCode);
		Iterator<UserSimple> it = list.iterator();
		while(it.hasNext()){
			UserSimple info_ = it.next();
		    if(info_.getUserCode().equals(userCode) ){
		        it.remove();
		    }
		}
		try {
			friendshipRedisDao.insert("friendshipConfirmed_" + currentUserCode, list);
		} catch (Exception e) {
			throw new CustomException(InfoMsg.ERROR_INSERT_REDIS_ERROR);
		}
	}

	/**
	 * 获取已输入密码错误的次数
	 * @param userName登录名
	 * @return
	 */
	public int selectLoginPasswordErrorRecord(String userName) {
		String count = redisDao.select("passwordErrorRecord" + userName);
		if (StringsUtils.isEmpty(count)) {
			return 0;
		}
		return Integer.valueOf(count);
	}

	/**
	 * 登录限制 （记录密码错误的次数）
	 * @param userName 登录名
	 * @param count 错误次数
	 */
	public void insertLoginPasswordRecord(String userName, String count) {
		Date date = new Date();
		Calendar midnight = Calendar.getInstance();
		midnight.setTime(date);
		midnight.add(Calendar.DAY_OF_MONTH, 1);
		midnight.set(Calendar.HOUR_OF_DAY, 0);
		midnight.set(Calendar.MINUTE, 0);
		midnight.set(Calendar.SECOND, 0);
		midnight.set(Calendar.MILLISECOND, 0);
		Integer seconds = (int) ((midnight.getTime().getTime() - date.getTime()) / 1000);
		redisDao.insert("passwordErrorRecord" + userName, count, seconds);
	}

	/**
	 * 连接中拼接域名
	 * @param url
	 * @return
	 */
	public String addDomain(String url) {
		if(!StringsUtils.isEmpty(url)) {
			if(url.startsWith("/") || url.startsWith("\\")) {
				url = url.substring(1);
			}
			url = url.indexOf(domainUrl)>=0 ? url : domainUrl + url;
			if(url.indexOf("?")>=0) {
				url = url.substring(0, url.indexOf("?"));
			}
		}
		return url;
	}
	
	/**
	 * 连接中拼接域名并增加变量，防止浏览器缓存
	 * @param url
	 * @return
	 */
	public String addDomainAndTs(String url) {
		if(StringsUtils.isEmpty(url))
		{
			return null;
		}
		return StringsUtils.urlAddTs(addDomain(url));
	}

	/**
	 * 添加域名到用户图片中
	 * @param list
	 * @return
	 */
	public List<MdeUser> addDomainUrl2UserImg(List<MdeUser> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
				list.get(i).setImage(addDomain(list.get(i).getImage()));
				list.get(i).setOnJobImage(addDomain(list.get(i).getOnJobImage()));
			}
		}
		return list;
	}

	public MdeUser addDomainUrl2UserImg(MdeUser user) {
		if(user == null )return null;
		user.setHeadPortrait(addDomainAndTs(user.getHeadPortrait()));
		user.setImage(addDomainAndTs(user.getImage()));
		user.setOnJobImage(addDomainAndTs(user.getOnJobImage()));
		return user;
	}

	/**
	 * 添加域名信息到热门动态连接中
	 * @param list
	 * @return
	 */
	public List<MdeInformation> addDomainUrl2InfomationImg(List<MdeInformation> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setInfoPicurl(addDomain(list.get(i).getInfoPicurl()));
		}
		return list;
	}

	public MdeInformation addDomainUrl2InfomationImg(MdeInformation info) {
		if(info == null )return null;
		info.setInfoPicurl(addDomain(info.getInfoPicurl()));
		return info;
	}

	/**
	 * 添加域名信息到动态图片中
	 * @param list
	 * @return
	 */
	public List<MdeTrends> addDomainUrl2TrendsImg(List<MdeTrends> list,String lang) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setTrendPicurl(splitTrendPic(list.get(i).getTrendPicurl()));
			list.get(i).setHeadImage(addDomain(list.get(i).getHeadImage()));
			list.get(i).setUserHeadPortrait(addDomain(list.get(i).getUserHeadPortrait()));
			list.get(i).setOriginUserHeadPortrait(addDomain(list.get(i).getOriginUserHeadPortrait()));
			list.get(i).setPublishTime2Now(trendsPublishTime2Now(list.get(i).getCreateDate()));
		}
		return list;
	}
	
	/**
	 * 添加域名信息到动态图片中
	 * @param list
	 * @return
	 */
/*	public List<TrendsDto> addUrl2TrendsImg(List<TrendsDto> list,String lang) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setTrendPicurl(splitTrendPic(list.get(i).getTrendPicurl()));
//			list.get(i).setHeadImage(addDomain(list.get(i).getHeadImage()));
			list.get(i).setUserHeadPortrait(addDomain(list.get(i).getUserHeadPortrait()));
			list.get(i).setOriginUserHeadPortrait(addDomain(list.get(i).getOriginUserHeadPortrait()));
			list.get(i).setPublishTime2Now(trendsPublishTime2Now(list.get(i).getCreateDate(),lang));
		}
		return list;
	}*/
	
	/**
	 * 切割多图动态
	 * @param picStr
	 * @return
	 */
	public String splitTrendPic(String picStr) {
		if(StringsUtils.isEmpty(picStr)) {
			return "";
		}
		String result = "";
		String[] imagesUrls = picStr.split("\\|");
		for(String imgUrl :imagesUrls) {
			if(!StringsUtils.isEmpty(imgUrl)) {
				result += addDomain(imgUrl)+"|";
			}
		}
		if(result.endsWith("|")) result = result.substring(0,result.length()-1);
		if(result.startsWith("|")) result = result.substring(1);
		return result;
	}
	public MdeTrends addDomainUrl2TrendsImg(MdeTrends trend,String lang) {
		if(trend == null )return null;
		trend.setTrendPicurl(splitTrendPic(trend.getTrendPicurl()));
		trend.setPublishTime2Now(trendsPublishTime2Now(trend.getCreateDate()));
		trend.setUserHeadPortrait(addDomain(trend.getUserHeadPortrait()));
		trend.setHeadImage(addDomain(trend.getHeadImage()));
		trend.setOriginUserHeadPortrait(addDomain(trend.getOriginUserHeadPortrait()));
		return trend;
	}
	public String[] trendsPublishTime2Now(Date date) {
		if(date==null) {
			return new String[2];
		}
		return Time2Now.format(date,"");
	}
	/**
	 * 添加域名信息到 酒店(职位)邀请信息
	 * @param resultList
	 * @return
	 */
	public List<HotelInvitationInfoResp> addDomainUrl2HotelInvitationImg(List<HotelInvitationInfoResp> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
		}
		return list;
	}

	/**
	 * 添加域名信息到 被好友评论的动态信息
	 * @param list
	 * @return
	 */
	private List<TrendCommentInfo> addDomainUrl2TrendCommentInfoImg(List<TrendCommentInfo> list) {
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
		}
		return list;
	}

	/**
	 * 添加域名信息到 用户简历
	 * @param userCVList
	 * @return
	 */
	public List<MdeUserCv> addDomainUrl2UserCvImg(List<MdeUserCv> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setCvUrl(addDomainAndTs(list.get(i).getCvUrl()));
		} //  下载简历 是从后台接口获取的, 所以简历地址不要加域名
		return list;
	}
	
	/**
	 * 添加域名信息到 伯乐
	 * @param allBole
	 * @return
	 */
	public List<MdeBoleInfo> addDomainUrl2BoleImg(List<MdeBoleInfo> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setImageUrl(addDomain(list.get(i).getImageUrl()));
		}
		return list;
	}
	
	/**
	 * 添加域名信息到 登录
	 * @param allBole
	 * @return
	 */
	public void addDomainUrlLogin(MdeUser mdeUser) {
		if(mdeUser != null ) {
			mdeUser.setHeadPortrait(addDomainAndTs(mdeUser.getHeadPortrait()));
		}
		
	}

	/**
	 * 添加域名信息到 企业收到简历 (企业查看 已投递人员信息)
	 * @param allBole
	 * @return
	 */
	public List<UserInfoResp> addDomainUrlEnterUserCv(List<UserInfoResp> list) {
		if(list == null ) return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadImage(addDomainAndTs(list.get(i).getHeadImage()));
			list.get(i).setCvUrl(addDomain(list.get(i).getCvUrl()));
		}
		return list;
	}

	/**
	 * 添加域名信息到 查看简历详情 
	 * 
	 * @param allBole
	 * @return
	 */
	public ContactUserInfoResp addDomainUrlLookUserCv(ContactUserInfoResp contactUserInfoResp) {
		if(contactUserInfoResp == null )return null;
		contactUserInfoResp.setHeadImage(addDomainAndTs(contactUserInfoResp.getHeadImage()));
		return contactUserInfoResp;
	}

	/**
	 * 添加域名信息到 人才检索
	 * 
	 * @param allBole
	 * @return
	 */
	public List<TalentRetrievalDto> addDomainUrlTalentRetrieval(List<TalentRetrievalDto> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadImage(addDomain(list.get(i).getHeadImage()));
		}
		return list;
	}
	
	/**
	 * 添加域名信息到好友关系
	 * @param list
	 * @return
	 */
	public List<MdeFriendRelation> addDomainUrl2FriendRelationImg(List<MdeFriendRelation> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
		}
		return list;
	}
	/**
	 * 添加域名信息到酒店收到的投递简历信息
	 * @param recievedCvList
	 * @return
	 */
	public ArrayList<JobCollectionReq> addDomainUrl2JobCollectionReqImg(ArrayList<JobCollectionReq> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setUserHeadPortrait(addDomain(list.get(i).getUserHeadPortrait()));
		}
		return list;
	}
	/**
	 * 推荐职位到发布职位
	 * @param list
	 * @return
	 */
	public List<MdeJobAdvertised> addDomainUrl2JobAdvertisedImg(List<MdeJobAdvertised> list) {
		if(list == null )return null;
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
		}
		return list;
	}
	
	/**
	 * 推荐职位到发布职位
	 * @param list
	 * @return
	 */
	public List<MdeJobAdvertised> makeJobAdvertisedImg(List<MdeJobAdvertised> list, String login) {
		if(list == null )return null;
		if(!StringsUtils.isEmpty(login))
		{
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
				list.get(i).setJobId(null);
			}
		}else
		{
			list = addDomainUrl2JobAdvertisedImg(list);
		}
		
		return list;
	}
	
	public List<JobAdvertisedListDto> makeJobAdvertisedImg2(List<JobAdvertisedListDto> list, String login) {
		if(list == null )return null;
		if(!StringsUtils.isEmpty(login))
		{
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
				list.get(i).setJobId(null);
			}
		}else
		{
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setHeadPortrait(addDomain(list.get(i).getHeadPortrait()));
			}
		}
		
		return list;
	}
	
	/**
	 * 获取内部通知人员邮箱地址
	 * @param message
	 * @param lang
	 */
	public String getNoticeEmailAdds() {
		List<LVResp> list = sysDictService.getDictLVByType("sys_notice_mail", "cn");// 获取管理员邮件
		String address = new String();
		for(LVResp v:list) {
			address = address + v.getValue() + ",";
		}
		return address;
	}
	/**
	 * 邮箱验证
	 * 
	 * @param userName
	 * @return
	 */
	public boolean checkMail(String mail) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(mail);
			flag = matcher.matches();
		} catch (Exception e) {
			log.info(e.getMessage());
			return flag;
		}
		return flag;
	}
	
	
	/**
	 * 拼装邀请id
	 * 
	 * @param userName
	 * @return
	 */
	public String getInviter(String userCode, String actId) {
		//24进制转换
		String inviter = getShortInviter(userCode)+ Constants.UNDER_LINE + actId;
		
		return inviter;
	}
	
	public String getShortInviter(String userCode) {
		BigInteger code = new BigInteger(userCode);
		//24进制转换
		String shortInviter = code.toString(24);
		
		return shortInviter;
	}
	
	
	/**
	 * 获取活动id
	 * 
	 * @param userName
	 * @return
	 */
	public String getActId() {
		String actid = redisDao.select("MDE_ACTID");
		if(StringsUtils.isEmpty(actid))
		{
			//没有缓存的情况下从DB获取
			List<String> list = actCategoryDao.getActIds();
			if(list.size() > 0) {
				actid = list.get(0);
			}
		}
		//缓存6小时
		redisDao.insert("MDE_ACTID", actid, 21600);
		return actid;
	}
	
	/**
	 * 创建新线程用于异步调用
	 *
	 * @return
	 */
	private ExecutorService cachedThreadPool = Executors.newCachedThreadPool() ;
	
	/**
	 * 发送内部提醒邮件
	 * 
	 * @param userInfo
	 * @param request
	 */
	public void sendNoticeEmail(final String mailContent, final String sendTo, final String notice) {
		//新线程，异步操作
		cachedThreadPool.submit(new Runnable() {
			@Override
			public void run() {
				try {
					if (mailUtil.sendNoticeMail(sendTo, notice+" "+DateUtils.dateToString(DateUtils.PATTEN_HM), mailContent)) {
					} else {
						log.error("内部提醒邮件"+notice+"发送失败，邮件地址：[" + sendTo + "]");
					}
				} catch (Exception e) {
					log.error("内部提醒邮件"+notice+"发送异常", e);
					throw new CustomException(InfoMsg.ERROR_SEND_EMAIL_FAIL);
				}
			}
		});
	}
	
	
	/**
	 * 根据工作年限获取工作起始时间范围
	 * @param experience
	 * @return
	 */
	public WorkDateDto getDateByExperience(String experience) {
		WorkDateDto workDate = new WorkDateDto();
		int lately = 0;
		int furthest = -60;
		
		if(!StringsUtils.isEmpty(experience))
		{
			switch(experience){
				case "1" :
					lately = -1;
					furthest = -3;
					break;
				case "3" :
					lately = -3;
					furthest = -5;
					break;
				case "5" :
					lately = -5;
					furthest = -10;
					break;
				case "10" :
					lately = -10;
					furthest = -60;
					break;
			}
		}
		workDate.setFrom(DateUtils.addYear(new Date(), furthest));
		workDate.setTo(DateUtils.addYear(new Date(), lately));

		return workDate;
	}
	
	
	/**
	 *  保存登陆历史
	 * 
	 * @return
	 */
	public void addLoginHis(HttpServletRequest request,String userId) {
		MdeLoginHis his = commonHelper.getDeviceType(request);
		//拼接redis key
		StringBuffer infoKey = new StringBuffer(userId);
		infoKey.append(his.getOperating());
		infoKey.append(his.getBrowserVersion());
		infoKey.append(his.getIp());
		String key =infoKey.toString();
		try {
			if(!redisDao.hasKey(key)) {
				//减少重复数据录入
				his.setHisId(R.UU16());
				his.setUserId(userId);
				his.setCreateBy(userId);
				loginHisDao.insertNewHis(his);
			}
			//记录缓存
			redisDao.insertMinutes(infoKey.toString(), "",tokenExpireTime);
			
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	
	
	/**
	 * 微信 图片上传-手机
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	public ResultEntity<String> uploadByWx(String pictureId, String childPath) throws Exception {
		ResultEntity<String> resq = new ResultEntity<String>();
		if (StringsUtils.isEmpty(pictureId)) {
			resq.setMsg(InfoMsg.ERROR_NULL_PARAM);
		}else {
			String url = weiXinService.saveImageToDisk(pictureId,childPath);
			if(StringsUtils.isEmpty(url))
			{
				resq.setMsg(InfoMsg.ERROR_IMAGE_UPLOAD);
			}else {
				resq.setResult(domainUrl+url);
			}
		}
		
		return resq;
	}
	
	

	/**
	 * 登陆用cookie生成
	 * @param open
	 * @param unionid
	 * @param loginModel
	 */
	public void setLoginCookies(HttpServletResponse response, String userCode, String identityFlag, Date createDate) {
			String creatTime = String.valueOf(createDate.getTime());
			// 生成token
			Cookie tokenCookie = null;
			try {
				tokenCookie = new Cookie(Constants.TOKEN_COOKIE_NAME,
						commonHelper.getToken(String.valueOf(userCode), identityFlag,creatTime));
			} catch (Exception e) {
				log.info(e.getMessage());
			}
			// token cookie失效时间
			int clearTokenSec = (tokenExpireTime * 60)-1;
			tokenCookie.setMaxAge(clearTokenSec);
			tokenCookie.setPath("/");
            response.addCookie(tokenCookie);
            
		    // 设置个人、企业区分
            Cookie identityCookie = new Cookie(Constants.TOKEN_IDENTITY_FLAG, identityFlag);
            identityCookie.setPath("/");
            identityCookie.setMaxAge(clearTokenSec);
            response.addCookie(identityCookie);
            
            // 短的邀请id
 			Cookie shortInviter = new Cookie(Constants.TOKEN_SHORT_INVITER, getShortInviter(userCode));
 			shortInviter.setPath("/");
 			shortInviter.setMaxAge(clearTokenSec);
 			response.addCookie(shortInviter);

			// 用户的userCode
			Cookie userCookie = new Cookie(Constants.TOKEN_USER_ID, String.valueOf(userCode));
			userCookie.setPath("/");
			userCookie.setMaxAge(clearTokenSec);
			response.addCookie(userCookie);
	}
	
	
	/**
	 * 根据code 获取省市区名称
	 * @param code
	 * @return
	 */
	public List<String> getNameListByCodes(List<String> codeList, String lang) {
		List<String> list = areaDao.getNamesByCodes(codeList,lang);
		
		return list;
	}
	
	public String getNameStrByCodes(List<String> codeList, String lang) {
		List<String> list = areaDao.getNamesByCodes(codeList,lang);
		String str = new String();
		if(list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				str = str + list.get(i);
			}
		}
		return str;
	}
	
	
	/**
	 * 验证用户关注公众号并绑定
	 * @param userCode
	 * @return
	 */
	public InfoMsg checkBindingAndSubscribe(String userCode) {
		InfoMsg msg = InfoMsg.SUCCESS_REQUEST;
		MdeUser userInfo = userDao.getUserSensitiveInfo(userCode);
		String openid = userInfo.getOpenId();
		if(StringsUtils.isEmpty(openid)) {
			msg = InfoMsg.ERROR_UNBINDING;
		} else {
			//获取用户关注信息
			 WxUserInfoDto wxUserInfo = weiXinService.getUserInfo(userInfo.getOpenId());
			 if("0".equals(wxUserInfo.getSubscribe())) {
				 msg = InfoMsg.ERROR_UN_SUBSCRIBE;
			 }
		}
		return msg;
	}

	/**
	 * 验证并限制接口访问频次
	 * ---广告点击率
	 * @return
	 */
	public boolean limitApiFrequencyAdCtrs(HttpServletRequest request) {
		boolean result = true;

		String relIp = commonHelper.getIRealIPAddr(request);
		String ipkey = Constants.REDIS_LIMIT_AD_CTR + relIp;
		if(redisIntegerDao.hasKey(ipkey)) {
			Integer visitNo = redisIntegerDao.select(ipkey);
			if(visitNo > 3) {
				//10秒内不能大于3此
				result = false;
			}else {
				visitNo = visitNo +1;
			}
		} else {
			//8秒后消失
			redisIntegerDao.insert(ipkey, 1, 8);
		}
		return result;
	}
}
