package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.OAuthConstants;
import com.palmnest.application.core.util.*;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.NeigouOrderManager;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;


/**
 * 点滴关怀-爱内购 集成 控制器
 *
 * @author qzy
 * @since 2017-11-28 17:00:00
 */
@Slf4j
@Controller
@RequestMapping(value = "/wechat/neigou*")
public class NeigouController {


	//当前环境地址(测试or 正式
	public static String webUrl = PropertiesKit.readPropertiesValue("callbackWebUrl", "wechat.properties");

	public static String meeting_index_url = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");
	
	public static String new_meeting_index_url = PropertiesKit.readPropertiesValue("new_meeting_index_url", "wechat.properties");

	public static String wjdc_index_url = PropertiesKit.readPropertiesValue("wjdc_index_url", "wechat.properties");
	public static String tsby_index_url = PropertiesKit.readPropertiesValue("tsby_index_url", "wechat.properties");

	@Autowired
	private PublicNoManager    publicNoManager;
	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private ReplayContentDao   replayContentDao;
	@Autowired
	private WeChatApiManager   weChatApiManager;
	@Autowired
	private AppUserManager     appuserManager;
	@Autowired
	private NeigouOrderManager neigouOrderManager;

	/**
	 * 爱内购 登录失败后处理 跳转
	 */
	@RequestMapping(value = "/neigouFailJump")
	public ModelAndView neigouFailJump(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//测试接口url
		//http://openapi.test.neigou.com/ChannelInterop/v1/Standard/Web/gateway?surl=http://test.neigou.com&furl=http://localhost:8080/super_reception/wechat/neigou/neigouFailJump?err=NG_ERRCODE?appid=wxffe70d6b42696497?user_mobile_id=13066855659&user=13066855659&company=cjqt_20171127&client_id=cjqt&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect

		//http://localhost:8080/super_reception/wechat/neigou/neigouFailJump?err=ERR_DIFF_COMPANY?appid=wxffe70d6b42696497?user_mobile_id=13066855659?user_company_id=company_10?neigouPdUrl=http://test.neigou.com/m/product-376205.html

		log.info("neigouFailJump=====do neigouFailJump method");

		Model model = new ExtendedModelMap();

		String err_code        = request.getParameter("err");//爱内购 返回错误code
		String appidStr        = "";//应用id 传参返回
		String user_mobile_id  = "";//用户id(手机号
		String user_company_id = "";//公司id
		String neigouPdUrl     = "";
		log.info("neigouFailJump err_code===:" + err_code);

		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);
			log.info("neigouFailJump " + reqName + "===:" + reqValue + "===");
		}

		if (StringUtils.isNotEmpty(err_code)) {

			if (err_code.indexOf("\\?") != 1) {
				String[] err_codes = err_code.split("\\?");
				err_code = err_codes[0];//err_code
				if (err_codes.length >= 2 && err_codes[1].indexOf("=") != 1) {
					appidStr = err_codes[1].split("=")[1];
				}
				if (err_codes.length >= 3 && err_codes[2].indexOf("=") != 1) {
					user_mobile_id = err_codes[2].split("=")[1];
				}

				if (err_codes.length >= 4 && err_codes[3].indexOf("=") != 1) {
					user_company_id = err_codes[3].split("=")[1];
				}
				if (err_codes.length >= 5 && err_codes[4].indexOf("=") != 1) {
					neigouPdUrl = err_codes[4].split("=")[1];
				}

			}

			if (StringUtils.isEmpty(appidStr)) {
				log.error("neigouFailJump===:返回 appid 为空");
			}

			if (StringUtils.isEmpty(user_mobile_id)) {
				log.error("neigouFailJump===:返回 user_id 手机号 为空");
			}

			if (StringUtils.isEmpty(user_company_id)) {
				log.error("neigouFailJump===:返回 user_company_id 公司id 为空");
			}

			if (StringUtils.isEmpty(neigouPdUrl)) {
				log.error("neigouPdUrl===:返回 neigouPdUrl 为空");
			}


			//使用login_token登录用户
			//1. 获得登录 login_token CreateAutoLoginURL
			//1.1 获得 accessToken

			//Load the properties file
			//**************不同 环境需要修改参数 oauth2Client.properties**************
			Properties config = NeigouOAuthUtils.getClientConfigProps(OAuthConstants.CONFIG_FILE_PATH);

			//Generate the OAuthDetails bean from the config properties file
			NeigouOAuth2Details oauthDetails = NeigouOAuthUtils.createOAuthDetails(config);

			//Validate Input
			if (!NeigouOAuthUtils.isValidInput(oauthDetails)) {
				log.info("Please provide valid config properties to continue.");
			}


			//	    NG_ERRCODE错误值：
			//		ERR_NOT_LOGIN 用户未登录  ok
			//		ERR_DIFF_USER 已经登录了不同的用户 ----force true 强制切换公司的 存在这种情况
			//		ERR_DIFF_COMPANY 用户已登录，但当前不在相应的公司 ----force true 强制切换公司的 存在这种情况
			//		UNSPECIFIC_CHANNEL 渠道不存在
			//		ERR_COMPANY_OR_USER_NOT_ACCESSABLE 用户或公司不存在 ok

			//API_PERMISSION_UNSPECIFIC

			if (err_code.equalsIgnoreCase(OAuthConstants.NEIGOU_ERR_NOT_LOGIN)) {//用户未登录


			} else if (err_code.equalsIgnoreCase(OAuthConstants.NEIGOU_ERR_COMPANY_OR_USER_NOT_ACCESSABLE)) {//用户或公司不存在

				//一个用户可能存在多个公司				
				//得到 accessToken
				String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);

				//创建用户
				//String createUserResult = NeigouOAuthUtils.CreateUser(oauthDetails,accessToken,user_company_id,user_mobile_id);


				AppUser userEn = appuserManager.getAppUsersByPhone(user_mobile_id);//查询用户 下方法需要名称---这块一个用户只同步一次 切换公司后  需要重建用户 返回的失败(重要
				if (null == userEn) {
					userEn = new AppUser();
					userEn.setUserMobile(user_mobile_id);
				}
				WxUser wxUser = scWxuserManager.getScWxuserByUserId(userEn.getId());
				if (null != wxUser) {//以微信昵称为主
					userEn.setNickName(wxUser.getNickName());
				}

				String createUserResult = NeigouOAuthUtils.CreateUser(oauthDetails, accessToken, user_company_id, userEn);

			}


			//下面重新登录一次 代码*************************************************

			//得到 accessToken
			String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);

			//创建用户登录使用的login_token
			//第三方用户唯一标识 （必填）---以手机号 维度 需判断 是否创建 **************
			//第三方用户所在公司唯一标识（非必填）--创建的公司 考虑 **************
			String login_token = NeigouOAuthUtils.CreateLoginToken(oauthDetails, accessToken, user_company_id, user_mobile_id);


			//得到login_urL 跳转

			//http://wx.palmnest.com/super_reception/wechat/neigou/neigouFailJump?err=NG_ERRCODE?appid=wxffe70d6b42696497	

			//多加一个手机id 以防止没有创建用户
			//1. appid
			//2. user_mobile_id
			//3. user_company_id
			//4. neigouPdUrl--内购专区或商品链接
			//需要接着传 这里登录还有可能失败
			String furl = webUrl + "/wechat/neigou/neigouFailJump?err=NG_ERRCODE?appid=" + appidStr + "?user_mobile_id=" + user_mobile_id + "?user_company_id=" + user_company_id;

			if (StringUtils.isNotEmpty(neigouPdUrl)) {
				furl += "?neigouPdUrl=" + neigouPdUrl;
				oauthDetails.setSurl(neigouPdUrl);
			}


			String login_urL = NeigouOAuthUtils.CreateLoginURL(oauthDetails, login_token, furl);


			log.info("login_urL===:" + login_urL);

			//login_urL="http://wx.palmnest.com/super_reception/wechat/frontSecurity/auth?redirectUrl="+login_urL;
			//login_urL=webUrl+"/wechat/frontSecurity/auth?redirectUrl="+login_urL;
			login_urL = webUrl + "/wechat/frontSecurity/auth?redirectUrl=" + URLEncoder.encode(login_urL, "utf-8");

			//URLEncoder encode
			String redirect_uri = URLEncoder.encode(login_urL, "utf-8");
			//拼装微信授权的URL
			StringBuffer redirectFullUrl = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?");
			redirectFullUrl.append("appid=" + appidStr);//应用id 通过返回地址再次获得
			redirectFullUrl.append("&redirect_uri=" + redirect_uri);//跳转地址
			redirectFullUrl.append("&response_type=code&scope=snsapi_base");
			redirectFullUrl.append("&state=1");
			redirectFullUrl.append("#wechat_redirect");
			log.info("neigouFailJump redirectFullUrl:" + redirectFullUrl);

			model.addAttribute("redirectFullUrl", redirectFullUrl.toString());
			return new ModelAndView("wechat/toWechatAuth", model.asMap());


		} else {
			log.error("neigouFailJump===:err_code 为空");
		}

		return null;
	}

	/**
	 * 爱内购 第一次点击图标跳转
	 * 填充参数 跳转
	 */
	@RequestMapping(value = "/neigouFirstJump")
	public ModelAndView neigouFirstJump(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();


			log.info("neigouFirstJump request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("neigouFirstJump " + reqName + "===:" + reqValue + "===");
			}


			//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffe70d6b42696497&redirect_uri=http%3A%2F%2Fwx.palmnest.com%2Fsuper_reception%2Fwechat%2FfrontSecurity%2Fauth%3FredirectUrl%3D%2Fwechat%2Fneigou%2FneigouFirstJump&response_type=code&scope=snsapi_base&state=1#wechat_redirect

			//测试接口url
			//http://localhost:8080/super_reception/wechat/neigou/neigouFirstJump?developId=gh_1b0d75ca6668&openId=o4L9Qty_oT8c4lWUQnkQ9ZAXgG_U	

			//http://openapi.test.neigou.com/ChannelInterop/v1/Standard/Web/gateway

			//首页
			//http://localhost:8080/super_reception/wechat/index/homePageView?openId=o4L9QtxtiMWB1mNcTPGms3J9hQ1g&developId=gh_1b0d75ca6668&organizationId=10&userId=

			//［必须］user 第三方用户唯一ID
			//［必填］client_id 分配的client_id
			//［必填] furl 访问失败后跳转地址
			//［选填］surl 访问成功后登录地址
			//［选填］company第三方公司唯一ID

			//Load the properties file
			//**************不同 环境需要修改参数 oauth2Client.properties**************
			Properties          config       = NeigouOAuthUtils.getClientConfigProps(OAuthConstants.CONFIG_FILE_PATH);
			NeigouOAuth2Details oauthDetails = NeigouOAuthUtils.createOAuthDetails(config);

			String     developId            = request.getParameter("developId");
			String     openId               = request.getParameter("openId");
			String     param_organizationId = request.getParameter("organizationId");
			WxPublicno publicno             = publicNoManager.getByDevelopId(developId);


			//订单处理 start

			//String accessTokenTemp = NeigouOAuthUtils.getAccessToken(oauthDetails);
			//System.out.println(accessTokenTemp);

			//String createUserResult = NeigouOAuthUtils.CreateUser(oauthDetails,accessTokenTemp,"company_10","18589021134");
			//System.out.println(createUserResult);

			//System.out.println(accessTokenTemp);
			//return null;
			//String createUserResultTemp = NeigouOAuthUtils.getUserMessage(oauthDetails,accessTokenTemp,replayContentDao,weChatApiManager);

			//neigouOrderManager.doNeigouOrderNews();

			//6~454

			//return null;

			//订单处理end


			String user_mobile_id = "";//第三方用户唯一ID 手机号
			String company_id     = oauthDetails.getDefault_companyid();//公司id 默认公司
			if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(developId)) {
				AppUser userEn = appUserManager.getAppUserByOpenId(developId, openId);
				if (userEn != null) {

					user_mobile_id = userEn.getUserMobile();

					int organizationId = 10;//为空默认一个项目
					if (null != userEn.getOrganizationId()) {
						organizationId = userEn.getOrganizationId();//楼栋id
					}

					TbOrganization organization = propertyManager.getTbOrganizationById(organizationId);
					if (organization.getIsSyncNeigou() != 1) {//同步公司

						//得到 accessToken
						String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);

						company_id = "company_" + organizationId;

						JSONObject companyJsonData = new JSONObject();
						companyJsonData.put("external_company_id", company_id);
						companyJsonData.put("company_name", company_id);
						companyJsonData.put("company_name_short", "超级前台");//固定"超级前台"
						companyJsonData.put("contacts_phone", "13066855659");
						companyJsonData.put("contacts_name", company_id);
						companyJsonData.put("contacts_email", "2290989798@qq.com");

						//创建公司
						String createCompanyResult = NeigouOAuthUtils.CreateCompany(oauthDetails, accessToken, companyJsonData);
						if (createCompanyResult.equals("true")) {//同步公司成功
							organization.setIsSyncNeigou(1);
							propertyManager.updateModel(organization);
						}
					} else {
						company_id = "company_" + organizationId;
					}

					int isSyncNeigou = userEn.getIsSyncNeigou();
					if (isSyncNeigou != 1) {//同步用户

						//得到 accessToken
						String accessToken = NeigouOAuthUtils.getAccessToken(oauthDetails);
						//创建用户
						//需要公司id
						//String createUserResult = NeigouOAuthUtils.CreateUser(oauthDetails,accessToken,company_id,user_mobile_id);					


						WxUser wxUser = scWxuserManager.getScWxuserByUserId(userEn.getId());
						if (null != wxUser) {//以微信昵称为主
							userEn.setNickName(wxUser.getNickName());
						}

						String createUserResult = NeigouOAuthUtils.CreateUser(oauthDetails, accessToken, company_id, userEn);

						if (createUserResult.equals("true")) {//同步用户成功
							userEn.setIsSyncNeigou(1);
							propertyManager.updateModel(userEn);
						}

					}

				}
			}

			if (StringUtils.isNotBlank(param_organizationId) && StringUtils.isNotBlank(openId)) {//从选项目那里过来

				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
				wxUser.setOrganizationId(Integer.parseInt(param_organizationId));
				propertyManager.updateModel(wxUser);
			}

			log.info("neigouFirstJump user_id(userMobile):" + user_mobile_id);

			//多加一个手机id 以防止没有创建用户
			String furl = webUrl + "/wechat/neigou/neigouFailJump?err=NG_ERRCODE?appid=" + publicno.getAppId() + "?user_mobile_id=" + user_mobile_id + "?user_company_id=" + company_id;


			String neigouPdUrl = request.getParameter("neigouPdUrl");
			if (StringUtils.isNotEmpty(neigouPdUrl)) {
				oauthDetails.setSurl(neigouPdUrl);
				furl += "?neigouPdUrl=" + neigouPdUrl;
			}

			//获得手机号
			String firstJumpUrl = NeigouOAuthUtils.getFirstJumpUrl(oauthDetails, company_id, user_mobile_id, furl);


			log.info("neigouFirstJump firstJumpUrl:" + firstJumpUrl);

			//login_urL="http://wx.palmnest.com/super_reception/wechat/frontSecurity/auth?redirectUrl="+login_urL;
			String redirect_uri = webUrl + "/wechat/frontSecurity/auth?redirectUrl=" + URLEncoder.encode(firstJumpUrl, "utf-8");

			//URLEncoder encode
			//String redirect_uri = URLEncoder.encode(firstJumpUrl,"utf-8");
			//拼装微信授权的URL
			StringBuffer redirectFullUrl = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?");
			redirectFullUrl.append("appid=" + publicno.getAppId());//应用id 通过返回地址再次获得
			redirectFullUrl.append("&redirect_uri=" + URLEncoder.encode(redirect_uri, "utf-8"));//跳转地址
			redirectFullUrl.append("&response_type=code&scope=snsapi_base");
			redirectFullUrl.append("&state=1");
			redirectFullUrl.append("#wechat_redirect");
			log.info("neigouFirstJump redirectFullUrl:" + redirectFullUrl);

			model.addAttribute("redirectFullUrl", redirectFullUrl.toString());
			return new ModelAndView("wechat/toWechatAuth", model.asMap());
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}

	}

	/**
	 * 空间家-跳转
	 * wx.palmnest.com/super_reception/wechat/neigou/spacehomeDo?userId=4173
	 */
	@RequestMapping(value = "/spacehomeDo")
	public String spacehomeDo(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();


			log.info("spacehomeDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("spacehomeDo " + reqName + "===:" + reqValue + "==");
			}


			String userId = request.getParameter("userId");

			//有token 取token 里的userId
			String token_useId = SupperAppUtils.getUserIdByToken(SupperAppUtils.getSuperDeskToten(request));
			if (StringUtils.isNotEmpty(token_useId)) {
				userId = token_useId;
			}

			//空间家平台参数
			String encrypt_key         = PropertiesKit.readPropertiesValue("spacehome_encrypt_key", "oauth2Client.properties");
			String platform_id         = PropertiesKit.readPropertiesValue("spacehome_platform_id", "oauth2Client.properties");
			String spacehome_login_url = PropertiesKit.readPropertiesValue("spacehome_login_url", "oauth2Client.properties");

			log.info("spacehomeDo encrypt_key" + encrypt_key);
			log.info("spacehomeDo platform_id" + platform_id);
			log.info("spacehomeDo login_url" + spacehome_login_url);

			//String encrypt_key="e10adc3949ba59abbe56e057f20f883e";

			//String userId="327";
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = userId + "|" + datatimeStr;
			log.info("spacehomeDo===" + sso_codeData);
			String sso_code = Java_AES_Cipher.encrypt(encrypt_key, sso_codeData);
			log.info("sso_code===" + sso_code);

			//https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code=DvEOITp4k5LYDEt47DLbdQ%3D%3D%3Aqd7d0c8z8M8R9ozBMYklEg%3D%3D&redirect_url=%2Fcaigou
			//String firstJumpUrl="https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code="+URLEncoder.encode(sso_code,"UTF-8")+"&redirect_url=%2Fcaigou";
			String firstJumpUrl = spacehome_login_url + "?method=sso&platform_id=" + platform_id + "&sso_code=" + URLEncoder.encode(sso_code, "UTF-8") + "&redirect_url=%2Fcaigou";

			log.info("spacehomeDo firstJumpUrl====" + firstJumpUrl);

			return "redirect:" + firstJumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	/**
	 * 会议室-跳转
	 * http://localhost:8080/super_reception/wechat/neigou/meetingDo?userId=4173
	 */
	@RequestMapping(value = "/meetingDo")
	public String meetingDo(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();
//			String meetType = request.getParameter("meetType");

			log.info("meetingDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("meetingDo " + reqName + "===:" + reqValue + "==");
			}

			//后继都用openid来对接
			String openId = request.getParameter("openId");
			if (StringUtils.isEmpty(openId)) {
				openId = request.getParameter("openid");
			}
			//tb_user
			//String userId=request.getParameter("userId");
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = openId + "|" + datatimeStr + "|" + CodeConstants.CLIENT_WECHAT;

			String token = GenPass.Encrypt(sso_codeData);

			//空间家平台参数
			//String meeting_index_url = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");
//			String firstJumpUrl ="";
//			if("1".equals(meetType)){
//				log.info("meetingDo new_meeting_index_url" + new_meeting_index_url);
//				firstJumpUrl =new_meeting_index_url + "?token=" + URLEncoder.encode(token, "UTF-8");
//			}else{
				log.info("meetingDo meeting_index_url" + meeting_index_url);
				String firstJumpUrl = meeting_index_url + "?token=" + URLEncoder.encode(token, "UTF-8");
//			}

			//https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code=DvEOITp4k5LYDEt47DLbdQ%3D%3D%3Aqd7d0c8z8M8R9ozBMYklEg%3D%3D&redirect_url=%2Fcaigou
			//String firstJumpUrl="https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code="+URLEncoder.encode(sso_code,"UTF-8")+"&redirect_url=%2Fcaigou";

			log.info("meetingDo firstJumpUrl====" + firstJumpUrl);

			return "redirect:" + firstJumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}
	
	/**
	 * 新会议室-跳转
	 * http://localhost:8080/super_reception/wechat/neigou/meetingDo?userId=4173
	 */
	@RequestMapping(value = "/newMeetingDo")
	public String newMeetingDo(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();

			String userId="";

			log.info("newMeetingDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("newMeetingDo " + reqName + "===:" + reqValue + "==");
				if("userId".equals(reqName)){
					userId=reqValue;
				}
			}

			//后继都用openid来对接
			String openId = request.getParameter("openId");
			if (StringUtils.isEmpty(openId)) {
				openId = request.getParameter("openid");
			}
			//tb_user
			//String userId=request.getParameter("userId");
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = openId + "|" + datatimeStr + "|" + CodeConstants.CLIENT_WECHAT+"|"+userId;

			String token = GenPass.Encrypt(sso_codeData);

			//空间家平台参数
			//String meeting_index_url = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");

			log.info("newMeetingDo new_meeting_index_url" + new_meeting_index_url);

			//https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code=DvEOITp4k5LYDEt47DLbdQ%3D%3D%3Aqd7d0c8z8M8R9ozBMYklEg%3D%3D&redirect_url=%2Fcaigou
			//String firstJumpUrl="https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code="+URLEncoder.encode(sso_code,"UTF-8")+"&redirect_url=%2Fcaigou";
			String firstJumpUrl = new_meeting_index_url + "?token=" + URLEncoder.encode(token, "UTF-8");

			log.info("newMeetingDo firstJumpUrl====" + firstJumpUrl);

			return "redirect:" + firstJumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	/**
	 * 体健-跳转
	 * http://localhost:8080/super_reception/wechat/neigou/meetingDo?userId=4173
	 */
	@RequestMapping(value = "/etongDo")
	public String etongDo(HttpServletRequest request, HttpServletResponse response) {

		try {
			Model model = new ExtendedModelMap();

			log.info("etongDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("etongDo " + reqName + "===:" + reqValue + "==");
			}

			String openId      = request.getParameter("openId");
			String developId   = request.getParameter("developId");
			String user_mobile = "";
			if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(developId)) {
				AppUser userEn = appUserManager.getAppUserByOpenId(developId, openId);
				if (userEn != null) {

					user_mobile = userEn.getUserMobile();
				}
			}
			String jumpUrl = HttpMesssageKit.getPathByAPI_SECRET(openId, user_mobile);


			log.info("meetingDo jumpUrl====" + jumpUrl);

			return "redirect:" + jumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	/**
	 * 问卷调查-跳转
	 * http://localhost:8080/super_reception/wechat/neigou/meetingDo?userId=4173
	 */
	@RequestMapping(value = "/wjdcDo")
	public String wjdcDo(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();
            // prt = 2 表示https.
		    String prt = request.getParameter("prt");
			log.info("meetingDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("meetingDo " + reqName + "===:" + reqValue + "==");
			}

			//后继都用openid来对接
			String openId = request.getParameter("openId");
			if (StringUtils.isEmpty(openId)) {
				openId = request.getParameter("openid");
			}
			//tb_user
			//String userId=request.getParameter("userId");
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = openId + "|" + datatimeStr + "|" + CodeConstants.CLIENT_WECHAT;

			String token = GenPass.Encrypt(sso_codeData);


			log.info("wjdcDo wjdc_index_url" + wjdc_index_url);

			//https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code=DvEOITp4k5LYDEt47DLbdQ%3D%3D%3Aqd7d0c8z8M8R9ozBMYklEg%3D%3D&redirect_url=%2Fcaigou
			//String firstJumpUrl="https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code="+URLEncoder.encode(sso_code,"UTF-8")+"&redirect_url=%2Fcaigou";
			String firstJumpUrl = wjdc_index_url + "?token=" + URLEncoder.encode(token, "UTF-8");
			if("2".equals(prt)){
				//需要重定向到https
				firstJumpUrl = firstJumpUrl.replaceFirst("http", "https");
			}
			//重定向地址
			String rdurl= request.getParameter("rdurl");
			if(rdurl != null && !"".equals(rdurl))
			{
				firstJumpUrl = rdurl + "?token=" + URLEncoder.encode(token, "UTF-8");
			}
			log.info("meetingDo firstJumpUrl====" + firstJumpUrl);
			String ext = request.getParameter("ext");
			log.info("meetingDo ext====" + ext);
			if(StringUtils.isNotEmpty(ext)){
				firstJumpUrl = firstJumpUrl +"&ext="+ext;
				log.info("meetingDo firstJumpUrl====" + firstJumpUrl);
			}
			return "redirect:" + firstJumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}


	/**
	 * 投诉表扬-跳转
	 * http://localhost:8080/super_reception/wechat/neigou/meetingDo?userId=4173
	 */
	@RequestMapping(value = "/tsbyDo")
	public String tsbyDo(HttpServletRequest request, HttpServletResponse response) {


		try {
			Model model = new ExtendedModelMap();
			// prt = 2 表示https.
			String prt = request.getParameter("prt");

			log.info("tsbyDo request.getRequestURI()====" + request.getRequestURI());
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName  = e.nextElement().toString();
				String reqValue = request.getParameter(reqName);
				log.info("tsbyDo " + reqName + "===:" + reqValue + "==");
			}

			//后继都用openid来对接
			String openId = request.getParameter("openId");
			if (StringUtils.isEmpty(openId)) {
				openId = request.getParameter("openid");
			}
			//tb_user
			//String userId=request.getParameter("userId");
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = openId + "|" + datatimeStr + "|" + CodeConstants.CLIENT_WECHAT;

			String token = GenPass.Encrypt(sso_codeData);

			//空间家平台参数

			log.info("tsbyDo tsby_index_url" + tsby_index_url);

			//https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code=DvEOITp4k5LYDEt47DLbdQ%3D%3D%3Aqd7d0c8z8M8R9ozBMYklEg%3D%3D&redirect_url=%2Fcaigou
			//String firstJumpUrl="https://test1.superxz.com/auth?method=sso&platform_id=100000021&sso_code="+URLEncoder.encode(sso_code,"UTF-8")+"&redirect_url=%2Fcaigou";
			String firstJumpUrl = tsby_index_url + "?token=" + URLEncoder.encode(token, "UTF-8");
			if("2".equals(prt)){
				//需要重定向到https
				firstJumpUrl = firstJumpUrl.replaceFirst("http", "https");
			}
			log.info("tsbyDo firstJumpUrl====" + firstJumpUrl);

			return "redirect:" + firstJumpUrl;// 要跳转的地址
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			throw new RuntimeException("请检查网络或稍后再试" + LogExceptionStackUtil.LogExceptionStack(e));
		}
	}

	public static void main(String[] args) {
		//String openId=request.getParameter("openId");
		String userId       = "o31ne0SVE0t185QQ3-NeYlSW28dc";
		Long   datatimeStr  = new Date().getTime();
		String sso_codeData = userId + "|" + datatimeStr + "|" + CodeConstants.CLIENT_WECHAT;

		//String sso_codeData="qzy2018st" +"|"+datatimeStr+"|"+CodeConstants.CLIENT_PC;

		String token = GenPass.Encrypt(sso_codeData);
		System.out.println(token);
	}

}
