package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppCommonResultDto;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.dto.output.VirAccountDto;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.ServiceProjectAllocation;
import com.palmnest.model.estateserve.ServiceTypeInfo;
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.ScWxuserManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.estateserve.ServiceTypeInfoManager;
import com.palmnest.service.user.ModuleUserCountService;
import com.palmnest.service.virtProject.VirtualArchService;
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.Map;

/**
 * @Author HXT
 * @Description 航电模块 接口控制器 /wechat/repair
 * @Date 2018/11/1 20:50
 **/
@Slf4j
@Controller
@RequestMapping(value = "/wechat/repair")
public class WechatRepairUserController {


	@Autowired
	private ScWxuserManager                 scWxuserManager;
	@Autowired
	private AppUserManager                  appUserManager;
	@Autowired
	private ModuleUserCountService          moduleUserCountService;
	@Autowired
	private OrganizationManager             organizationManager;
	@Autowired
	private VirtualArchService              virtualArchService;
	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private ServiceTypeInfoManager          serviceTypeInfoManager;

	/**
	 * 校验当前用户是否已经注册
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/checkRegister")
	public ModelAndView checkRegister(HttpServletRequest request, HttpServletResponse response) {

		Model  model       = new ExtendedModelMap();
		String redirectUrl = request.getParameter("redirectUrl");
		String openId      = request.getParameter("openId");
		if (StringUtils.isBlank(openId)) {
			openId = request.getParameter("openid");
		}
		String developId = request.getParameter("developId");
		if (StringUtils.isBlank(developId)) {
			developId = request.getParameter("developid");
		}
		String  projectno     = request.getParameter("projectno");
		String  serviceCode   = request.getParameter("serviceCode");// 服务模块编码(用于统计用户活跃次数)
		String  serviceNumber = request.getParameter("serviceNumber");
		WxUser  wxUser        = scWxuserManager.getScWxuserByOpenId(openId);
		Integer orgId         = wxUser.getOrganizationId();
		log.info("=================== 维修服务、报事服务、投诉与表扬 服务模块请求,校验用户是否注册 ===================");
		log.info("=================== 跳转链接 redirectUrl=======>:{}===================", redirectUrl);

		//未注册跳转路径
		String redirectUrl_ = "wechat/bindPhone";
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("oldUrl", redirectUrl);

		//获取当前登录用户所选择的项目id
		if (wxUser != null) {
			log.info("developId:{}-----openId:{}-----orgId:{}", developId, openId, wxUser.getOrganizationId());

			try {
//            	VirAccountDto dto=virtualArchService.getUserInfo(openId,orgId+"",null);
				if ("QYFK".equals(serviceNumber)) {
					AppResultDto  rto = virtualArchService.getUserInfo(openId, orgId + "", null);
					VirAccountDto dto = null;
					if (rto.getCode() == AppConstants.SUCCESS_CODE) {
						dto = (VirAccountDto) ((AppCommonResultDto) rto).getData();
					}
					if (dto != null && dto.getIsLogin() != null && 2 == dto.getIsLogin() && StringUtils.isNotEmpty(dto.getFoodCardNo()) && StringUtils.isNotEmpty(dto.getFoodCardH5())) {
						log.info("企业饭卡跳转地址：" + redirectUrl_);
						redirectUrl_ = "redirect:" + dto.getFoodCardH5() + "?spid=" + dto.getFoodCardNo() + "&out_account_id=" + openId + "&name=" + dto.getUserName() + "&mobile=" + dto.getMobile();
						log.info("企业饭卡跳转地址end：" + redirectUrl_);
					} else {
						if (redirectUrl.indexOf("&attach") > 0) {
							String url  = redirectUrl.substring(0, redirectUrl.indexOf("&attach") + 8);
							String url1 = URLEncoder.encode(redirectUrl.substring(redirectUrl.indexOf("&attach") + 8), "utf-8");
							redirectUrl = url + url1;
						}
						redirectUrl_ = "redirect:" + redirectUrl;
					}
					log.info("===end=跳转redirectUrl：" + redirectUrl_);
					return new ModelAndView(redirectUrl_, null);
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
			}

			TbOrganization organization = organizationManager.getOrganizationById(wxUser.getOrganizationId());
			//维修服务接口跳转
			if (redirectUrl.contains("?")) {
				// 如果跳转链接中包含"?",即携带参数,例如:http://npxwx.pai-xiu.com/wx/outlink?openid=123456;则只需拼接参数,&a=xxx&b=1111...
				int i = redirectUrl.indexOf("?");
				redirectUrl = redirectUrl.substring(0, i);
			}

			String params = "?openid=" + openId + "&developid=" + developId + "&projectno=" + organization.getHdProjectId();

			//首先根据用户openid与公众号developId查询用户
			AppUser         user            = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
			ServiceTypeInfo serviceTypeInfo = serviceTypeInfoManager.getServiceTypeInfoByServiceCode(serviceNumber);
			String          roleType        = "1";
			if (serviceTypeInfo != null) {
				ServiceProjectAllocation localtion = serviceProjectAllocationManager.getServiceProjectAllocation(serviceTypeInfo.getId(), orgId);
				if (localtion.getRoleGroup().equals("2")) {
					roleType = "2";
				}
			}
			//该用户已经注册过并且已经是登录状态,则直接跳转,否则去登录页面
			if (user != null && user.getIsLogin() == 1) {
				if (roleType.equals("2") && !user.getUserType().equals("0")) {
					redirectUrl_ = "/wechat/changeAccountLogin";
				}
				if (roleType.equals("1") || (roleType.equals("2") && user.getUserType().equals("0"))) {

					// 模块日用户量统计
					moduleUserCountService.saveModuleUserToRedis(serviceCode, user.getId(), user.getOrganizationId());

					if (StringUtils.isBlank(user.getUserCode()) || "2000".equalsIgnoreCase(user.getUserCode())) {
						try {
							Map<String, Object> map = appUserManager.hdRegister(user.getUserMobile(), openId);
							if (map != null && (Boolean) map.get("success")) {
								Map<String, Object> data = (Map<String, Object>) map.get("data");
								user.setUserCode((String) data.get("userCode"));
							}
							appUserManager.updateModel(user);
						} catch (Exception e) {
							log.error("WechatRepairUserController checkRegister 航电用户注册异常=====>:" + e.getMessage());
						}
					}
					if (redirectUrl.contains("customervoice")) {//投诉与表扬接入
						params = "?openId=" + openId + "&developid=" + developId + "&projectId=" + organization.getHdVoiceProjectId();
						params += "&userId=" + user.getUserCode();
					}
					if (redirectUrl.contains("weChatOath/redirectHdReportRepair")) {//报事报修接入
						params = "?openId=" + openId + "&developid=" + developId + "&projectId="
								+ organization.getHdVoiceProjectId() + "&sendType=" + "01";
						params += "&userCode=" + user.getUserCode();
					}
					//已注册跳转路径
					redirectUrl_ = "redirect:" + redirectUrl + params;
				}
			}
		}

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

	}
}
