3451d6d1011674d98a9054bfa80db15e230ac0d5.svn-base 15.9 KB
package com.thinkgem.jeesite.modules.reg.web.wechat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.reg.entity.base.RegBaseYy;
import com.thinkgem.jeesite.modules.reg.entity.bus.RegBusSlsq;
import com.thinkgem.jeesite.modules.reg.service.base.RegBaseYyService;
import com.thinkgem.jeesite.modules.reg.service.bus.RegBusSlsqService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

@Controller
@RequestMapping(value = "${adminPath}/reg/wechatInterface")
public class WechatController extends BaseController{
	
	@Autowired
	private RegBusSlsqService regBusSlsqService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RegBaseYyService regBaseYyService;
	
    private String DNBX_TOKEN = "88250909";//令牌   (Token)
   
    private static final Logger LOGGER = LoggerFactory.getLogger(WechatController.class);
    
    /**
     * 微信接入
     * @param wc
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "wechat",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void connectWeixin(HttpServletRequest request, HttpServletResponse response) throws IOException{
        // 将请求、响应的编码均设置为UTF-8(防止中文乱码)  
    	//微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
        request.setCharacterEncoding("UTF-8");  
        //在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
        response.setCharacterEncoding("UTF-8"); 
        boolean isGet = request.getMethod().toLowerCase().equals("get"); 
        PrintWriter out = response.getWriter();
        try {
            if (isGet) {
                String signature = request.getParameter("signature");// 微信加密签名  
                String timestamp = request.getParameter("timestamp");// 时间戳  
                String nonce = request.getParameter("nonce");// 随机数  
                String echostr = request.getParameter("echostr");//随机字符串  
                // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败  
                if (SignUtil.checkSignature(DNBX_TOKEN, signature, timestamp, nonce)) {  
                    LOGGER.info("修改配置成功.");
                    response.getWriter().write(echostr);  
                } else {  
                    LOGGER.error("修改配置失败!"); 
                }
            }else{
                String respMessage = "异常消息!";
                try {
                    respMessage = weixinPost(request);
                    out.write(respMessage);
                    LOGGER.info("请求成功!");
                    LOGGER.info("微信服务: "+respMessage);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage()); 
                }
            }
        } catch (Exception e) {
            LOGGER.error("微信相应发生错误.");
        }finally{
            out.close();
        }
    }
    
    /**
     * 处理微信发来的请求
     * 
     * @param request
     * @return
     */
    public String weixinPost(HttpServletRequest request) {
        String respMessage = null;
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.xmlToMap(request);

            // 发送方帐号(open_id)
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 消息内容
            String content = requestMap.get("Content");
            // 二维码内容
            String ScanResult = requestMap.get("ScanResult");
            LOGGER.info("FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);
            // 文本消息
            if (MessageUtil.RESP_MESSAGE_TYPE_TEXT.equals(msgType)) {
            	String pattern = "^2[\\d]{10}";
            	boolean isMatch = Pattern.matches(pattern, content);
            	TextMessage text = new TextMessage();
                if(content.length() == 11 && isMatch){
            		content = selectYwh(content);
            		//自动回复
            		text.setContent(content);
	            }else{
	            	text.setContent("业务号格式不正确!");
	            }
                text.setToUserName(fromUserName);
                text.setFromUserName(toUserName);
                text.setCreateTime(System.currentTimeMillis());
                text.setMsgType(msgType);
                respMessage = MessageUtil.textMessageToXml(text);
            } else if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) { // 事件推送
                String eventType = requestMap.get("Event");// 事件类型
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
                    TextMessage text = new TextMessage();
                    text.setContent("欢迎关注,xxx");
                    text.setToUserName(fromUserName);
                    text.setFromUserName(toUserName);
                    text.setCreateTime(System.currentTimeMillis());
                    text.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_EVENT);
                    respMessage = MessageUtil.textMessageToXml(text);
                }else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {// 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
                	
                } else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
                    String eventKey = requestMap.get("EventKey");// 事件KEY值,与创建自定义菜单时指定的KEY值对应
                    if (eventKey.equals("V1001_TODAY_MUSIC")) {
                        TextMessage text = new TextMessage();
                        text.setContent("0755-86671980");
                        text.setToUserName(fromUserName);
                        text.setFromUserName(toUserName);
                        text.setCreateTime(System.currentTimeMillis());
                        text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                        respMessage = MessageUtil.textMessageToXml(text);
                    }
                } else if (eventType.equals(MessageUtil.EVENT_TYPE_SCANWAIT)) {// 自定义菜单二维码事件
//                	String eventKey = requestMap.get("EventKey");// 事件KEY值,与创建自定义菜单时指定的KEY值对应
//                	if (eventKey.equals("rselfmenu_1_0")) {//业务办理key值,在调试接口中body设置
	            		content = selectYwh(ScanResult);
	            		TextMessage text = new TextMessage();
	            		text.setContent(content);
	            		text.setToUserName(fromUserName);
	            		text.setFromUserName(toUserName);
	            		text.setCreateTime(System.currentTimeMillis());
	            		text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
	            		respMessage = MessageUtil.textMessageToXml(text);
//                	}
                }
            }
        }
        catch (Exception e) {
        	LOGGER.error("error....");
        }
        return respMessage;
    }
    
    public String selectYwh(String content){
    	RegBusSlsq regBusSlsq = new RegBusSlsq();
		regBusSlsq = regBusSlsqService.getByYwh(content);
		String djxl = DictUtils.getDictLabel(regBusSlsq.getDjxl(), "reg_bus_djxl", "");
//		String regbus13 = "(待初审)";
//		String regbus14 = "(待复审)";
//		String regbus15 = "(待核定)";
//		String regbus16 = "(待登簿)";
//		String regbus17 = "(待繕证)";
//		String regbus18 = "(待收费)";
//		String regbus19 = "(待发证)";
//		String regbus20 = "(待归档)";
		if(regBusSlsq != null){
    		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().
    				processInstanceId(regBusSlsq.getProcInsId())
    				.orderByHistoricActivityInstanceStartTime().asc().orderByHistoricActivityInstanceEndTime().asc().list();
    		String ActivityName = "";
//    		for (int i=0; i<list.size(); i++){
				HistoricActivityInstance histIns = list.get(list.size()-1);
				ActivityName = histIns.getActivityName();
//				if(i == 0){
//					content = "业务进度:    "+ActivityName;
//				}
//				if(i == list.size()-1){
//					if(histIns.getActivityName().equals("受理申请")){
//						ActivityName = histIns.getActivityName()+" "+regbus13;
//					}else if(histIns.getActivityName().equals("初审(主办科室)")){
//						ActivityName = histIns.getActivityName()+" "+regbus14;
//					}else if(histIns.getActivityName().equals("复审(登记中心主任)")){
//						ActivityName = histIns.getActivityName()+" "+regbus15;
//					}else if(histIns.getActivityName().equals("核定(登记局局长)")){
//						ActivityName = histIns.getActivityName()+" "+regbus16;
//					}else if(histIns.getActivityName().equals("登簿")){
//						ActivityName = histIns.getActivityName()+" "+regbus17;
//					}else if(histIns.getActivityName().equals("繕证")){
//						ActivityName = histIns.getActivityName()+" "+regbus18;
//					}else if(histIns.getActivityName().equals("收费")){
//						ActivityName = histIns.getActivityName()+" "+regbus19;
//					}else if(histIns.getActivityName().equals("发证")){
//						ActivityName = histIns.getActivityName()+" "+regbus20;
//					}else if(histIns.getActivityName().equals("归档")){
//						ActivityName = histIns.getActivityName()+" (已完结)";
//					}
					content = "您好,你查询的业务号为 "+content+" 的("+djxl+")业务已进行至 "+ActivityName+" 环节。";
//				}
//				if(i > 0 && histIns.getActivityName() != null){
//					content += "--->"+ ActivityName;
//				}
//			}
		}else{
			content = "暂无相关信息!";
		}
    	return content;
    }
    
    //办理查询页面
    @RequestMapping(value = "findSel")
    public String findSel(RegBusSlsq regBusSlsq, Model model, HttpServletRequest request, HttpServletResponse response) {
    	String bj = request.getParameter("bj");
    	if(StringUtils.isNoneBlank(bj)){
    		if(bj.equals("1")){
    			String ywh = request.getParameter("ywh");
    			String context = selectYwh(ywh);
    			model.addAttribute("ywh", ywh);
    			model.addAttribute("context", context);
    		}
    	}
    	model.addAttribute("bj", bj);
    	model.addAttribute("regBusSlsq", regBusSlsq);
    	return "modules/reg/base/regBusSlsqQueryWay";
    }
    
    //微信预约查询菜单进入
    @RequestMapping(value = "index")
    public String index(RegBaseYy regBaseYy, Model model, HttpServletRequest request, HttpServletResponse response) {
    	model.addAttribute("regBaseYy", regBaseYy);
    	return "modules/reg/base/regBaseYyIndex";
    }
    
    //预约页面
    @RequestMapping(value = "form")
	public String form(RegBaseYy regBaseYy, Model model, HttpServletRequest request, HttpServletResponse response) {
    	String bj = request.getParameter("bj");//进入方式入口610428199808088888
    	if(StringUtils.isNoneBlank(bj)){
    		if(bj.equals("1")){//查询方式进入
    			String id = request.getParameter("id");
    			regBaseYy = regBaseYyService.get(id);
    			model.addAttribute("yyrmc", regBaseYy.getYyrmc());
    			model.addAttribute("phone", regBaseYy.getYyrphone());
    			model.addAttribute("zjh", regBaseYy.getYyrzjh());
    			model.addAttribute("date", regBaseYy.getDates());
    			model.addAttribute("time", regBaseYy.getTimes());
    			model.addAttribute("yyh", regBaseYy.getYyh());
    			model.addAttribute("djdl", regBaseYy.getDjdl());
    			model.addAttribute("zjzl", regBaseYy.getYyrzjzl());
    		}
    	}
    	model.addAttribute("bj", bj);
    	model.addAttribute("regBaseYy", regBaseYy);
		return "modules/reg/base/regBaseYyForm";
	}
    
    //预约保存
    @RequestMapping(value = "save")
	public String save(Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
    	String view;
    	String djdl = request.getParameter("djdl");
    	String name = request.getParameter("name");
    	String phone = request.getParameter("phone");//13888888888
    	String zjzl = request.getParameter("zjzl");
    	String zjh = request.getParameter("zjh");//610425199009098888
    	String date = request.getParameter("date");
    	String time = request.getParameter("time");
    	String year = date.substring(0, 4);
    	String month = date.substring(5, 7);
    	String day = date.substring(8, 10);
    	RegBaseYy regBaseYy = new RegBaseYy();
    	regBaseYy.setYyrmc(name);
    	regBaseYy.setDates(date);
    	regBaseYy.setYyrzjzl(zjzl);//证件类型
		regBaseYy.setYyrzjh(zjh);
    	List<RegBaseYy> regBaseYyList = regBaseYyService.findList(regBaseYy);
    	if(regBaseYyList.size() > 0){
    		addMessage(redirectAttributes, "今日已经预约,不能重复预约");
    		view = "redirect:"+Global.getAdminPath()+"/reg/wechatInterface/form?bj=0";
    	}else{
    		regBaseYy.setYyrmc(null);
    		regBaseYy.setYyrzjzl(null);
    		regBaseYy.setYyrzjh(null);
    		regBaseYyList = regBaseYyService.findList(regBaseYy);
    		String maxNum = String.format("%04d",(regBaseYyList.size()+1));
    		regBaseYy.setYyh(year+month+day+maxNum);
    		regBaseYy.setDjdl(djdl);//登记类型
    		regBaseYy.setYyrmc(name);
    		regBaseYy.setYyrphone(phone);
    		regBaseYy.setYyrzjzl(zjzl);//证件类型
    		regBaseYy.setYyrzjh(zjh);
    		regBaseYy.setDates(date);
    		regBaseYy.setTimes(time);
    		regBaseYy.setYyfs("微信预约");
    		regBaseYyService.save(regBaseYy);
    		addMessage(redirectAttributes, "保存预约排号保存成功");
    		view = "redirect:"+Global.getAdminPath()+"/reg/wechatInterface/form?bj=1&id="+regBaseYy.getId();
    	}
		return view;
	}

    //预约查询页面
    @RequestMapping(value = "query")
    public String query(RegBaseYy regBaseYy, Model model, HttpServletRequest request, HttpServletResponse response) {
    	model.addAttribute("regBaseYy", regBaseYy);
    	return "modules/reg/base/regBaseYyQuery";
    }

    //预约查询列表页面
    @RequestMapping(value = "querylist")
    public String querylist(Model model, HttpServletRequest request, HttpServletResponse response) {
    	String name = request.getParameter("name");
    	String zjzl = request.getParameter("zjzl");
    	String zjh = request.getParameter("zjh");
    	RegBaseYy regBaseYy = new RegBaseYy();
    	regBaseYy.setYyrmc(name);
    	regBaseYy.setYyrzjzl(zjzl);//证件类型
		regBaseYy.setYyrzjh(zjh);
		Page<RegBaseYy> page = regBaseYyService.findPage(new Page<RegBaseYy>(request, response), regBaseYy); 
		List<RegBaseYy> listRegBaseYy = page.getList();
		RegBaseYy temp = new RegBaseYy();
		for(int i=0; i<listRegBaseYy.size(); i++){
			temp = listRegBaseYy.get(i);
			temp.setDates(temp.getDates()+" "+temp.getTimes());
		}
		page.setList(listRegBaseYy);
		model.addAttribute("name", name);
		model.addAttribute("zjzl", zjzl);
		model.addAttribute("zjh", zjh);
		model.addAttribute("page", page);
    	return "modules/reg/base/regBaseYyQueryList";
    }

}