package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.ReturnObject;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.CommonDto;
import com.palmnest.model.ContractIinformation;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.UserImageInfo;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.impl.WeChatAccessManagerImpl;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.json.JSONException;
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.ui.ModelMap;
import org.springframework.util.CollectionUtils;
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 javax.servlet.http.HttpSession;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 会员用户信息管理前端控制器
 *
 * @author yubing
 * @since 2017-1-14
 */
@Slf4j
@Controller
@RequestMapping(value = "/wechat/appUser*")
public class AppUserController {

	@Autowired
	private AppUserManager                   appUserManager;
	@Autowired
	private PublicNoManager                  publicNoManager;
	@Autowired
	private PropertyManager                  propertyManager;
	@Autowired
	private VisitorInFoManager               visitorInFoManager;
	@Autowired
	private ScWxuserManager                  scWxuserManager;
	@Autowired
	private VirtUserManager                  virtUserManager;
	@Autowired
	private EmigrationManager                emigrationManager;
	@Autowired
	private VirtualArchManager               virtualArchManager;
	@Autowired
	private ContractIinformationOrderManager contractIinformationOrderManager;
	@Autowired
	private BaseRedisService baseRedisService;

	public void init(Model model, String url, String developId) {
		String noncestr  = StringUtil.create_nonce_str();
		String timestamp = StringUtil.create_timestamp();
//		String signature = StringUtil.wxSignature_JS(developId, noncestr, timestamp, url);
		String jsapi_ticket =baseRedisService.get(Constants.JSAPI+developId);
		if (StringUtils.isBlank(jsapi_ticket)) {
			jsapi_ticket = new WeChatAccessManagerImpl().getJsApiTicket(developId);
		}
		Map<String, String> ret = StringUtil.sign(jsapi_ticket, url, noncestr, timestamp);
		String signature= ret.get("signature");

		WxPublicno publicno = publicNoManager.getByDevelopId(developId);
		model.addAttribute("appId", publicno.getAppId());
		model.addAttribute("noncestr", noncestr);
		model.addAttribute("timestamp", timestamp);
		model.addAttribute("signature", signature);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
	}

	/**
	 * 进行网页授权获取用户信息
	 */
	@RequestMapping(value = "/execWechatAuth")
	public ModelAndView authReBindPhone(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model     = new ExtendedModelMap();
		String developId = request.getParameter("developId");
		String pageType  = request.getParameter("pageType");
		log.info("----execWechatAuth----");
		log.info("developId:" + developId);
		log.info("pageType:" + pageType);
		if (StringUtils.isNotBlank(developId)) {
			String pageAccessUrl = PropertiesKit.readPropertiesValue(pageType, "wechat.properties");
			log.info("pageAccessUrl:" + pageAccessUrl);
			//拼装参数
			Enumeration reqNames = request.getParameterNames();
			for (Enumeration e = reqNames; e.hasMoreElements(); ) {
				String reqName = e.nextElement().toString();
				if ("pageType".equals(reqName) || "developId".equals(reqName)) {
					continue;
				} else {
					String reqValue = request.getParameter(reqName);
					pageAccessUrl += "&" + reqName + "=" + reqValue;
				}
			}
			log.info("pageAccessUrlNew:" + pageAccessUrl);
			//URLEncoder encode
			WxPublicno wxPublicno   = publicNoManager.getByDevelopId(developId);
			String     redirect_uri = URLEncoder.encode(pageAccessUrl, "utf-8");
			//拼装微信授权的URL
			StringBuffer redirectFullUrl = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?");
			redirectFullUrl.append("appid=" + wxPublicno.getAppId());
			redirectFullUrl.append("&redirect_uri=" + redirect_uri);
			redirectFullUrl.append("&response_type=code&scope=snsapi_base");
			redirectFullUrl.append("&state=" + wxPublicno.getId());
			redirectFullUrl.append("#wechat_redirect");
			log.info("redirectFullUrl:" + redirectFullUrl);
			model.addAttribute("redirectFullUrl", redirectFullUrl.toString());
			return new ModelAndView("wechat/toWechatAuth", model.asMap());
		} else {
			log.info("AppUserController authReBindPhone ========> 微信用户developId为空");
			return new ModelAndView("wechat/noPage", model.asMap());
		}
	}

