WxMiniServiceImpl.java 26.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
package org.theyeasy.weixin.service.impl;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.util.Strings;
import org.theyeasy.weixin.model.BaseMessage;
import org.theyeasy.weixin.service.WxMiniService;
import org.theyeasy.weixin.service.WxOpenService;
import org.theyeasy.weixin.service.WxPayService;
import org.theyeasy.weixin.util.ActivitySettingUtils;
import org.theyeasy.weixin.util.WxMessageUtil;
import org.theyeasy.weixin.util.WxMiniUtil;
import org.theyeasy.weixin.util.WxMpUtil;

import com.w1hd.zzhnc.dao.AutoreplyDao;
import com.w1hd.zzhnc.dao.FansDao;
import com.w1hd.zzhnc.dao.LotteryLogDao;
import com.w1hd.zzhnc.enums.ActivityStatus;
import com.w1hd.zzhnc.enums.ChatLogReplyType;
import com.w1hd.zzhnc.model.Activity;
import com.w1hd.zzhnc.model.Autoreply;
import com.w1hd.zzhnc.model.Chatlog;
import com.w1hd.zzhnc.model.Fans;
import com.w1hd.zzhnc.model.Lotterylog;
import com.w1hd.zzhnc.model.Prize;
import com.w1hd.zzhnc.service.ActivityService;
import com.w1hd.zzhnc.service.AutoreplyService;
import com.w1hd.zzhnc.service.ChatLogService;
import com.w1hd.zzhnc.service.FansService;
import com.w1hd.zzhnc.util.CommonUtil;
import com.w1hd.zzhnc.util.JsonMapper;
import com.w1hd.zzhnc.util.QQFaceUtil;
import com.w1hd.zzhnc.util.RedisUtil;
import com.w1hd.zzhnc.vo.Vo_msg;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class WxMiniServiceImpl implements WxMiniService {

	@Autowired
	WxOpenService wxOpenService;

	@Autowired
	FansService fansService;

	@Autowired
	ChatLogService chatLogService;

	@Autowired
	AutoreplyService AutoreplyService;

	@Autowired
	ActivityService activityService;

	@Autowired
	LotteryLogDao lotteryLogDao;

	@Autowired
	AutoreplyDao autoreplyDao;

	@Autowired
	FansDao fansDao;

	@Autowired
	WxPayService wxPayService;

	@Override
	public String processRequest(HttpServletRequest request) {
		String respMessage = "success";
		Boolean copyToWxkf = true;
		try {
			// xml请求解析
			Map<String, String> requestMap = WxMessageUtil.parseXml(request);
			System.out.println("进入WxMiniUtil.processRequest,requestMap:" + requestMap);
			// 发送方帐号(open_id)
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息ID
			String msgId = requestMap.get("MsgId");
			// 消息时间
			String msgTime = requestMap.get("CreateTime");

			/****************
			 * 微信消息去重处理(重要!!!服务器繁忙时微信会重复3次推送同一条消息 add by lcc 2017-10-30
			 ****************************/
			String key = "WxMiniMsgKey_";
			key += fromUserName + msgTime;

			long j = RedisUtil.setNX(key, "0");
			if (j == 0) {
				System.out.println("重复的wxWxMiniMsg,直接返回succes. key=" + key);
				return "success"; // 重复消息
			} else {
				RedisUtil.set(key, "0", 60 * 5);
			}

			Fans fans = fansService.getFansByMiniOpenid(fromUserName);
			if (fans == null) {
				fans = fansService.addFans(fromUserName);
				System.out.println("会话事件中添加了粉丝,id=" + fans.getId());
			}
			int saleid = fans.getGoodsId();
			if (saleid < 1) // 没有销售的就分配一个万小二给他。
			{
				fansDao.updateByPrimaryKeySelective(fans);
			}

			String sendResult = "";//

			if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				String content = requestMap.get("Content").trim(); // 用户发送的内容
				// if (content.equals("TEST_WXMSG_BUSY_SLEEP_6"))
				// Thread.currentThread().sleep(6000); // 测试重复消息的过滤功能(add by lcc
				// 171030);

				content = QQFaceUtil.regix(content);

				Activity activitySetting = activityService.getActivitySetting();
				if (activitySetting != null && activitySetting.getStatus() > ActivityStatus.UNSTART.getIndex()
						&& !content.equals("人工万小二")) {
					String[] keywords = activitySetting.getKeyword().split("\\|");
					boolean containKeyword = false;
					for (String keyword : keywords) {
						if (content.contains(keyword)) {
							containKeyword = true;
							break;
						}

					}

					// 金额比较 Edit by lcc 171207
					BigDecimal currentMny = activitySetting.getCurrentMny();
					int compareTo = 0;
					if (currentMny != null) {
						compareTo = activitySetting.getPlanMny().compareTo(activitySetting.getCurrentMny());
					}
					// 抽奖活动已结束或红包预算已经发放完毕的回复.. add by lcc 171207
					if (containKeyword && (activitySetting.getStatus() > 2 || compareTo < 0)) {
						WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getFinishReply());
						saveChatLog(fans.getId(), content, activitySetting.getFinishReply(), fans.getGoodsId(),
								ChatLogReplyType.自动回复, "", "");
						return respMessage;
					}

					// 抽奖活动进行中
					if (!Strings.isNullOrEmpty(activitySetting.getKeyword()) && containKeyword
							&& activitySetting.getStatus() == 2) {
						Fans fansByMiniOpenid = fansService.getFansByMiniOpenid(fromUserName);
						Example example = new Example(Lotterylog.class);

						// 从redis判断是否此人已中过奖
						String hasLottery = RedisUtil.get("zzhnc_lottery_fansid_" + fans.getId());
						if (null != hasLottery && hasLottery.equals("1")) {
							WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getNoChanceReply());
							saveChatLog(fans.getId(), content, activitySetting.getNoChanceReply(), fans.getGoodsId(),
									ChatLogReplyType.自动回复, "", "");
							return respMessage;
						}

						// 判断本轮的总抽奖次数,最多两次抽奖机会 add by lcc 171207
						example.createCriteria().andEqualTo("fansid", fansByMiniOpenid.getId()).andEqualTo("turn",
								activitySetting.getTurn());
						int count = lotteryLogDao.selectCountByExample(example);
						if (count >= 2) {
							WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getNoChanceReply());
							saveChatLog(fans.getId(), content, activitySetting.getNoChanceReply(), fans.getGoodsId(),
									ChatLogReplyType.自动回复, "", "");
							return respMessage;
						}

						// 判断是否中奖过,最多一次中奖机会 add by lcc 171207
						example.clear();
						example.createCriteria().andEqualTo("fansid", fansByMiniOpenid.getId())
								.andEqualTo("turn", activitySetting.getTurn()).andGreaterThan("status", "0");
						int succeedCount = lotteryLogDao.selectCountByExample(example);
						if (succeedCount > 0) {
							WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getNoChanceReply());
							saveChatLog(fans.getId(), content, activitySetting.getNoChanceReply(), fans.getGoodsId(),
									ChatLogReplyType.自动回复, "", "");
							return respMessage;
						}

						boolean sussess = false;

						// 指定城市范围
						String city = activitySetting.getCity();
						// 粉丝城市
						String fansCity = fansByMiniOpenid.getProvince();
						if (Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(fansCity)
								|| !fansCity.startsWith(city)) {
							if (null == fansCity || fansCity == "null" || fansCity.length() < 1)
								fansCity = "未授权";
							String msg = "红包活动仅限【" + city + "】,您的省份【" + fansCity + "】不在本次活动范围内,不能参与抽奖哦~~/玫瑰/玫瑰";
							// if(null==fansCity || fansCity=="") msg="红包活动仅限【" + city + "】,您的省份【" +
							// fansCity+ "】可能是您未授权,小二无法判断您是否在本次活动范围内,所以不能参与抽奖哦~~";
							WxMiniUtil.sendCustomMsgText(fromUserName, msg);
							saveChatLog(fans.getId(), content, msg, fans.getGoodsId(), ChatLogReplyType.自动回复, "", "");
							return respMessage;
						}

						WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getReplyWait());
						saveChatLog(fans.getId(), content, activitySetting.getReplyWait(), fans.getGoodsId(),
								ChatLogReplyType.自动回复, "", "");

						Thread.sleep(1000);

						/** 取100-200内的数值,单位为分 */
						List<Prize> prizes = ActivitySettingUtils.getInstance(activitySetting).getPrizes();
						Collections.sort(prizes, new Comparator<Prize>() {

							public int compare(Prize o1, Prize o2) {
								if (o1.getProbability() > o2.getProbability()) {
									return -1;
								}
								if (o1.getProbability() == o2.getProbability()) {
									return 0;
								}
								return 1;
							}
						});
						int max = ActivitySettingUtils.getInstance(activitySetting).max();
						int nextInt = RandomUtils.nextInt(0, max);
						Prize temp = null;
						for (Prize p : prizes) {
							if (nextInt < p.getProbability()) {
								if (p.getNum() > 0) {
									temp = p;
								}
							}
						}

						Vo_msg msg = new Vo_msg(-1, null, "未知错误.");
						int mny = 0;
						if (temp.getIsMoney()) {
							mny = RandomUtils.nextInt(temp.getMixMoney(), temp.getMaxMoney());
							msg = wxPayService.payMoney("pay" + DateTime.now().getMillis(), fromUserName, mny,
									"来自【东莞万科万小二】的红包奖励");
							sussess = (msg.code == 0);
							activitySetting
									.setCurrentMny(activitySetting.getCurrentMny().add(new BigDecimal(mny * 0.01)));
						} else {
							temp.setNum(temp.getNum() - 1);
							switch (temp.getId()) {
							case 1:
								activitySetting.setP1(temp);
								break;
							case 2:
								activitySetting.setP2(temp);
								break;
							case 3:
								activitySetting.setP3(temp);
								break;
							case 4:
								activitySetting.setP4(temp);
								break;
							default:
								break;
							}
							sussess = true;
						}
						activityService.updateActivity(activitySetting);
						activityService.addLotteryLog(fansByMiniOpenid.getId(), new BigDecimal(mny * 0.01),
								sussess == true ? 1 : 0, activitySetting.getTurn(),temp.getName());
						if (sussess) { // 已中奖
							// 扣减红包预算总额

							// 已中奖的推送到Redis中进行缓存,避免出现sql并发重复参与抽奖
							RedisUtil.set("zzhnc_lottery_fansid_" + fans.getId(), "1", 10 * 60);
							// 发送中奖提示语
							WxMiniUtil.sendCustomMsgText(fromUserName, activitySetting.getReplySucceed());
							saveChatLog(fans.getId(), content, activitySetting.getReplySucceed(), fans.getGoodsId(),
									ChatLogReplyType.自动回复, "", "");
							// 推送中奖链接
							String url = "http://mini.weiyisz.com/zzhnc/wx/redpackage?mny=" + mny * 0.01;
							WxMiniUtil.sendCustomMsgLink(fromUserName, activitySetting.getLotteryTitle(),
									activitySetting.getLotterySubTitle(), url,
									"http://mini.weiyisz.com/zzhnc/res/images/redpackage.png");
							// 推送小程序卡片
							SendMiniProgram(fromUserName);

							return respMessage;
						} else { // 未中奖
							// 发送未中奖提示语
							String failedReply = count == 0 ? activitySetting.getUnLotteryReply()
									: activitySetting.getReplyFailed2(); // 第一次和第二次未中奖的提示语有区别
							WxMiniUtil.sendCustomMsgText(fromUserName, failedReply);
							saveChatLog(fans.getId(), content, failedReply, fans.getGoodsId(), ChatLogReplyType.自动回复,
									"", "");

							// 两次未中奖时推送小程序卡片
							if (count > 0) {
								SendMiniProgram(fromUserName);
							}
							return respMessage;
						}
					}
				}

				// 人工客服未接管,但是与客服正在聊天,无论如何都要发模板消息
				if (RedisUtil.getFansChatStatus(fans.getId()) > 1) {
					nofitySalesIncludeVanker(saleid, content, fans);
				} else
				// 人工客服未接管:判断是否需要给后台客服人员发送模板消息
				if (needNotifySales(content)) {
					// 用模板消息通过对应的销售,没有对应销售时发送给所有万小二。
					nofitySalesIncludeVanker(saleid, content, fans);

					// 自动随机回复客户
					String randomReply = getRandomReplyAfterNotify();
					WxMiniUtil.sendCustomMsgText(fromUserName, randomReply);
					if (saleid == 0) {
						String vankerId = RedisUtil.get("zzhnc_vanke");
						if (Strings.isNullOrEmpty(vankerId)) {
							int id = Integer.parseInt(vankerId);
							saleid = id;
						}
					}
					saveChatLog(fans.getId(), content, randomReply, saleid, ChatLogReplyType.自动回复, "", "");

					return respMessage;
				}

				String faces = WxMiniUtil.sponseQqFace(content);
				if (faces.startsWith("[") && faces.endsWith("]"))
					faces = faces.substring(1, faces.length() - 1);
				if (faces.length() > 0) {
					WxMiniUtil.sendCustomMsgText(fromUserName, faces);
					saveChatLog(fans.getId(), content, faces, saleid, ChatLogReplyType.自动回复, "", "");
					return respMessage;
				}

				HashMap<Object, Object> data = AutoreplyService.autoreply(content, cache(toUserName), fromUserName);
				Autoreply auto = (Autoreply) data.get("autoreply");

				// 判断是否需要发送小程序卡片 add by lcc 2017-12-11
				if (auto.getContents().startsWith("【发送小程序卡片】")) {
					Vo_msg vo = SendMiniProgram(fromUserName);
					System.out.println("发送小程序卡片:" + vo.msg);
					return respMessage;
				}
				WxMiniUtil.sendCustomMsgText(fromUserName, auto.getContents());
				saveChatLog(fans.getId(), content, auto.getContents(), saleid,
						Integer.parseInt(data.get("type").toString()) == 2 ? ChatLogReplyType.自动回复
								: ChatLogReplyType.机器人,
						"", "");

				// 判断是否需要通知人工客服 --add by lcc 171207
				if (auto.getIsredirectstaff()) {
					nofitySalesIncludeVanker(saleid, content, fans);
				}

				return respMessage;

			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {// 图片消息

				String fansImgUrl = requestMap.get("PicUrl");
				boolean handle = false;
				if (!handle) {
					String imgReply = getImgReply();
					WxMiniUtil.sendCustomMsgText(fromUserName, imgReply);// 还没办法自动回复图片
					saveChatLog(fans.getId(), "", imgReply, saleid, ChatLogReplyType.机器人, fansImgUrl, "");
				}

			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {// 地理位置消息
			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_LINK)) {// 链接消息
			} else if (msgType.equals(WxMessageUtil.RESP_MESSAGE_TYPE_MUSIC)) {// 音频消息
			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_VOICE)) {// 音频消息
			} else if (msgType.equals(WxMessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
				String eventType = requestMap.get("Event");// 事件类型,未使用
				if (eventType.equals("user_enter_tempsession")) // 用户在小程序进入客服面板
				{
					// 保存进入会话时传入的参数
					String sessionFrom = requestMap.get("SessionFrom");
					cache(fromUserName, getSessionFromValue(sessionFrom, 0));
					String floorname = getSessionFromValue(sessionFrom, 1);// 楼盘名称

					// 保存粉丝最后一次进入会话的时间
					boolean firstEnter = (fans.getLastEnterTime() == null);
					fans.setLastEnterTime(DateTime.now().toDate());
					fansDao.updateByPrimaryKey(fans);

					// 发送欢迎语
					String welcome = getWelcome(firstEnter);
					if (firstEnter) {
						// 如果红包活动正在进行中,发送红包活动的提醒文字
						Activity activitySetting = activityService.getActivitySetting();
						if (activitySetting != null
								&& activitySetting.getStatus() == ActivityStatus.RUNNING.getIndex()) {
							welcome = activitySetting.getReplyWelcome();
						}
					}

					sendResult = WxMiniUtil.sendCustomMsgText(fromUserName, welcome);

					saveChatLog(fans.getId(), "进入会话:" + floorname, welcome, fans.getGoodsId(), ChatLogReplyType.进入会话,
							"", "");
				}
				copyToWxkf = false; // 事件不要转发给客服系统。
			}

			System.out.print("WxMiniMsg.sendResult=" + sendResult);
			// 以下处理回复给微信服务器的消息
			if (copyToWxkf) // 将用户发送的消息自动转发给微信的官方客服系统。
			{
				BaseMessage msg = new BaseMessage();
				msg.setToUserName(fromUserName);
				msg.setFromUserName(toUserName); // 开发者微信号
				msg.setCreateTime(new Date().getTime());
				msg.setMsgType("transfer_customer_service");
				respMessage = WxMessageUtil.messageToXml(msg);
			} else {
				respMessage = "success"; // 不希望微信作处理里回复success,微信收不到响应会重复5次推送消息。
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

	/**
	 * 是否需要给销售或万小二发送模板消息通知
	 */
	@Override
	public boolean needNotifySales(String fansMsg) {
		String keywordsRegex = "有人吗|人工|客服|在吗|没人吗|有人不?|有人么|在不在?|找人工|找客服|客服在不在|有真人吗|有活人";
		Pattern p = Pattern.compile(keywordsRegex);
		Matcher m = p.matcher(fansMsg);
		return m.find();
	}

	// 发送模板消息给销售或万小二
	public Boolean SendTemplateToSale(String openId, String custMsg, Fans fromFans) {
		System.out.println("SendTemplateToSale");

		if (fromFans.getGoodsId() == 0) // 粉丝未绑定销售时,在此绑定对应销售(实际只在分配万小二时起作用) edit by lcc 2017-12-10
		{
			fansDao.updateByPrimaryKeySelective(fromFans);
		}

		String fansName = fromFans.getNickname();
		if (null == fansName || fansName.equals(""))
			fansName = "粉丝(id:" + fromFans.getId() + ")";
		String url = "http://www.baidu.com";

		try {
			String newurl = wxOpenService.getWxMpService(RedisUtil.getMpAppid()).oauth2buildAuthorizationUrl(url,
					WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(fromFans.getMiniopenid()));
			WxMpUtil.SendTemplate_Vanker(openId, custMsg, fansName, "无", DateTime.now().toString(), newurl);
			// 更新粉丝的最后触发时间
			fromFans.setLastAskMsg(custMsg);
			fromFans.setLastAskTime(DateTime.now().toDate());
			fromFans.setReaded(false);
			fansDao.updateByPrimaryKey(fromFans);
			return true;
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public String sendCustMsgIdentify(String wxMiniOpenId, String info) {
		String url = "http://mini.weiyisz.com/zzhnc/wx/regist";

		try {
			String newurl = wxOpenService.getWxMpService(RedisUtil.getMpAppid()).oauth2buildAuthorizationUrl(url,
					WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(wxMiniOpenId));
			System.out.println("绑定销售身份的链接:" + newurl);
			String sendResult = WxMiniUtil.sendCustomMsgLink(wxMiniOpenId, info, "请点击打开页面,再输入手机号进行万小二销售人员的身份绑定。",
					newurl, "http://mini.weiyisz.com/zzhnc/res/images/confirm.jpg");
			return sendResult;
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	@Override
	public String sendLogin(int saleid, String wxMiniOpenId, String info) {
		String url = "http://mini.weiyisz.com/wx/chatListView?salesId=" + saleid;

		try {
			String newurl = wxOpenService.getWxMpService(RedisUtil.getMpAppid()).oauth2buildAuthorizationUrl(url,
					WxConsts.OAUTH2_SCOPE_BASE, "");
			System.out.println("推送万小二销售的登录链接:" + newurl);
			String sendResult = WxMiniUtil.sendCustomMsgLink(wxMiniOpenId, info, "点击登录到客服面板", newurl,
					"http://mini.weiyisz.com/zzhnc/res/images/confirm.jpg");
			return sendResult;
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public boolean sendRedBack(int fansId, String fromUserName, String titile, String subTitle, int mny) {

		/** 正式的 */
		String merchatId = "199";
		String activityId = "1291";

		String sendGet = CommonUtil.sendGet("http://www.w1hd.com/api/wx/createOrder",
				"merchantid=" + merchatId + "&wxactivityId=" + activityId + "&mny=" + mny);

		Object fromJsonString = JsonMapper.fromJsonString(sendGet, Map.class);
		Map<String, Object> map = (Map<String, Object>) JsonMapper.fromJsonString(sendGet, Map.class);
		System.out.println("订单生成请求结果:" + sendGet);

		if (!map.get("code").equals(0) || !map.containsKey("data")) {
			return false;
		}

		String url = getAuthorizeUrl(map.get("data").toString(), activityId, fansId);

		WxMiniUtil.sendCustomMsgLink(fromUserName, titile, subTitle, url,
				"http://mini.weiyisz.com/zzhnc/res/images/redpackage.png");

		return true;
	}

	@Override
	public String getRandomReplyAfterNotify() {
		String allMsg = "亲,你的消息我已经转发给人工客服了,你不会是想要找客服投诉我吧/流泪|亲/玫瑰,伦家已经帮您通知人工客服啦...|哎哟,客服的哥哥姐姐怎么还不来/抓狂,我再催催/左太极/左太极|/西瓜/西瓜/西瓜,再跟小二聊会嘛,客服收到通知啦啦 ...|客服里有大美女哦../色/色 |你的问题太深奥啦啦 ,我去通知客服姐姐来/咖啡/咖啡";

		// 从autoReply表获取回复内容
		Example example = new Example(Autoreply.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("keywords", "reply_when_notify_sales").andEqualTo("deleted", false);
		List<Autoreply> list = autoreplyDao.selectByExample(example);
		if (null != list && list.size() > 0) {
			allMsg = list.get(0).getContents();
		}

		String[] randomMsg = allMsg.split("\\|");
		int index = WxMiniUtil.getRandom(randomMsg.length);
		return randomMsg[index];
	}

	@Override
	public int saveChatLog(int fansid, String ask, String reply, int salesid, ChatLogReplyType replyType,
			String fansImgUrl, String replyImgurl) {
		Chatlog log = new Chatlog();

		log.setFansid(fansid);
		log.setAsk(ask);
		log.setReply(reply);
		log.setAsktime(new Date());
		log.setNoticetime(new Date());
		log.setSalesid(salesid);
		log.setVankerid(0);
		log.setReplytime(new Date());
		log.setAskfrom(1);
		log.setReplytype(replyType.getIndex());
		log.setReaded(false);
		log.setImgurl(fansImgUrl);
		log.setImgurl2(replyImgurl);

		return 1;
	}

	@Override
	public String getLastReply() {
		String allMsg = "你难住我了。。。/难过/大哭|世界那么大,我要出去走走/奋斗/奋斗/奋斗|....|今天天气真好呀!/呲牙/呲牙|让我想想.../阴险|我要提高下智商了/拳头/拳头/拳头|/抠鼻|/睡着|/睡着/睡着|skdfiqwkmqwemlqwdkl 哎呀,碰到键盘了。。。";
		String[] randomMsg = allMsg.split("\\|");
		int index = WxMiniUtil.getRandom(randomMsg.length);
		return randomMsg[index];
	}

	@Override
	public String getImgReply() {
		String reply = WxMiniUtil.getQQFace();

		return reply;
	}

	@Override
	public String getWelcome(boolean firstEnter) {
		String keyword = firstEnter ? "first_enter_session" : "second_enter_session";
		String reply = RedisUtil.get(keyword);
		if (null == reply || reply.length() < 1) // redis中没有欢迎语
		{
			Example example = new Example(Autoreply.class);
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("keywords", keyword).andEqualTo("deleted", false);
			List<Autoreply> list = autoreplyDao.selectByExample(example);
			if (null != list && list.size() > 0) {
				reply = list.get(0).getContents();
				RedisUtil.set(keyword, reply, 60 * 5); // 在redis内存中保留5分钟
			}
		}

		if (null == reply)
			return "";

		String[] randomMsg = reply.split("\\|");
		int index = WxMiniUtil.getRandom(randomMsg.length);

		return randomMsg[index];
	}

	@Override
	public String getSessionFromValue(String sessionFrom, int index) {
		// sessfrom的格式为:floorid:0,floorname:万科·珠江东岸,saleId:228

		if (sessionFrom == null)
			return "";

		String[] values = sessionFrom.split(",");
		System.out.println("values.length=" + values.length + " index=" + index);
		if (index >= values.length)
			return "";

		String[] kv = values[index].split(":");
		return kv.length == 2 ? kv[1] : "";
	}

	/**
	 * 发送模板消息给销售,如果saleid为0则发给所有万小二。
	 */
	@Override
	public void nofitySalesIncludeVanker(int saleid, String content, Fans fans) {
	}

	// 发送小程序卡片
	@Override
	public Vo_msg SendMiniProgram(String miniOpenId) {
		String thumb_url = RedisUtil.get("zzhnc_leave_program_thumb_url");
		String media_id = RedisUtil.get("zzhnc_leave_program_media_id");

		// redis中如果不存在,则重新上传临时素材
		if (null == media_id || media_id.length() < 1 || null == thumb_url || thumb_url.length() < 1) {
			// 获取默认首页的海报
			// Example example = new Example(Postertemplet.class);
			// example.createCriteria().andEqualTo("postertype", 3).andEqualTo("deleted",
			// false);
			// java.util.List<Postertemplet> posterList =
			// postertempletDao.selectByExample(example);
			// if (posterList.size() < 1)
			// return new Vo_msg(-1, null, "小程序卡片对应的海报模板不存在");
			// thumb_url = posterList.get(0).getImgurl();

			Vo_msg imgMsg = WxMiniUtil.uploadImage(thumb_url, false);
			if (imgMsg.code != 0)
				return new Vo_msg(-1, null, imgMsg.msg);

			media_id = imgMsg.data.toString();
			RedisUtil.set("zzhnc_leave_program_media_id", media_id, 24 * 60 * 60); // redis缓存配置为24小时
			RedisUtil.set("zzhnc_leave_program_thumb_url", thumb_url, 24 * 60 * 60); // redis缓存配置为24小时
		}

		String result = WxMiniUtil.sendCustoMiniprogrampage(miniOpenId, "买房就找万小二", "pages/openAnimation/openAnimation",
				thumb_url, media_id);
		return new Vo_msg(0, null, result);
	}

	public static void main(String[] arg) {

	}

	public static String getAuthorizeUrl(String orderId, String activityId, int fansId) {

		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd06aec668fe359d1&redirect_uri=http://www.w1hd.com/api/wx/wxd06aec668fe359d1/payWxMpUser2/"
				+ orderId + "/" + activityId + "/nmamtf&response_type=code&scope=snsapi_userinfo&state=" + fansId
				+ "&component_appid=wx79ad5a35526f26fb&connect_redirect=1#wechat_redirect";
		return url;
	}

	private void cache(String fromUserName, String projectId) {
		System.out.println("当前进入的楼盘projectId:" + projectId);
		if (Strings.isNullOrEmpty(projectId)) {
			RedisUtil.set("zzhnc_cache_project_" + fromUserName, 0 + "", 30 * RedisUtil.EXRP_MINUTE); // Edit by lcc
		} else {
			RedisUtil.set("zzhnc_cache_project_" + fromUserName, projectId + "", 30 * RedisUtil.EXRP_MINUTE);
		}
	}

	private Integer cache(String fromUserName) {
		String string = RedisUtil.get("zzhnc_cache_project_" + fromUserName);
		if (Strings.isNullOrEmpty(string)) {
			return 0;
		} else {
			return Integer.parseInt(string);
		}

	}

}