package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.Constants;
import com.palmnest.application.bean.ReturnObject;
import com.palmnest.service.wechat.WeChatAccessManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
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 org.springframework.web.servlet.ModelAndView;

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

/**
 * 微信平台：针对微信平台请求和发送处理--测试所用
 *
 * @author yubing
 * @since 2015-02-27
 */
@Slf4j
@Controller
@RequestMapping("/wechat/api/*")
public class WeChatApiController {

	@Autowired
	private WeChatApiManager    weChatApiManager;
	@Autowired
	private WeChatAccessManager weChatAccessManager;

	@RequestMapping(value = "/executePage")
	public ModelAndView executePage(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView("wechat/initPage");
	}

	@RequestMapping(value = "executeMenu", method = {RequestMethod.GET, RequestMethod.POST})
	public @ResponseBody
	String executeMenu(HttpServletRequest request, HttpServletResponse response) {
		String developId = request.getParameter("developId");
		String actType   = request.getParameter("actType");
		String json      = request.getParameter("json");
		try {
			if ("1".equals(actType)) {
				if (weChatApiManager.createMenu(developId, json)) {
					return "true";
				} else {
					return "false";
				}
			} else if ("2".equals(actType)) {
				return weChatApiManager.getMenuInfo(developId);
			} else if ("3".equals(actType)) {
				if (weChatApiManager.deleteMenu(developId)) {
					return "true";
				} else {
					return "flase";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "flase";
	}

	@RequestMapping(value = "subscribe", method = {RequestMethod.GET, RequestMethod.POST})
	public void subscribe(HttpServletRequest request, HttpServletResponse response) {
		String       developId = request.getParameter("developId");
		StringBuffer xmlMsg    = new StringBuffer("<xml><ToUserName><![CDATA[" + developId + "]]></ToUserName>");
		xmlMsg.append("<FromUserName><![CDATA[oTGfjsvSRXHfCzEut02cPZ6tFz10]]></FromUserName>");
		xmlMsg.append("<CreateTime>1348831860</CreateTime>");
		xmlMsg.append("<MsgType><![CDATA[event]]></MsgType>");
		xmlMsg.append("<Event><![CDATA[subscribe]]></Event>");
		xmlMsg.append("</xml>");
		try {
			String outPut = weChatAccessManager.saveProcessing(xmlMsg.toString());
			outputJson(response, outPut);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "unsubscribe", method = {RequestMethod.GET, RequestMethod.POST})
	public void unsubscribe(HttpServletRequest request, HttpServletResponse response) {
		String       developId = request.getParameter("developId");
		StringBuffer xmlMsg    = new StringBuffer("<xml><ToUserName><![CDATA[" + developId + "]]></ToUserName>");
		xmlMsg.append("<FromUserName><![CDATA[o-6WPuOI5RxrFVs37yM9rpFc7vBU]]></FromUserName>");
		xmlMsg.append("<CreateTime>1348831860</CreateTime>");
		xmlMsg.append("<MsgType><![CDATA[event]]></MsgType>");
		xmlMsg.append("<Event><![CDATA[unsubscribe]]></Event>");
		xmlMsg.append("</xml>");
		try {
			String outPut = weChatAccessManager.saveProcessing(xmlMsg.toString());
			outputJson(response, outPut);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "doText", method = {RequestMethod.GET, RequestMethod.POST})
	public void doText(HttpServletRequest request, HttpServletResponse response) {
		String textXml = request.getParameter("textXml");
		try {
			String outPut = weChatAccessManager.saveProcessing(textXml);
			outputJson(response, outPut);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void outputJson(HttpServletResponse response, String json) {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询用户角色
	 *
	 * @param request
	 * @param response
	 * @return 树
	 */
	@RequestMapping(value = "getAccessToken", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
	public @ResponseBody
	String queryAppRoleTree(HttpServletRequest request,
							HttpServletResponse response) {
		ReturnObject rt        = new ReturnObject();
		String       developId = request.getParameter("developId");
		String       str       = "";
		if (StringUtils.isNotBlank(developId)) {
			try {
				String              accessToken = weChatApiManager.getAccessToken(developId);
				Map<String, String> resultMap   = new HashMap<String, String>();
				resultMap.put("accessToken", accessToken);

				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
				rt.setReturnDTO(resultMap);
			} catch (Exception e) {
				rt.setResult(Constants.RESULT_FIAL);
				rt.setResultCode(Constants.RESULTCODE_EXCEPTION);
				rt.setResultDesc("服务器异常");
			}
		} else {
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
			rt.setResultDesc("请检查参数");
		}
		str = JSONObject.fromObject(rt).toString();
		if (StringUtils.isNotBlank(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}
		return str;
	}
}