	/**
	 * 绑定手机号码
	 * 注册or登录页面
	 */
	@RequestMapping(value = "/bindphone")
	public ModelAndView bindphone(HttpServletRequest request, HttpServletResponse response) throws Exception {


		log.info("AppUserController bindphone 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("AppUserController bindphone " + reqName + "===:" + reqValue + "===");
		}


		Model  model       = new ExtendedModelMap();
		String openId      = request.getParameter("openId");
		String developId   = request.getParameter("developId");
		String redirectUrl = request.getParameter("redirectUrl");
		String urlKey      = request.getParameter("urlKey");
		String mECode      = request.getParameter("mECode");//商城的项目id
		String st          = request.getParameter("st");//商城返回的用户状态
		String refererId   = request.getParameter("refererId");//商城返回的链接
		String serviceCode = request.getParameter("serviceCode");
		String fromType    = request.getParameter("fromType");
		String login       = request.getParameter("login");

		log.info("----AppUserController bindphone redirectUrl----" + redirectUrl);


		if (StringUtils.isNotEmpty(redirectUrl)) {
			redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
		}

		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("redirectUrl", redirectUrl);
		model.addAttribute("fromType", fromType);
		model.addAttribute("serviceCode", serviceCode);
		model.addAttribute("urlKey", urlKey);
		model.addAttribute("mECode", mECode);
		model.addAttribute("st", st);
		model.addAttribute("refererId", refererId);
		model.addAttribute("login", login);
		return new ModelAndView("wechat/ubindphone", model.asMap());
	}

