package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.PropertiesKit;
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.OrganizationManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.NeigouManager;
import com.palmnest.service.estateserve.PublicNoManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.user.ModuleUserCountService;
import com.palmnest.service.virtProject.UserAccountService;
import com.palmnest.service.virtProject.VirtualArchService;
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.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * 微信端业务的前置控制器
 * 作用：验证用户是否注册
 *
 * @author yubing
 * @since 2017-1-14
 */
@Slf4j
@Controller
@RequestMapping(value = "/wechat/frontSecurity*")
public class FrontSecurityController {


	@Autowired
	private WeChatApiManager       weChatApiManager;
	@Autowired
	private AppUserManager         appUserManager;
	@Autowired
	private ScWxuserManager        scWxuserManager;
	@Autowired
	private UserAccountService     userAccountService;
	@Autowired
	private OrganizationManager    organizationManager;
	@Autowired
	private NeigouManager          neigouManager;
	@Autowired
	private ModuleUserCountService moduleUserCountService;
	@Autowired
	private PublicNoManager        publicNoManager;
	@Autowired
	private       VirtualArchService virtualArchService;

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

	/**
	 * 访问的安全认证
	 * 校验用户是否注册登录.
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth")
	public ModelAndView auth(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("auth uri:" + request.getRequestURI());
		Model   model       = new ExtendedModelMap();
		boolean authFlag    = false;
		String  redirectUrl = "wechat/bindPhone";
		String  actype      = request.getParameter("actype");
		String  urlKey      = request.getParameter("urlKey");
		String  openId      = request.getParameter("openId");
		String  developId   = request.getParameter("developId");
		String  orgId       = request.getParameter("orgId");
		String  serviceCode = "";// 服务模块编码(用于统计用户活跃次数)

		String redirectUrl_ = request.getParameter("redirectUrl");
		// 公众号关联项目列表
		List<Map<String, Object>> relationOrgs = null;

		//根据服务的是否注册判断该服务是否需要跳转到绑定手机的页面-----lmz
		//微信网页授权获取用户基本信息处理方式
		if (StringUtils.isEmpty(actype)) {

			String code  = request.getParameter("code"); // 公众号网页授权返回code
			String state = request.getParameter("state"); // 自定义参数(公众号的ID与服务编码拼接,例如:  1;FW-001);是在获取服务列表的时候拼接的;

			log.info("================ 微信网页授权返回code:" + code + " ================");
			log.info("================ 自定义参数(公众号id和服务编码)state:" + state + " ================");
			// 公众号ID
			String publicId = state;

//			if (state.contains(";")) {
			if (state.indexOf(";") != -1) {
				publicId = state.split(";")[0];
				serviceCode = state.split(";")[1]; // 切割state参数来获取服务编码
			}

			try{
				int i = Integer.parseInt(publicId);
			}catch (Exception ex)
			{
				throw new Exception("参数非法");
			}
			// ---重要
			//2019.11.08融合公众号菜单重定向到新系统首页链接  start-------

			String newUrl = newWebUrl + "/wx/main";
			if (redirectUrl_.indexOf("/wechat/index/homePageView") != -1) {
				redirectUrl_ = "redirect:" + newWebUrl + "/api/wechat/front/auth2?code=" + code + "&state=" + publicId + "&redirectUrl=" + newUrl;
				return new ModelAndView(redirectUrl_, model.asMap());
			}

			// ---重要
			//2019.11.08融合公众号菜单重定向到新系统首页链接  end--------

			if (org.apache.commons.lang3.StringUtils.isBlank(developId) &&
					org.apache.commons.lang3.StringUtils.isNotBlank(publicId)) {

				WxPublicno publicno = publicNoManager.getWxPublicnoById(Integer.parseInt(publicId));
				// TODO 通行码 bug 如果没找到呢
				developId = publicno.getDevelopId();
			}

			relationOrgs = publicNoManager.getWxPublicnoOrgRelations(developId);

			// 通过code换取网页授权access_token
			Map<String, String> retMap = weChatApiManager.oauth2(code, publicId);
			Map<String, Object> map    = JSON.parseObject(retMap.get("jsonStr"), Map.class);
			openId = map == null ? "" : map.get("openid") == null ? "" : map.get("openid").toString();
			developId = retMap.get("developid");
			log.info("FrontSecurityController auth() .oauth_response openid and developid:" + openId + ";" + developId + ";serviceCode:" + serviceCode);
		}

		// 如果公众下有且只有一个项目,不用跳转
		if (!relationOrgs.isEmpty() && relationOrgs.size() == 1) {
			orgId = relationOrgs.get(0).get("id").toString();
			model.addAttribute("organizationId", orgId);
		}

		//保存粉丝start
		AppUser user = null;
		if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(developId)) {
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				if (wxUser.getOrganizationId() != null) {
					user = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
					if (user != null && user.getIsLogin() == 1) {
						//authFlag=true;
						model.addAttribute("userId", user.getId());
					}
				} else {
					return new ModelAndView("wechat/selectProject", model.asMap());
				}
			} else {
				scWxuserManager.saveWxUser(openId, developId);//到这里就会保存粉丝
				//项目信息为空，跳转到选择项目
				return new ModelAndView("wechat/selectProject", model.asMap());
			}
		} else {
			String userId = request.getParameter("userId");
			if (StringUtils.isNotBlank(userId)) {
				user = appUserManager.get(Integer.parseInt(userId));
				if (user != null) {
					authFlag = true;
				} else {
					scWxuserManager.saveWxUser(openId, developId);
				}
				model.addAttribute("userId", userId);
			}
		}

		if (user != null && StringUtils.isNotBlank(serviceCode)) {
			// 模块日用户量统计
			moduleUserCountService.saveModuleUserToRedis(serviceCode, user.getId(), user.getOrganizationId());
		}


		redirectUrl = "redirect:" + redirectUrl_;
		log.info("=======FrontSecurityController authFlag ========：" + authFlag);

		//处理(传递)参数
		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);

			log.info("======= frontSecurity auth reqName " + reqName + "========：" + reqValue);

			model.addAttribute(reqName, reqValue);
		}
		//企业迁出、电子放行条
		//订餐、电子放行条、访客、会议室
		//电子放行、会议室需要同时支持企业账号和个人
		log.info("====begin跳转redirectUrl_：" + redirectUrl_);
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (StringUtils.isEmpty(orgId)) {
			orgId = wxUser.getOrganizationId() + "";
		}
		TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(orgId));
		log.info("====项目信息：" + org.getId() + "accountType:" + org.getAccountType());

		//小邮局项目编码
		if (StringUtils.isNotEmpty(org.getPostofficeClient())) {
			model.addAttribute("Client", org.getPostofficeClient());
		} else {
			model.addAttribute("Client", "");
		}
		//个人账号类没有绑定跳转绑定手机号码
		//用户手机号码不存在走绑定
		model.addAttribute("oldUrl", redirectUrl_);

		if (org.getAccountType() == null || org.getAccountType() == 0) {
			log.info("====走企业账号类=====");
			if (redirectUrl_.indexOf("/super_wechat/release") != -1
					|| redirectUrl_.indexOf("/super_wechat/air") != -1  //空调加时
			) {
				int isHave = userAccountService.isHaveAccLogin(openId, wxUser.getOrganizationId() == null ? "" : wxUser.getOrganizationId().toString());
				if (isHave != 1) {
					redirectUrl = "redirect:/wechat/appUser/virAccount";
					log.info("====2跳转redirectUrl_：" + redirectUrl);
				} else {
					redirectUrl = "redirect:" + redirectUrl_;
				}
			}
		} else if (org.getAccountType() == 1) {
			if (redirectUrl_.indexOf("/super_wechat/release") != -1
//			  || redirectUrl_.indexOf("/visitor")!=-1
					|| redirectUrl_.indexOf("/super_wechat/air") != -1  //空调加时
//			  || redirectUrl_.indexOf("/wechat/neigou/wjdcDo")!=-1  //问卷调查
//			  || redirectUrl_.indexOf("/wechat/neigou/tsbyDo")!=-1  //投诉建议
					|| redirectUrl_.indexOf("/newneigou/indexPage") != -1 // 企业内购
					|| redirectUrl_.indexOf("/super_wechat/dist") != -1
					|| redirectUrl_.indexOf("/wx/flashdeliver") != -1
					|| redirectUrl_.indexOf("/wx/ordermealwx") != -1
			) {
				log.info("====走个人账号类=====");
				//如果已经登录航电平台，但是不在白名单，则提示更换手机号码登录
				if (user == null || user.getIsLogin() == 0) {
					redirectUrl = "wechat/bindPhone";
				} else if (user != null && user.getIsLogin() == 1 && user.getIsBinding() == 0) {
					redirectUrl = "wechat/changeAccountLogin";
				}
			}

			if (redirectUrl_.indexOf("/visitor") != -1
					|| redirectUrl_.indexOf("/wechat/neigou/wjdcDo") != -1  //问卷调查
					|| redirectUrl_.indexOf("/wechat/neigou/tsbyDo") != -1  //投诉建议
			) {
				// 访客功能为低级权限功能,即非白名单用户也可以使用
				// 1.如果用户不存在(即非白名单用户)或未登录,则去登录界面注册或登录
				log.info("==== 访客流程 =====");
				if (user == null || user.getIsLogin() == 0) {
					redirectUrl = "wechat/bindPhone";
				}
			}
		}

		//企业迁出暂走企业账号
		if (redirectUrl_.indexOf("/super_wechat/emig") != -1) {
			int isHave = userAccountService.isHaveAccLogin(openId, wxUser.getOrganizationId() == null ? "" : wxUser.getOrganizationId().toString());
			if (isHave != 1) {
				redirectUrl = "redirect:/wechat/appUser/virAccount";
				log.info("====2跳转redirectUrl_：" + redirectUrl);
			} else {
				redirectUrl = "redirect:" + redirectUrl_;
			}
		}

		if (user != null) {
			// 用户登录状态下,直接取用户的相关信息,然后直接跳转企业内购页面
			// --------------------- 企业内购模块参数 start ---------------------
			model.addAttribute("userMobile", user.getUserMobile());
			model.addAttribute("virId", user.getVirtualArchId());
			model.addAttribute("orgId", user.getOrganizationId());
			// --------------------- 企业内购模块参数 end ---------------------
		}

		if (redirectUrl.indexOf("/wx/ordermealwx") != -1) {
			//订餐
			redirectUrl = redirectUrl + "&fromStatus=1&mealType=1,2,3&serviceLevel=3&accType=3";
			log.info("ordermealwx:" + redirectUrl);
		}

		log.info("======== orgId:{},==openId:{},===developId:{}", orgId, openId, developId);
		log.info("===end=跳转redirectUrl_：" + redirectUrl);
		return new ModelAndView(redirectUrl, model.asMap());
	}

	/**
	 * 访问的安全认证
	 * 校验用户是否注册登录.
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/mailAuth")
	public ModelAndView mailAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {

		log.info("=======FrontSecurityController mailAuth========：");

		log.info("auth uri:" + request.getRequestURI());
		Model  model     = new ExtendedModelMap();
		String actype    = request.getParameter("actype");
		String openId    = "";
		String developId = "";

		//微信网页授权获取用户基本信息处理方式
		if (StringUtils.isEmpty(actype)) {
			String code  = request.getParameter("code");
			String state = request.getParameter("state");  //公众号的ID

			log.info("=======FrontSecurityController code========：" + code);
			log.info("=======FrontSecurityController state========：" + state);


			Map<String, String> retMap = weChatApiManager.oauth2(code, state);
			Map<String, Object> map    = JSON.parseObject(retMap.get("jsonStr"), Map.class);
			openId = (String) map.get("openid");
			developId = (String) retMap.get("developid");
			log.info("FrontSecurityController auth() .oauth_response openid and developid:" + openId + ";" + developId);
		}
		//传参方式
		else {
			openId = request.getParameter("openId");
			developId = request.getParameter("developId");
		}

		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		String redirectUrl_ = request.getParameter("redirectUrl");


		log.info("=======FrontSecurityController 最终地址 使用redirectUrl========：" + redirectUrl_);

		//处理(传递)参数
		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);

			log.info("======= frontSecurity mailAuth reqName " + reqName + "========：" + reqValue);

			model.addAttribute(reqName, reqValue);
		}


		log.info("======end ModelAndView redirectUrl====" + redirectUrl_);
		return new ModelAndView(redirectUrl_, model.asMap());
	}


	//判断是否关注
	public boolean judgeIsSubscribe(String openId, String developId) {

		boolean isSubscribe = false;
		if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(developId)) {
			UserInfo weixinUser = weChatApiManager.getUserInfo(developId, openId);
			if (null == weixinUser) {//没有关注
				isSubscribe = false;
			} else {
				isSubscribe = true;
			}
		}

		return isSubscribe;
	}

	/**
	 * 访问的安全认证
	 * 校验员工是否信息绑定.
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/authStaff")
	public ModelAndView authStaff(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("auth uri:" + request.getRequestURI());
		Model   model       = new ExtendedModelMap();
		boolean authFlag    = false;
		String  redirectUrl = "redirect:/wechat/staff/staffMsgBind";
		String  openId      = "";
		String  developId   = "";

		//微信网页授权获取用户基本信息处理方式
		String              code   = request.getParameter("code");
		String              state  = request.getParameter("state");  //公众号的ID
		Map<String, String> retMap = weChatApiManager.oauth2(code, state);
		Map<String, Object> map    = JSON.parseObject(retMap.get("jsonStr"), Map.class);
		openId = (String) map.get("openid");
		developId = (String) retMap.get("developid");
		log.info("FrontSecurityController authStaff() .oauth_response openid and developid:" + openId + ";" + developId);

		if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(developId)) {
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null && wxUser.getUserId() != null) {
				model.addAttribute("userId", wxUser.getUserId());
				authFlag = true;
			}
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
		} else {
			String userId = request.getParameter("userId");
			if (StringUtils.isNotBlank(userId)) {
				AppUser user = appUserManager.get(Integer.parseInt(userId));
				if (user != null) {
					authFlag = true;
				}
				model.addAttribute("userId", userId);
			}
		}
		String redirectUrl_ = request.getParameter("redirectUrl");
		//用户已经注册，服务端重定向具体业务控制器
		if (authFlag) {
			redirectUrl = "redirect:" + redirectUrl_;  //   redirect:/pblic/no/list
		}
		log.info("=======redirectUrl_========：" + redirectUrl_);
		//处理(传递)参数
		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);
			model.addAttribute(reqName, reqValue);
		}
		return new ModelAndView(redirectUrl, model.asMap());
	}

	@RequestMapping({"/auth2"})
	public ModelAndView auth2(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.log.info("auth uri:" + request.getRequestURI());
		Model   model       = new ExtendedModelMap();
		boolean authFlag    = false;
		String  redirectUrl = "redirect:/wechat/appUser/bindphone";
		String  actype      = request.getParameter("actype");
		String  urlKey      = request.getParameter("urlKey");
		String  openId      = "";
		String  developId   = "";
		if (StringUtils.isEmpty(actype)) {
			String code  = request.getParameter("code");
			String state = request.getParameter("state");

			Map<String, String> retMap = this.weChatApiManager.oauth2(code, state);
			Map<String, Object> map    = (Map) JSON.parseObject((String) retMap.get("jsonStr"), Map.class);
			openId = (String) map.get("openid");
			developId = (String) retMap.get("developid");
			this.log.info("FrontSecurityController auth() .oauth_response openid and developid:" + openId + ";" + developId);
		} else {
			openId = request.getParameter("openId");
			developId = request.getParameter("developId");
		}
		if ((StringUtils.isNotBlank(openId)) && (StringUtils.isNotBlank(developId))) {
			AppUser user = this.appUserManager.getAppUserByOpenId(developId, openId);
			if (user != null) {
				authFlag = true;
				model.addAttribute("userId", user.getId());
			} else {
				this.scWxuserManager.saveWxUser(openId, developId);
			}
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
		} else {
			String userId = request.getParameter("userId");
			if (StringUtils.isNotBlank(userId)) {
				AppUser user = (AppUser) this.appUserManager.get(Integer.valueOf(Integer.parseInt(userId)));
				if (user != null) {
					authFlag = true;
				} else {
					this.scWxuserManager.saveWxUser(openId, developId);
				}
				model.addAttribute("userId", userId);
			}
		}
		String redirectUrl_ = request.getParameter("redirectUrl");
		System.out.println("传入参数redirectUrl：" + redirectUrl_);
		if ((authFlag) ||
				((urlKey != null) && (!urlKey.equals("")) && (urlKey.equals("Cterminal"))) ||
				("index".equals(redirectUrl_)) ||
				("/wechat/index/homePageView".equals(redirectUrl_)) ||
				("/wechat/recharge/toFlowRecharge".equals(redirectUrl_)) ||
				("/wechat/memberManage/joinCompanyPage".equals(redirectUrl_)) ||
				("/wechat/navigation/filmIndex".equals(redirectUrl_)) ||
				(redirectUrl_.indexOf("/wechat/postoffice") != -1) ||
				("/wechat/sikpMall/customerShop".equals(redirectUrl_))) {
			redirectUrl = "redirect:" + redirectUrl_;
		}

		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);

			this.log.info("======= frontSecurity auth reqName " + reqName + "========��" + reqValue);

			model.addAttribute(reqName, reqValue);
		}
		this.log.info("========/wechat/spacehome/spacehomeDo.equals(redirectUrl_)" + "/wechat/spacehome/spacehomeDo".equals(redirectUrl_));
		if ((!authFlag) && ("/wechat/neigou/neigouFirstJump".equals(redirectUrl_)) && (!judgeIsSubscribe(openId, developId))) {
			this.log.info("======judgeIsSubscribe");

			redirectUrl = "redirect:/wechat/index/judgeIsSubscribe";
		} else if ((!authFlag) && ("/wechat/neigou/neigouFirstJump".equals(redirectUrl_)) && (StringUtils.isNotBlank(openId))) {
			this.log.info("======neigouFirstJump");
			WxUser wxUser = this.scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser.getOrganizationId() == null) {
				String userStatus = "0";
				String register   = "0";

				model.addAttribute("userStatus", userStatus);
				model.addAttribute("register", register);

				redirectUrl = "redirect:/wechat/index/neigouChoiceAddress";
			}
		}
		System.out.println("最终redirectUrl：" + redirectUrl);
		this.log.info("======end ModelAndView redirectUrl====" + redirectUrl);
		return new ModelAndView(redirectUrl, model.asMap());
	}


	public static void main(String[] args) {


		String state = "56";

		System.out.println(state.contains(";"));
	}
}
