package com.cftech.mp.reply.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.mp.fans.service.MpFanssService;
import com.cftech.mp.reply.service.CoreService;
import com.cftech.mp.reply.service.ReplyService;
import com.google.gson.Gson;
import org.mp.api.core.common.util.MessageUtil;
import org.mp.api.core.common.util.SignUtil;
import org.mp.api.core.req.model.message.IndustryTemplateMessageSend;
import org.mp.api.core.req.model.message.TemplateData;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.mp.api.wxsendmsg.test.JwSendMessageAPITest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 
 * @author lisw
 * @date 2016-08-24
 */
@Controller
@RequestMapping("/mobile/wechat")
public class MobileWechatController {
	
	@Autowired
	private MpAccountsService accountService;

	@Autowired
	private CoreService coreService;

	@Autowired
	private MpTokenUtil tokenUtil;

	@Autowired
	private ReplyService replyService;
	
	/**
	 * 确信能够成功与微信服务器对接
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/get",method=RequestMethod.GET)
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		
		//公众号ID
		String appid = request.getParameter("appid");
		
		String token = "";
		if(appid!=null){
			MpAccountsEntity accounts= accountService.getMpAccountsAppid(appid);
			if(accounts!=null){
				token=accounts.getToken();
			}
		}
		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce,token)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}
	

	/**
	 * 
	 */
	@RequestMapping(value = "/get",method=RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//调用核心业务类接收消息、处理消息、
		Map<String, String> map = null;
		try {
			map  = MessageUtil.parseXml(request);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String appid = request.getParameter("appid");

		String respMessage = coreService.processRequest(appid,map,request);
		//响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		out.close();
	}

	/**
	 *亚太接口发送模板消息
	 */
	@RequestMapping(value = "/sendTemplateMessage",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject sendTemplte(String unionId,String templateId,HttpServletRequest request,String dataJson){
		JSONObject rtnJson = new JSONObject();
		rtnJson.put("errorNo",0);
		rtnJson.put("errorMsg","发送成功");
		String restToken =request.getHeader("token");
		if(!StringUtils.equals(restToken,"ae810823caf24aaf2f392a25ebac0afb")){
			rtnJson.put("errorNo",1);
			rtnJson.put("errorMsg","token无效");
			return rtnJson;
		}
		if(StringUtils.isEmpty(unionId) || StringUtils.isEmpty(templateId) || StringUtils.isEmpty(dataJson)){
			rtnJson.put("errorNo",1);
			rtnJson.put("errorMsg","参数错误");
			return rtnJson;
		}
		String openId = replyService.getOpenId(unionId);
		if(StringUtils.isEmpty(openId)){
			rtnJson.put("errorNo",1);
			rtnJson.put("errorMsg","未找到对应的OPENID");
			return rtnJson;
		}
		MpAccountsEntity accounts= accountService.getMpAccountsAppid(SystemConfig.p.getProperty("WX_MP_SERVER_APPID"));
		IndustryTemplateMessageSend mc = new IndustryTemplateMessageSend();
		mc.setTemplate_id(templateId);
		mc.setTouser(openId);
		mc.setAccess_token(tokenUtil.getToken(accounts.getId()));
		StringBuffer json = new StringBuffer();
		Gson gson = new Gson();
		String objJson = gson.toJson(mc);
		json.append(objJson);
		json.setLength(json.length() - 1);
		json.append(",");
		json.append("\"data\":");
		json.append(dataJson);
		json.append("}");
		String result =JwTemplateMessageAPI.sendTemplateMsgJson(json.toString(), mc.getAccess_token());
		if(result!=null){
			JSONObject resultJson = JSON.parseObject(result);
			if(resultJson.containsKey("errcode") && !StringUtils.equals(resultJson.getString("errcode"),"0")){
				return resultJson;
			}
		}
		return rtnJson;
	}
	
}