	/**
	 * 绑定电话号码
	 * 号码内容提交
	 */
	@RequestMapping(value = "/submitphone", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String submitphone(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		ReturnObject rt;
		try {
			String openId     = request.getParameter("openId");
			String developId  = request.getParameter("developId");
			String authCode   = request.getParameter("authCode");
			String userMobile = request.getParameter("userMobile");
			String st         = request.getParameter("st");
			String fromType   = request.getParameter("fromType");
			String codes      = request.getParameter("codes");
			String superId    = request.getParameter("super");
			if (StringUtils.isEmpty(codes)) {
				rt = new ReturnObject(Constants.RESULT_SUCC, Constants.RESULTCODE_EXCEPTION, "图片验证码错误或已过期");
				String str = JSONObject.fromObject(rt).toString();
				return str;
			}
			if (!codes.equalsIgnoreCase((String) session.getAttribute(superId + "_checkCode"))) {
				rt = new ReturnObject(Constants.RESULT_SUCC, Constants.RESULTCODE_EXCEPTION, "图片验证码错误或已过期");
				String str = JSONObject.fromObject(rt).toString();
				return str;
			}
			Map<String, Object> resultMap = appUserManager.assignBindPhone(openId, developId, userMobile, authCode);
			String              flag      = (String) resultMap.get("flag");
			if ("success".equals(flag)) {
				AppUser appUser = (AppUser) resultMap.get("appUser");
				int     userId  = appUser.getId();
				String  status  = appUser.getStatus();
				rt = new ReturnObject();
				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
				rt.setResultDesc("success");
				Map<String, String> rsMap = new HashMap<String, String>();
				rsMap.put("userId", userId + "");
				rsMap.put("status", status);
				rsMap.put("shopUrlKey", "Cterminal");//个人商城
				rsMap.put("st", st);
				rsMap.put("fromType", fromType);
				rt.setReturnDTO(rsMap);
			} else if ("codeError".equals(flag)) {
				rt = new ReturnObject(Constants.RESULT_SUCC, Constants.RESULTCODE_EXCEPTION, "短信验证码错误或失效");
			} else if ("error".equals(flag)) {
				rt = new ReturnObject(Constants.RESULT_SUCC, Constants.RESULTCODE_EXCEPTION, "注册失败，请检查网络或稍后再试.");
			} else {
				rt = new ReturnObject(Constants.RESULT_SUCC, Constants.RESULTCODE_EXCEPTION, "此电话号码已绑定");
			}
		} catch (Exception e) {
			rt = new ReturnObject(Constants.RESULT_FIAL, Constants.RESULTCODE_EXCEPTION, "未知异常");
		}
		String str = JSONObject.fromObject(rt).toString();
		if (StringUtils.isNotEmpty(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}
		return str;
	}

	/**
	 * 项目地址选择
	 */
	@RequestMapping(value = "/choiceOrgAddress")
	public ModelAndView choiceOrgAddress(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model       = new ExtendedModelMap();
		String userId      = request.getParameter("userId");
		String openId      = request.getParameter("openId");
		String developId   = request.getParameter("developId");
		String actType     = request.getParameter("actType");
		String redirectUrl = "wechat/choiceOrgAddress";

		//来自注册完成之后
		if (StringUtils.isEmpty(actType)) {
			AppUser appUser = appUserManager.get(Integer.parseInt(userId));
			if (appUser.getOrganizationId() != null) {
				model.addAttribute("appUser", appUser);
				model.addAttribute("organization", propertyManager.getTbOrganizationById(appUser.getOrganizationId()));
				redirectUrl = "wechat/uInfo";
			} else {
				//根据developId判断是否关联多个项目
				List<Map<String, Object>> relationOrgs = publicNoManager.getWxPublicnoOrgRelations(developId);
				if (!CollectionUtils.isEmpty(relationOrgs)) {
					if (relationOrgs.size() > 1) {
						Map<String, List<Map<String, Object>>> resultMap = publicNoManager.getWxPublicnoOrgRelationsGroupByCity(relationOrgs);
						model.addAttribute("userId", userId);
						model.addAttribute("resultMap", resultMap);
						//距离最近的项目
						model.addAttribute("organization", propertyManager.getTbOrganizationById((Integer) relationOrgs.get(0).get("id")));
					} else {
						model.addAttribute("appUser", appUser);
						model.addAttribute("organization", propertyManager.getTbOrganizationById((Integer) relationOrgs.get(0).get("id")));
						redirectUrl = "wechat/uInfo";
					}
				}
			}
		}
		//来自个人信息也切换地址
		else {
			//根据developId判断是否关联多个项目
			List<Map<String, Object>> relationOrgs = publicNoManager.getWxPublicnoOrgRelations(developId);
			if (!CollectionUtils.isEmpty(relationOrgs)) {
				Map<String, List<Map<String, Object>>> resultMap = publicNoManager.getWxPublicnoOrgRelationsGroupByCity(relationOrgs);
				model.addAttribute("userId", userId);
				model.addAttribute("resultMap", resultMap);
				//距离最近的项目
				model.addAttribute("organization", propertyManager.getTbOrganizationById((Integer) relationOrgs.get(0).get("id")));
			}
		}
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		return new ModelAndView(redirectUrl, model.asMap());
	}

	/**
	 * 用户信息界面
	 */
	@RequestMapping(value = "/userInfo")
	public ModelAndView userInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String userId         = request.getParameter("userId");
			String openId         = request.getParameter("openId");
			String developId      = request.getParameter("developId");
			String organizationId = request.getParameter("organizationId");

			AppUser appUser = appUserManager.get(Integer.parseInt(userId));
			if (StringUtils.isEmpty(organizationId)) {
				if (appUser.getOrganizationId() != null) {
					organizationId = appUser.getOrganizationId() + "";
				}
			} else {
				//更新选择的项目
				appUser.setOrganizationId(Integer.parseInt(organizationId));
				appUserManager.updateModel(appUser);
				appUserManager.assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);
			}
			if ("1".equals(appUser.getRoleType()) && "1".equals(appUser.getStatus())) {
				model.addAttribute("noCheckCount", appUserManager.getAppUserNonCheckedCount(appUser.getVirtualArchId() + "", "0"));
				model.addAttribute("count", appUserManager.getAppUserNonCheckedCount(appUser.getVirtualArchId() + "", "1"));
			}

			if (StringUtils.isNotBlank(organizationId)) {
				TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(organizationId));
				model.addAttribute("organization", organization);
			}

			List<UserImageInfo> list = visitorInFoManager.getUserImageInfo(Integer.parseInt(userId), "1");
			if (list != null && list.size() > 0) {
				model.addAttribute("userImageInfo", list.get(0));
			} else {
				model.addAttribute("userImageInfo", null);
			}
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			model.addAttribute("appUser", appUser);
			model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
//			if(appUser.getVirtualArchId()!=null){
//				model.addAttribute("virtualArchitecture", propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId()));
//			}
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				List<CommonDto> listDto = emigrationManager.getVirListByReman(wxUser.getUserId());
				if (listDto != null && listDto.size() > 0) {
					model.addAttribute("virList", listDto);
				} else {
					List<CommonDto> dtoList = new ArrayList<CommonDto>();
					if (appUserManager.exists(wxUser.getUserId())) {
						AppUser   appUserInfo = appUserManager.get(wxUser.getUserId());
						CommonDto dto         = new CommonDto();
						dto.setId(Long.parseLong(String.valueOf(appUserInfo.getVirtualArchId())));
						VirtualArchitecture virInfo = virtualArchManager.get(appUserInfo.getVirtualArchId());
						dto.setName(virInfo.getName());
						dtoList.add(dto);
						model.addAttribute("virList", dtoList);
					}
				}
			}
		} catch (Exception e) {
			log.error("redirect userInfo occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return new ModelAndView("wechat/uInfo", model.asMap());
	}

	/**
	 * 更新用户资料界面
	 */
	@RequestMapping(value = "/toModifyUser")
	public ModelAndView toModifyUserName(HttpServletRequest request, HttpServletResponse response) {
		Model  model     = new ExtendedModelMap();
		String actType   = request.getParameter("actType");
		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");
		String userId    = request.getParameter("userId");

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		model.addAttribute("appUser", appUser);
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("organizationId", request.getParameter("organizationId"));
		appUserManager.updateModel(appUser);

		String redirectUrl = "";
		if ("1".equals(actType)) {
			redirectUrl = "wechat/umodifyname";
		} else if ("2".equals(actType)) {
			redirectUrl = "wechat/umodifytel";
		} else {
			redirectUrl = "wechat/umodifytel";
		}
		return new ModelAndView(redirectUrl, model.asMap());
	}

	/**
	 * 更新用户资料信息--用户姓名
	 */
	@RequestMapping(value = "/modifyUserName")
	public ModelAndView modifyUserInfo(HttpServletRequest request, HttpServletResponse response) {
		Model  model          = new ExtendedModelMap();
		String userId         = request.getParameter("userId");
		String userName       = request.getParameter("userName");
		String openId         = request.getParameter("openId");
		String developId      = request.getParameter("developId");
		String organizationId = request.getParameter("organizationId");

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		appUser.setUserName(userName);
		appUserManager.updateModel(appUser);

		appUserManager.assignSyncUser(appUser, ElementConstant.OPRATETYPE_UPD);

		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("organizationId", organizationId);
		model.addAttribute("userId", appUser.getId());
		return new ModelAndView("redirect:/wechat/appUser/userInfo", model.asMap());
	}

	/**
	 * 更新用户资料信息--修改手机
	 */
	@RequestMapping(value = "/modifyUserMobile", method = RequestMethod.POST)
	public @ResponseBody
	AppResultDto modifyUserMobile(HttpServletRequest request, HttpServletResponse response) {
		String userId     = request.getParameter("userId");
		String userMobile = request.getParameter("userMobile");
		String authCode   = request.getParameter("authCode");

		String result = appUserManager.updateAppUserMobile(Integer.parseInt(userId), userMobile, authCode);
		return AppResultUtil.createSuccesDto(result);
	}

	/**
	 * 公司认证
	 */
	@RequestMapping(value = "/uauthentication")
	public ModelAndView uauthentication(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model          = new ExtendedModelMap();
		String openId         = request.getParameter("openId");
		String developId      = request.getParameter("developId");
		String userId         = request.getParameter("userId");
		String organizationId = request.getParameter("organizationId");
		String redirectUrl    = "wechat/uauthentication";

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		model.addAttribute("appUser", appUser);
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		List<UserImageInfo> list = visitorInFoManager.getUserImageInfo(Integer.parseInt(userId), "1");
		model.addAttribute("list", list);

		if (appUser.getOrganizationId() != null) {
			organizationId = appUser.getOrganizationId().toString();
			model.addAttribute("organization", propertyManager.getTbOrganizationById(appUser.getOrganizationId()));
		}
		if (appUser.getVirtualArchId() != null) {
			model.addAttribute("virtualArch", propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId()));
		}
		model.addAttribute("organizationId", organizationId);
		return new ModelAndView(redirectUrl, model.asMap());
	}

	/**
	 * 验证头像是否规范
	 *
	 * @param response
	 * @return error
	 * 文件上传的相对路径
	 */
	@RequestMapping(value = "/validateHeadStandard", method = RequestMethod.POST)
	public @ResponseBody
	String validateHeadStandard(HttpServletRequest request, HttpServletResponse response) {
		String faceImage     = request.getParameter("faceImage");
		String virtualArchId = request.getParameter("virtualArchId");
		return appUserManager.validateHeadStandard(faceImage, virtualArchId);
	}

	/**
	 * 公司认证
	 * 提交完善的信息
	 */
	@RequestMapping(value = "/submitUserInfo", method = RequestMethod.POST)
	public String submitUserInfo(HttpServletRequest request,
								 HttpServletResponse response, ModelMap modelMap) throws Exception {
		com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();

		String openId          = request.getParameter("openId");
		String developId       = request.getParameter("developId");
		String userId          = request.getParameter("userId");
		String organizationId  = request.getParameter("organizationId");
		String virtualArchId   = request.getParameter("virtualArchId");
		String zhengjianImage  = request.getParameter("zhengjianImage");
		String headRelativeUrl = request.getParameter("headRelativeUrl");
		String userName        = request.getParameter("userName");
		String dataUrl         = request.getParameter("dataUrl");
		String remark          = request.getParameter("remark");

		log.info("-----submitUserInfo");
		log.info("openId:" + openId);
		log.info("developId:" + developId);
		log.info("userId:" + userId);
		log.info("organizationId:" + organizationId);
		log.info("virtualArchId:" + virtualArchId);
		log.info("headRelativeUrl:" + headRelativeUrl);
		log.info("userName:" + userName);

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		appUser.setOrganizationId(Integer.parseInt(organizationId));
		appUser.setVirtualArchId(Integer.parseInt(virtualArchId));
		appUser.setUserName(userName);
		appUser.setStatus("0");            //待审核
		appUser.setRoleType("2");        //普通员工
		appUser.setRemark(remark);
		json.put("organizationId", organizationId);
		json.put("userMobile", appUser.getUserMobile());
		String retCode = appUserManager.updateAppUser(appUser, zhengjianImage, headRelativeUrl, developId, dataUrl);
		json.put("retCode", retCode);
		log.info("=======retCode===========:" + retCode);
		log.info("=======json===========:" + json);
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 查询虚拟组织架构
	 *
	 * @param request  organizationId 项目ID
	 *                 type 类型 1-企业  2-企业部门
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getVirtualArchitectureList", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<VirtualArchitecture> getVirtualArchitectureList(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		String                    type           = request.getParameter("type");
		List<VirtualArchitecture> list           = propertyManager.getVirtualArchitectureList(Integer.parseInt(organizationId));
		List<VirtualArchitecture> result         = new ArrayList<VirtualArchitecture>();
		for (VirtualArchitecture virtualArchitecture : list) {
			if (type.equals(virtualArchitecture.getType())) {
				result.add(virtualArchitecture);
			}
		}
		return result;
	}

	/**
	 * 解除公司认证绑定
	 */
	@RequestMapping(value = "/removeBinding", method = RequestMethod.POST)
	public @ResponseBody
	String removeBinding(HttpServletRequest request, HttpServletResponse response) {
		String userId = request.getParameter("userId");
		return appUserManager.updateAppUser(Integer.parseInt(userId), "0", "", "", "2");
	}


	@RequestMapping(value = "/redirectSingleServerKey")
	public ModelAndView redirectSingleServerKey(HttpServletRequest request, HttpServletResponse response) {
		String  userId    = request.getParameter("userId");
		String  openId    = request.getParameter("openId");
		String  developId = request.getParameter("developId");
		String  url       = "";
		AppUser appUser   = appUserManager.get(Integer.parseInt(userId));
		if (appUser.getOrganizationId() != null) {
			String serviceCode          = request.getParameter("serviceCode");
			String ContractStatus       = "0";
			String authenticationStatus = appUser.getStatus();//认证状态
			if (!"1".equals(authenticationStatus)) {
				authenticationStatus = "0";
			} else {
				authenticationStatus = "1";
				if (appUser.getVirtualArchId() != null) {
					ContractIinformation contractIinformation = contractIinformationOrderManager.getContractIinformationByVirtualId(appUser.getVirtualArchId());
					if (contractIinformation != null) {
						ContractStatus = "1";
					}
				}
			}
			String userMobile = appUser.getUserMobile();
			url = "redirect:" + Constants.SERVER_SINGLE_URL + "/wechat/server/singleServerKey?authenticationStatus=" + authenticationStatus + "&userMobile="
					+ "" + userMobile + "&ContractStatus=" + ContractStatus + "&serviceCode=" + serviceCode;
			return new ModelAndView(url);
		} else {
			Model model = new ExtendedModelMap();
			model.addAttribute("userId", userId);
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			return new ModelAndView("redirect:/wechat/appUser/choiceOrgAddress", model.asMap());
		}
	}

	@RequestMapping(value = "/getVirtualArchitectureListByName", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<Map<String, Object>> getVirtualArchitectureListByName(HttpServletRequest request, HttpServletResponse response) {
		String                    organizationId = request.getParameter("organizationId");
		String                    type           = request.getParameter("type");
		String                    params         = request.getParameter("params");
		List<Map<String, Object>> list           = propertyManager.getVirtualarchitectureList(organizationId, type, params);
		return list;
	}

	@RequestMapping(value = "/uploadImage", method = {RequestMethod.GET, RequestMethod.POST})
	public @ResponseBody
	String uploadImage(HttpServletRequest request) throws IOException, ParseException, JSONException {
		String imageUrl     = request.getParameter("imageUrl");
		String relativePath = "";
		try {
			// Base64解码
//			imageUrl=imageUrl.replace("data:image/png;base64,", "");
			imageUrl = imageUrl.split("base64,")[1];
			relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
			return relativePath;
		} catch (Exception e) {
			FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
			log.error("检测图片接口错误:" + e.getMessage());
		}
		return "";
	}

	@RequestMapping(value = "/getProvincecityByCityList", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<Map<String, Object>> getProvincecityByCityList(HttpServletRequest request, HttpServletResponse response) {
		String                    params    = request.getParameter("params");
		String                    developId = request.getParameter("developId");
		List<Map<String, Object>> orgIdList = publicNoManager.getWxPublicnoOrgRelations(developId);
		String                    id        = "";
		for (int i = 0; i < orgIdList.size(); i++) {
			id += orgIdList.get(i).get("id") + ",";
		}
		id = id.substring(0, id.length() - 1);
		List<Map<String, Object>> list = propertyManager.getProvincecityByCityList(params, id);
		return list;
	}

	@RequestMapping(value = "/getOrganizationListByName", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<Map<String, Object>> getOrganizationListByName(HttpServletRequest request, HttpServletResponse response) {
		String                    cityCode  = request.getParameter("cityCode");
		String                    params    = request.getParameter("params");
		String                    developId = request.getParameter("developId");
		List<Map<String, Object>> orgIdList = publicNoManager.getWxPublicnoOrgRelations(developId);
		String                    id        = "";
		for (int i = 0; i < orgIdList.size(); i++) {
			id += orgIdList.get(i).get("id") + ",";
		}
		id = id.substring(0, id.length() - 1);
		List<Map<String, Object>> list = propertyManager.getOrganizationListByName(params, cityCode, id);
		return list;
	}

	/**
	 * 获取微信登录用户的信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getWechatUserInfo", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	AppResultDto getWechatUserInfo(HttpServletRequest request, HttpServletResponse response) {
		String              openId = request.getParameter("openId");
		AppResultDto        dto    = AppResultUtil.createErrorDto("100", "传输参数异常");
		Map<String, Object> map    = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(openId)) {
			WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			if (wxUser != null) {
				int    userId     = 0;
				String userMobile = "";
				String userName   = "";
				if (wxUser.getUserId() != 0) {
					userId = wxUser.getUserId();
					AppUser user = appUserManager.get(userId);
					if (user != null) {
						userMobile = user.getUserMobile();
						userName = user.getUserName();
					}
				}
				map.put("userMobile", userMobile);
				map.put("userName", userName);
				map.put("nickName", wxUser.getNickName());
				map.put("headImgUrl", wxUser.getHeadimgUrl());
				dto = AppResultUtil.createSuccesDto(map);
			}
		}
		return dto;
	}

	@RequestMapping(value = "/updateTelByHisTel", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	AppResultDto updateTelByHisTel(HttpServletRequest request, HttpServletResponse response) {
		String       openId    = request.getParameter("openId");
		String       developId = request.getParameter("developId");
		String       newTel    = request.getParameter("mobile");
		String       code      = request.getParameter("authCode");
		AppResultDto dto       = AppResultUtil.createErrorDto("100", "传输参数异常");
		dto = appUserManager.updateTelByHisTel(newTel, code, developId, openId);
		return dto;
	}

	@RequestMapping(value = "/getUserIdByOpenId", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	AppResultDto getUserIdByOpenId(HttpServletRequest request, HttpServletResponse response) {
		String       openId    = request.getParameter("openId");
		String       developId = request.getParameter("developId");
		AppResultDto dto       = AppResultUtil.createSuccesDto();
		AppUser      appUser   = appUserManager.getAppUserByOpenId(developId, openId);
		if (appUser != null) {
			String userId = "";
			if (appUser.getId() != null) {
				userId = appUser.getId().toString();
			}
			dto = AppResultUtil.createSuccesDto(userId);
		}
		return dto;
	}

	/**
	 * 修改用户信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateUserState")
	@ResponseBody
	public AppResultDto updateUserState(HttpServletRequest request, HttpServletResponse response) {

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

		return null;
	}
}
