package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.UserInfo;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.model.Element;
import com.palmnest.model.InPuchaseUser;
import com.palmnest.model.ScopeEntity;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.TbOrganizationConfig;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.org.OrganizationService;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.virtProject.manager.UserAccountManager;
import com.palmnest.service.virtProject.manager.VirtualAccountManager;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.service.wechat.WeChatIndexManager;
import com.palmnest.webapp.controller.BaseFormController;
import com.palmnest.webapp.filter.JwtUtil;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 主页控制层
 *
 * @author 金牙
 */
@Slf4j
@Controller
@RequestMapping("/wechat/index/*")
public class WeChatIndexController extends BaseFormController {


	@Autowired
	private ScWxuserManager                 scWxuserManager;
	@Autowired
	private AppUserManager                  appUserManager;
	@Autowired
	private PublicNoManager                 publicNoManager;
	@Autowired
	private PropertyManager                 propertyManager;
	@Autowired
	private WeChatApiManager                weChatApiManager;
	@Autowired
	private WeChatIndexManager              weChatIndexManager;
	@Autowired
	private OrganizationService             organizationService;
	@Autowired
	private OrganizationManager             organizationManager;
	@Autowired
	private SmsAuthCodeManager              smsAuthCodeManager;
	@Autowired
	private VirtualArchManager              virtualArchManager;
	@Autowired
	private VirtualAccountManager           virtualAccountManager;
	@Autowired
	private UserAccountManager              userAccountManager;
	@Autowired
	private BaseRedisService                baseRedisService;
	@Autowired
	private NeigouManager                   neigouManager;
	@Autowired
	private EnterprisePermissionManager     enterprisePermissionManager;
	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private ServiceTypeInfoManager          serviceTypeInfoManager;
	@Autowired
	private AppUserService                  appUserService;

	private static String hdUrl = PropertiesKit.readPropertiesValue("hdUrl", "wechat.properties");

	public void init(Model model) {
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
	}

	/**
	 * 跳转首页
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/homePageView")
	@ResponseBody
	public ModelAndView homePageView(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			init(model);

			String openId         = request.getParameter("openId");//用户当前公众号唯一标识
			String developId      = request.getParameter("developId");//公众号开发者id
			String organizationId = request.getParameter("organizationId");//项目id

			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
//			model.addAttribute("organizationId", organizationId);

			log.info("-------- homePageView --------");
			log.info("openId:" + openId);
			log.info("developId:" + developId);
			log.info("organizationId:" + organizationId);

			if (StringUtils.isNotEmpty(openId)) {
				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
				if (wxUser == null) {
					wxUser = saveWxUser(developId, openId, organizationId);
				} else if (wxUser != null && StringUtils.isNotBlank(organizationId)) {
					wxUser.setOrganizationId(Integer.parseInt(organizationId));
					propertyManager.updateModel(wxUser);
				}
				TbOrganization tbOrganization = propertyManager.getTbOrganizationById(wxUser.getOrganizationId());//获取用户所属项目

				model.addAttribute("organization", tbOrganization);
				//已经绑定已经登录，展示真实名称
				AppUser user = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
				if (user != null && user.getIsLogin() == 1) {
					if (user.getIsBinding() == 1 && StringUtils.isNotBlank(user.getUserName())) {
						wxUser.setNickName(user.getUserName());
					}
					model.addAttribute("user", user);
					model.addAttribute("userId", user.getId());
				}
				WxPublicno wxPublicno = publicNoManager.getByDevelopId(developId);
				if (null != wxPublicno) {
					model.addAttribute("publicId", wxPublicno.getId());
				}
				model.addAttribute("wxUser", wxUser);
				return new ModelAndView("wechat/servicehome_two", model.asMap());//2017.11.3更新
			} else {
				log.info("WeChatIndexController homePageView ========> 微信用户openId为空");
				return new ModelAndView("wechat/noPage", model.asMap());//2018.12.3更新
			}
		} catch (Exception e) {
			log.error("controller find homePageView error{}", LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 获取用户服务列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/serviceList")
	@ResponseBody
	public AppResultDto serviceList(HttpServletRequest request) {
		try {
			String  openId    = request.getParameter("openId");
			String  developId = request.getParameter("developId");
			WxUser  wxUser    = scWxuserManager.getScWxuserByOpenId(openId);
			Integer orgId     = wxUser.getOrganizationId();
			//服务项放入缓存
			String serviceJson = baseRedisService.get(CodeConstants.ORG_SERVICE_LIST_KEY + orgId);
			if (StringUtils.isNotEmpty(serviceJson)) {
				Map<String, Object> serviceList = JSONObject.parseObject(serviceJson);
				if (serviceList != null) {
					return AppResultUtil.createSuccesDto(serviceList);
				}
			}
			Map<String, Object> serviceListAll = weChatIndexManager.getServiceListAll(openId, developId, wxUser.getOrganizationId() + "");
			baseRedisService.set(CodeConstants.ORG_SERVICE_LIST_KEY + orgId, JSONObject.toJSONString(serviceListAll));
			return AppResultUtil.createSuccesDto(serviceListAll);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询service列表失败");
		}
	}

	/**
	 * 获取用户服务列表带分类
	 *
	 * @return
	 */
	@RequestMapping(value = "/serviceListCategory")
	@ResponseBody
	public AppResultDto serviceListCategory(HttpServletRequest request) {
		try {
			String  openId    = request.getParameter("openId");
			String  developId = request.getParameter("developId");
			WxUser  wxUser    = scWxuserManager.getScWxuserByOpenId(openId);
			Integer orgId     = wxUser.getOrganizationId();
			//服务项放入缓存
			String serviceJson = baseRedisService.get(CodeConstants.ORG_SERVICE_CATEGORY_KEY + orgId);
			if (StringUtils.isNotEmpty(serviceJson)) {
				List<Map> list2 = JSONObject.parseArray(serviceJson, Map.class);
				if (!CollectionUtils.isEmpty(list2)) {
					return AppResultUtil.createSuccesDto(list2);
				}
			}
			List<Map<String, Object>> serviceListCategory = weChatIndexManager.getServiceListCategory(openId, developId, wxUser.getOrganizationId() + "");
			baseRedisService.set(CodeConstants.ORG_SERVICE_CATEGORY_KEY + orgId, JSONObject.toJSONString(serviceListCategory));
			return AppResultUtil.createSuccesDto(serviceListCategory);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询service列表失败");
		}
	}

	/**
	 * 获取该项目商圈发现
	 *
	 * @return
	 */
	@RequestMapping(value = "/discoverCategory")
	@ResponseBody
	public AppResultDto discoverCategory(HttpServletRequest request) {
		try {
			Map<String, Object>  map    = new HashMap<String, Object>();
			String               orgId  = request.getParameter("orgId");//项目id
			TbOrganizationConfig config = organizationService.getDiscoverConfigByOrgId(orgId);

			boolean isEnabled = false;
			if (null != config && "1".equals(config.getDiscoverIsEnabled())) {//商圈发现开启
				isEnabled = true;
				Element element = this.getElementGroupManager().getByItemCode("discoverCategory", config.getDiscoverCategory());
				if (element != null) {
					map.put("name", element.getItemname());
				}
			}

			map.put("isEnabled", isEnabled);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询失败");
		}
	}

	@RequestMapping(value = "/neigouChoiceAddress")
	public ModelAndView neigouChoiceAddress(HttpServletRequest request) throws Exception {
		Model  model       = new ExtendedModelMap();
		String developId   = request.getParameter("developId");
		String openId      = request.getParameter("openId");
		String userId      = request.getParameter("userId");
		String redirectUrl = request.getParameter("redirectUrl");
		model.addAttribute("developId", developId);
		model.addAttribute("openId", openId);
		model.addAttribute("userId", userId);
		model.addAttribute("redirectUrl", redirectUrl);
		try {
			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("resultMap", resultMap);
					//距离最近的项目
					model.addAttribute("organization", propertyManager.getTbOrganizationById((Integer) relationOrgs.get(0).get("id")));
				}
			}
			return new ModelAndView("wechat/neigouChoiceAddress", model.asMap());
		} catch (Exception e) {
			log.error("controller get choiceOrgAddressIndex error{}", e);
		}
		return null;
	}

	/**
	 * 判断是否关注
	 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffe70d6b42696497&redirect_uri=http%3A%2F%2Fwx.palmnest.com%2Fsuper_reception%2Fwechat%2Findex%2FjudgeIsSubscribe&response_type=code&scope=snsapi_base&state=1#wechat_redirect
	 */
	@RequestMapping(value = "/judgeIsSubscribe")
	public ModelAndView judgeIsSubscribe(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Model model = new ExtendedModelMap();
		return new ModelAndView("wechat/noSubscribe", model.asMap());

	}


	@RequestMapping(value = "/choiceOrgAddressIndex")
	public ModelAndView choiceOrgAddressIndex(HttpServletRequest request) throws Exception {
		Model  model     = new ExtendedModelMap();
		String developId = request.getParameter("developId");
		String openId    = request.getParameter("openId");
		String userId    = request.getParameter("userId");
		model.addAttribute("developId", developId);
		model.addAttribute("openId", openId);
		model.addAttribute("userId", userId);
		try {
			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("resultMap", resultMap);
					//距离最近的项目
					model.addAttribute("organization", propertyManager.getTbOrganizationById((Integer) relationOrgs.get(0).get("id")));
				}
			}
			return new ModelAndView("wechat/choiceOrgAddressIndex", model.asMap());
		} catch (Exception e) {
			log.error("controller get choiceOrgAddressIndex error{}", e);
		}
		return null;
	}

	/**
	 * 根据用户经纬度获取最近项目
	 * 附近5000米范围内的所有项目
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/initOrgSelect")
	@ResponseBody
	public AppResultDto initOrgSelect(double latitude,
									  double longitude,
									  String developId,
									  HttpServletRequest request) {

//		String latitude=request.getParameter("latitude");//维度
//		String longitude=request.getParameter("longitude");//经度
//		String developId=request.getParameter("developId");//微信公众号唯一标识
//		TbOrganization tbOrganization=null;
//		try{
//			// 获取公众号关联项目列表
//			List<Map<String, Object>> relationOrgs=publicNoManager.getWxPublicnoOrgRelations(developId);
//			int counts=0;
//			boolean flg=false;
//			if(!CollectionUtils.isEmpty(relationOrgs)){
//				if(relationOrgs.size()>1){
//					// 根据城市对项目进行分组
////					Map<String, List<Map<String, Object>>> resultMap=publicNoManager.getWxPublicnoOrgRelationsGroupByCity(relationOrgs);
////					model.addAttribute("resultMap", resultMap);
//					for(int i=0;i<relationOrgs.size();i++){
//						Map<String,Object> map=relationOrgs.get(i);
//						if(map.get("lng")!=null&&StringUtils.isNotBlank(map.get("lng").toString())){
//							BigDecimal lng=new BigDecimal(map.get("lng").toString());
//							BigDecimal lat=new BigDecimal(map.get("lat").toString());
//							int count=MapDistanceUtil.getDistance(Double.valueOf(longitude),Double.valueOf(latitude),
//									lng.doubleValue(),lat.doubleValue());
//							if(counts==0 && !(flg)){
//								flg=true;
//								counts=count;
//								tbOrganization=propertyManager.getTbOrganizationById((Integer) relationOrgs.get(i).get("id"));
//							}
//							if(counts==0 && flg){
//								break;
//							}
//							if(count<counts){
//								counts=count;
//								tbOrganization=propertyManager.getTbOrganizationById((Integer) relationOrgs.get(i).get("id"));
//							}
//						}
//					}
//				}
//			}
//		}catch(Exception e){
//			log.error("controller get choiceOrgAddressIndex error{}", e);
//		}
//
//		OrgDto orgDto = new OrgDto();
//		if (tbOrganization != null){
//			orgDto.setId(tbOrganization.getId());
//			orgDto.setName(tbOrganization.getName());
//		}
//		return AppResultUtil.createSuccesDto(orgDto);

		ScopeEntity  scopeEntity = LocationUtil.findNeighPosition(longitude, latitude, 1);
		List<OrgDto> orgList     = propertyManager.getScopeOrgList(scopeEntity, developId);
		return AppResultUtil.createSuccesDto(orgList);
	}

	public WxUser saveWxUser(String developId, String openId, String organizationId) {
		WxUser   wxUser   = new WxUser();
		UserInfo userInfo = weChatApiManager.getUserInfo(developId, openId);
		wxUser.setDevelopId(developId);
		wxUser.setOpenId(openId);
		if (userInfo != null) {
			if (StringUtils.isNotEmpty(userInfo.getNickname())) {
				String nickName = StringUtil.StringFilter(EmojiFilterUtils
						.filterEmoji(userInfo.getNickname().replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*")));
				wxUser.setNickName(nickName);
			} else {
				wxUser.setNickName("微信用户");
			}
			wxUser.setCity(userInfo.getCity());
			wxUser.setCountry(userInfo.getCountry());
			wxUser.setProvince(userInfo.getProvince());
			wxUser.setLanguage(userInfo.getLanguage());
			wxUser.setHeadimgUrl(userInfo.getHeadimgurl());
		}
		wxUser.setSubscribeTime(new Date());
		wxUser.setIsSubscribe("subscribe");
		if (StringUtils.isNotBlank(organizationId)) {
			wxUser.setOrganizationId(Integer.parseInt(organizationId));
		}
		scWxuserManager.saveModel(wxUser);
		return wxUser;
	}


	/**
	 * 跳转服务列表页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/serviceListPage")
	public ModelAndView serviceListPage(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 userStatus = request.getParameter("userStatus");
		String register   = request.getParameter("register");
		String organId    = request.getParameter("organId");

		model.addAttribute("openId", openId);
		model.addAttribute("userId", userId);
		model.addAttribute("developId", developId);
		model.addAttribute("userStatus", userStatus);
		model.addAttribute("register", register);
		model.addAttribute("organId", organId);
		return new ModelAndView("wechat/serviceList", model.asMap());
	}

	/**
	 * 跳转公告列表页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/infoListPage")
	public ModelAndView infoListPage(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 userStatus = request.getParameter("userStatus");
		String register   = request.getParameter("register");
		String organId    = request.getParameter("organId");

		model.addAttribute("openId", openId);
		model.addAttribute("userId", userId);
		model.addAttribute("developId", developId);
		model.addAttribute("userStatus", userStatus);
		model.addAttribute("register", register);
		model.addAttribute("organId", organId);
		return new ModelAndView("wechat/informationList", model.asMap());
	}

	@RequestMapping(value = "/tradeArea")
	public ModelAndView tradeArea(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();

		return new ModelAndView("wechat/tradeArea", model.asMap());
	}

	/**
	 * 获取微信公众号关联项目列表
	 * 按字母分类(A-Z)
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/wechatPublicOrgList")
	@ResponseBody
	public AppResultDto wechatPublicOrgList(HttpServletRequest request) {

		String developId = request.getParameter("developId");
		String orgName   = request.getParameter("orgName");

		if (StringUtils.isBlank(developId)) {
			return AppResultUtil.createErrorDto("100", "微信公众号ID为空");
		}

		List<String> list1 = new ArrayList<String>();

		List<WxPublicnoOrgRelation> list = scWxuserManager.getWxOrgRelation(developId, orgName);

		if (null != list && list.size() > 0) {
			for (WxPublicnoOrgRelation relation : list) {
				TbOrganization organization = organizationManager.getOrganizationById(relation.getOrganizationId());
				if (organization != null && "1".equals(organization.getIsEnabled()))
					list1.add(organization.getName() + ":" + organization.getId());
			}
		}


		Map<String, List<OrgDto>> stringListMap = orgSort(list1);

		List<Map<String, Object>> orgList = new ArrayList<Map<String, Object>>();

		if (!stringListMap.isEmpty()) {
			for (Map.Entry<String, List<OrgDto>> set : stringListMap.entrySet()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("key", set.getKey());
				map.put("data", set.getValue());
				orgList.add(map);
			}
		}


		return AppResultUtil.createSuccesDto(orgList);
	}

	/**
	 * 对项目列表进行排序
	 *
	 * @param list
	 */
	public Map<String, List<OrgDto>> orgSort(List<String> list) {
		Sort                      sort = new Sort();
		Map<String, List<String>> map  = sort.sort(list);

		Map<String, List<OrgDto>> resultMap = new TreeMap<String, List<OrgDto>>(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				if (o1.equalsIgnoreCase(o2) && "#".equalsIgnoreCase(o1)) {
					return 0;
				} else if ("#".equalsIgnoreCase(o1)) {
					return 1;
				} else {
					return o1.compareTo(o2);  //从小到大排序
				}
			}
		});

		// 遍历排序之后的集合
		for (Map.Entry<String, List<String>> listEntry : map.entrySet()) {
			for (String value : listEntry.getValue()) {

				// map中的key是否包含品牌首字母，若存在则把数据处理之后存储到对象里面，然后添加到List里面,
				// 否则新建key然后再把数据处理之后存储到对象里面，然后添加到List里面
				String key = listEntry.getKey();
				if (resultMap.containsKey(key)) {
					OrgDto orgDto = new OrgDto();

					String[] brandArray = value.split(":"); // 按:把品牌名称和id分开
					orgDto.setName(brandArray[0]);                    // 品牌名称
					orgDto.setId(Integer.parseInt(brandArray[1]));  // 品牌id

					resultMap.get(key).add(orgDto);

				} else {
					List<OrgDto> list2  = new ArrayList<OrgDto>();
					OrgDto       orgDto = new OrgDto();

					String[] brandArray = value.split(":"); // 按:把品牌名称和id分开
					orgDto.setName(brandArray[0]);                    // 品牌名称
					orgDto.setId(Integer.parseInt(brandArray[1]));  // 品牌id
					list2.add(orgDto);

					resultMap.put(key, list2);
				}
			}
		}

		return resultMap;
	}


	/**
	 * 跳转选择项目列表页面
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/chooseItemView")
	@ResponseBody
	public ModelAndView chooseItemView(HttpServletRequest request) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			init(model);
			String openId    = request.getParameter("openId");
			String developId = request.getParameter("developId");

			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			return new ModelAndView("wechat/chooseItem", model.asMap());
		} catch (Exception e) {
			log.error("controller find chooseItemView error{}", LogExceptionStackUtil.LogExceptionStack(e));
		}

		return null;
	}


	/**
	 * 获取微信公众号商圈发现界面的服务列表 (不带分类)
	 *
	 * @return
	 */
	@RequestMapping(value = "/discoverServiceList")
	@ResponseBody
	public AppResultDto discoverServiceList(HttpServletRequest request) {
		try {
			String orgId = request.getParameter("orgId");
			return AppResultUtil.createSuccesDto(weChatIndexManager.getDiscoverServiceList(orgId));
		} catch (Exception e) {
			log.info("WeChatIndexController discoverServiceList Error =========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询service列表失败");
		}
	}

	/**
	 * 获取微信公众号商圈发现界面的服务列表 (带分类)
	 *
	 * @return
	 */
	@RequestMapping(value = "/discoverServiceListCategory")
	@ResponseBody
	public AppResultDto discoverServiceListCategory(HttpServletRequest request) {
		try {
			String orgId = request.getParameter("orgId");//项目id
			return AppResultUtil.createSuccesDto(weChatIndexManager.discoverServiceListCategory(orgId));
		} catch (Exception e) {
			log.info("WeChatIndexController discoverServiceListCategory Error =========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询service列表失败");
		}
	}

	/**
	 * 获取微信公众号商圈发现界面的爆款商品列表
	 * 爆品
	 *
	 * @return
	 */
	@RequestMapping(value = "/goodsList")
	@ResponseBody
	public AppResultDto goodsList(HttpServletRequest request) {
		try {

			//先从缓存取
			String goodsJson = baseRedisService.get(CodeConstants.GOODS_CATEGORY_KEY);
			if (StringUtils.isNotEmpty(goodsJson)) {
				List<Map> goodsList = JSONObject.parseArray(goodsJson, Map.class);
				if (goodsList != null) {
					return AppResultUtil.createSuccesDto(goodsList);
				}
			}

			//图片前缀
			String pre_ImgUrl = "https://wxn.avic-s.com/attachment/";

			//获取福利商城爆品列表
			String     resultStr = HttpKit.get("https://wxn.avic-s.com/app/index.php?i=17&c=entry&m=superdesk_shopv2&do=mobile&r=pc.api.recommendGoods");
			JSONObject object    = (JSONObject) JSON.parse(resultStr);

			List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();

			if ((Integer) object.get("status") == 1) {
				JSONObject jsonObject = JSON.parseObject(object.get("result").toString());

				if (jsonObject != null) {
					for (int i = 0; i < 6; i++) {//取6条数据
						if (jsonObject.containsKey(i + "")) {
							Map                 map1 = JSON.parseObject(jsonObject.getString(i + ""), Map.class);
							Map<String, Object> map  = new HashMap<String, Object>();
							map.put("goodsPic", map1.get("thumb").toString().contains("http") ? map1.get("thumb") : pre_ImgUrl + map1.get("thumb"));
							map.put("goodsUrl", "https://wxn.avic-s.com/app/index.php?i=17&c=entry&m=superdesk_shopv2&do=mobile&r=goods.detail&id=" + map1.get("id"));
							map.put("goodsPrice", map1.get("marketprice").toString());
							map.put("goodsName", map1.get("title").toString());

							goodList.add(map);
						}
					}
					//服务项放入缓存 每天更新
					baseRedisService.set(CodeConstants.GOODS_CATEGORY_KEY, JSONObject.toJSONString(goodList), 24 * 60 * 60);
				}
			}

			return AppResultUtil.createSuccesDto(goodList);
		} catch (Exception e) {
			log.info("WeChatIndexController goodsList Error =========>:" + e.getMessage());
			return AppResultUtil.createErrorDto(AppConstants.GET_BANNER_DETAIL_ERROR, "查询goodsList列表失败");
		}
	}

	/**
	 * 获取短信验证码
	 * 校验白名单
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getSmsCode")
	@ResponseBody
	public AppResultDto getSmsCode(HttpServletRequest request, HttpServletResponse response) {

		String orgId         = request.getParameter("orgId");
		String openId        = request.getParameter("openId");
		String mobile        = request.getParameter("mobile");
		String oldUrl        = request.getParameter("oldUrl");
		String serviceNumber = request.getParameter("serviceNumber");
		if (oldUrl.contains("serviceNumber")) {
			String u1 = oldUrl.substring(oldUrl.indexOf("serviceNumber="));
			String u2 = u1.substring(0, u1.indexOf("&"));
			serviceNumber = u2.substring(u2.indexOf("=") + 1);
		}
		log.info("获取短信验证码 :WechatIndexController getSmsCode orgId:{},openId:{},mobile:{}", orgId, openId, mobile);

		try {
			//校验当前用户该项目下的手机号是否重复
			//用户在某项目下某手机号码是否登录绑定验证
			//航电接口不需要白名单验证，手机号码验证后直接获取验证码
			//电子放行条，访客 ，订餐，会议室需要先判断是否经过白名单验证，如果航电验证过，但没有经过白名单验证需要验证是否在白名单
			WxUser  wxUser  = scWxuserManager.getScWxuserByOpenId(openId);
			AppUser appUser = appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));//只查询未禁用状态的用户

			ServiceTypeInfo serviceTypeInfo = serviceTypeInfoManager.getServiceTypeInfoByServiceCode(serviceNumber);
			String          roleType        = "";
			if (serviceTypeInfo != null) {
				ServiceProjectAllocation localtion = serviceProjectAllocationManager.getServiceProjectAllocation(serviceTypeInfo.getId(), Integer.parseInt(orgId));
				if (localtion.getRoleGroup().equals("2")) {
					roleType = "2";
				} else {
					roleType = "1";
				}
			}

			if (oldUrl.indexOf("/customervoice/h5") != -1 //投诉与表扬
					|| oldUrl.indexOf("/wx/outlink") != -1 //派修
//					|| oldUrl.indexOf("/weChatOath/redirectHdReportRepair")!=-1 //报事
					|| oldUrl.indexOf("/wechat/visitor/authorVisitor") != -1
					|| oldUrl.indexOf("/wechat/neigou/wjdcDo") != -1  //问卷调查
					|| oldUrl.indexOf("/wechat/neigou/tsbyDo") != -1  //投诉建议
					|| "1".equals(roleType)
			) {
				if (appUser != null && appUser.getIsLogin() == 1) {
//					return AppResultUtil.createErrorDto("100","该手机号已登录");
				}
			} else {
				//白名单验证
				if (wxUser != null) {
					if (appUser == null) {
						return AppResultUtil.createErrorDto("300", "该手机号权限不足，请联系管理员");
					} else {
						String userType = appUser.getUserType();
						// 低权限用户或者被禁用的用户
						if (StringUtil.isEqual("-1", userType) || StringUtil.isEqual("2", userType)) {
							return AppResultUtil.createErrorDto("300", "该手机号权限不足，请联系管理员");
						}
					}
				}
			}
			//然后再进行传输验证码
			String code    = NumberUtils.getValidateCode();
			String content = "您的验证码为" + code + "，15分钟内有效，如非本人操作，请忽略。";
			//发送短信
			String result = smsAuthCodeManager.smsSendByOrgId(orgId, content, mobile, code, CodeConstants.SMS_CODE_TYPE);

			if ("Success".equals(result)) {
				return AppResultUtil.createSuccesDto();
			} else if ("3".equalsIgnoreCase(result)) {
				return AppResultUtil.createErrorDto("100", "该项目下未配置短信账号");
			} else {
				return AppResultUtil.createErrorDto("100", "验证码发送失败");
			}
		} catch (Exception e) {
			log.info(e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "验证码发送失败");
	}


	/**
	 * 用户注册登录接口
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login")
	@ResponseBody
	public AppResultDto login(HttpServletRequest request) {

		String orgId      = request.getParameter("orgId");
		String openId     = request.getParameter("openId");
		String mobile     = request.getParameter("mobile");
		String mobileCode = request.getParameter("mobileCode");
		String oldUrl     = request.getParameter("oldUrl");
		log.info("登录注册 :WechatIndexController login orgId--:{},openId--:{},mobile--:{},mobileCode--:{},oldUrl:{}",
				orgId, openId, mobile, mobileCode, oldUrl);

		if (StringUtils.isBlank(mobileCode)) {
			return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入验证码");
		}
		if (!"9999".equalsIgnoreCase(mobileCode)) {//9999不验证
			SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(mobile, mobileCode, "1", 15);
			if (smsAuthCode == null) {
				return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
			}
		}

		//先走航电的登录
		//再绑定
		//1.航电登录 ---2.平台登录
		//1.1 查找用户 不存在注册  存在绑定
		//2.平台登录 ---2.航电登录
		//2.1 注册绑定 登录航电
//        if(oldUrl.indexOf("/customervoice/h5") != -1
//        		|| oldUrl.indexOf("/wx/outlink")!=-1 //派修
//				|| oldUrl.indexOf("/weChatOath/redirectHdReportRepair")!=-1 //报事
//				|| oldUrl.indexOf("/wechat/visitor/authorVisitor")!=-1
//				|| oldUrl.indexOf("/wechat/neigou/wjdcDo")!=-1  //问卷调查
//				|| oldUrl.indexOf("/wechat/neigou/tsbyDo")!=-1  //投诉建议
//				) {
//	        try {
//				JSONObject object = hdLogin(mobile, openId, orgId);
//				// 对直接跳方法的服务模块进行url重新组装
//				// 1.如果是智慧访客请求 则需对url重新拼装,否则会丢失项目名称
//				if(oldUrl.indexOf("/visitor/authorVisitor") != -1){
//					oldUrl = request.getContextPath()+"/wechat/visitor/authorVisitor";
//					object.put("oldUrl",oldUrl);
//				}
//				return AppResultUtil.createSuccesDto(object);
//			} catch (Exception e) {
//				log.info("WeChatIndexController login =======> " + e.getMessage());
//				e.printStackTrace();
//			}
//        }else {
		//查找tb_user,关联tb_wxUser
		JSONObject object = new JSONObject();
		WxUser     wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		AppUser    user   = appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));
		//根据项目id查询绑定的航电项目id
		TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));
		String         hdProjectId  = organization.getHdProjectId();
		object.put("hdProjectId", StringUtils.isBlank(hdProjectId) ? "440305001200" : hdProjectId);
		object.put("hdVoiceProjectId", organization.getHdVoiceProjectId());
		if (user != null) {
			try {
				// 此手机账号登录成功后将 同项目下相同wxUserid的用户置为下线状态
				appUserManager.updateAppUser(user.getId(), wxUser.getId(), Integer.parseInt(orgId));
				//个人时 绑定企业账号
				updateUserAccount(orgId, user.getVirtualArchId(), openId);
			} catch (Exception e) {
				log.info("WeChatIndexController login =======> " + e.getMessage());
			}

			user.setModifyTime(new Date());
			user.setWxUserId(wxUser.getId());
			user.setIsBinding(1);
//        		user.setIsEnabled("1");
			//绑定白名单时 如果没注册航电则默认注册航电;如果已经注册航电但是未登录,则只需改变登录状态即可
			Map<String, Object> result;
			try {
				if (StringUtils.isBlank(user.getUserCode())) {//未注册
					result = appUserManager.hdRegister(mobile, openId);
					if (result != null && (Boolean) result.get("success")) {
						Map<String, Object> data = (Map<String, Object>) result.get("data");
						user.setUserCode((String) data.get("userCode"));
					}
				}
				user.setIsLogin(1);
				appUserManager.updateModel(user);
				object.put("userId", user.getId());
				object.put("userName", user.getUserName());
				object.put("mobile", mobile);
				object.put("hdUserId", user.getUserCode());
				object.put("virId", user.getVirtualArchId());
				if (user.getVirtualArchId() != null) {
					VirtualArchitecture v = propertyManager.getVirtualArchitectureById(user.getVirtualArchId());
					if (v != null) {
						object.put("virName", v.getName());
						object.put("address", v.getAddress());
						if (StringUtils.isNotEmpty(user.getAddress())) {
							object.put("address", user.getAddress());
						}
					}
				}
				//个人时获得企业及企业账号信息 空调加时使用 by qzy
				List<UserAccountRecode> userList = userAccountManager.getUserAccountRecode(orgId, openId);
				if (userList != null && userList.size() > 0) {
					UserAccountRecode userAcc = userList.get(0);
					if (userAcc != null) {
						VirtualAccount virAcc = virtualAccountManager.get(userAcc.getAccountId());
						object.put("accId", virAcc.getId());
						object.put("virId", virAcc.getVirId());
						object.put("account", virAcc.getVirAccount());
					}
				}

				try {
					// 白名单登陆成功后,企业内购也标记为已登陆
//						neigouManager.neigouLogin(openId,wxUser.getDevelopId(),mobile);
					neigouManager.newNeigouLogin(openId, wxUser.getDevelopId(), mobile);
				} catch (Exception e) {
					log.error("同步企业内购白名单用户登陆异常 ============>" + e.getMessage());
				}

				return AppResultUtil.createSuccesDto(object);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				object = hdLogin(mobile, openId, orgId);
				// 对直接跳方法的服务模块进行url重新组装
				// 1.如果是智慧访客请求 则需对url重新拼装,否则会丢失项目名称
				return AppResultUtil.createSuccesDto(object);
			} catch (Exception e) {
				log.info("WeChatIndexController login =======> " + e.getMessage());
				e.printStackTrace();
			}
		}
		if (oldUrl.indexOf("/visitor/authorVisitor") != -1) {
			oldUrl = request.getContextPath() + "/wechat/visitor/authorVisitor";
			object.put("oldUrl", oldUrl);
		}
//        }

		return AppResultUtil.createErrorDto("100", "登录失败");
	}

	/**
	 * 用户切换手机号码登录接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/changeAccountLogin")
	@ResponseBody
	public AppResultDto changeAccountLogin(HttpServletRequest request, HttpServletResponse response) {

		String orgId      = request.getParameter("orgId");
		String userId     = request.getParameter("userId");
		String openId     = request.getParameter("openId");
		String mobile     = request.getParameter("mobile");
		String mobileCode = request.getParameter("mobileCode");
		String oldUrl     = request.getParameter("oldUrl");
		log.info("登录注册 :WechatIndexController login orgId--:{},openId--:{},mobile--:{},mobileCode--:{}", orgId, openId, mobile, mobileCode);

		if (StringUtils.isBlank(mobileCode)) {
			return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入验证码");
		}
		if (!"9999".equalsIgnoreCase(mobileCode)) {//9999不验证
			SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(mobile, mobileCode, "1", 15);
			if (smsAuthCode == null) {
				return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
			}
		}
		//原来的账号失效，下线
		//新账号绑定，上线
		AppUser user = appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));
		if (user == null) {
			return AppResultUtil.createErrorDto("300", "该手机号权限不足，请联系管理员");
		}
		//航电登录切换到白名单登录
		//查找tb_user,关联tb_wxUser
		AppUser oldUser = appUserManager.get(Integer.parseInt(userId));
		if (oldUser != null) {
			oldUser.setIsBinding(0);
			oldUser.setIsEnabled("0");
			oldUser.setWxUserId(null);
			oldUser.setIsLogin(0);
			appUserManager.updateModel(oldUser);
		}
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		user.setModifyTime(new Date());
		user.setWxUserId(wxUser.getId());
		user.setIsBinding(1);
//		user.setIsEnabled("1");
		user.setIsLogin(1);

		JSONObject object = new JSONObject();
		//绑定白名单时 如果没注册航电则默认注册航电;如果已经注册航电但是未登录,则只需改变登录状态即可
		Map<String, Object> result;
		try {
			if (StringUtils.isBlank(user.getUserCode())) {//未注册
				result = appUserManager.hdRegister(mobile, openId);
				if (result != null && (Boolean) result.get("success")) {
					Map<String, Object> data = (Map<String, Object>) result.get("data");
					user.setUserCode((String) data.get("userCode"));
				}
			}
			appUserManager.updateModel(user);
			object.put("userId", user.getId());
			object.put("userName", user.getUserName());
			//根据项目id查询绑定的航电项目id
			TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));
			String         hdProjectId  = organization.getHdProjectId();
			object.put("hdProjectId", StringUtils.isBlank(hdProjectId) ? "440305001200" : hdProjectId);
			object.put("hdVoiceProjectId", organization.getHdVoiceProjectId());
			object.put("hdUserId", user.getUserCode());

			if (user.getVirtualArchId() != null) {
				VirtualArchitecture v = propertyManager.getVirtualArchitectureById(user.getVirtualArchId());
				if (v != null) {
					object.put("virId", user.getVirtualArchId());
					object.put("virName", v.getName());
					object.put("address", v.getAddress());
					if (StringUtils.isNotEmpty(user.getAddress())) {
						object.put("address", user.getAddress());
					}
				}
			}
			//升级需要处理企业账号
			updateUserAccount(orgId, user.getVirtualArchId(), openId);

			// 对直接跳方法的服务模块进行url重新组装
			// 1.如果是智慧访客请求 则需对url重新拼装,否则会丢失项目名称
			if (oldUrl.indexOf("/visitor/authorVisitor") != -1) {
				oldUrl = request.getContextPath() + "/wechat/visitor/authorVisitor";
				object.put("oldUrl", oldUrl);
			}

			object.put("mobile", mobile);
			//个人时获得企业及企业账号信息 空调加时使用 by qzy
			List<UserAccountRecode> userList = userAccountManager.getUserAccountRecode(orgId, openId);
			if (userList != null && userList.size() > 0) {
				UserAccountRecode userAcc = userList.get(0);
				if (userAcc != null) {
					VirtualAccount virAcc = virtualAccountManager.get(userAcc.getAccountId());
					object.put("accId", virAcc.getId());
					object.put("virId", virAcc.getVirId());
					object.put("account", virAcc.getVirAccount());
				}
			}

			try {
				// 白名单登陆成功后,企业内购也标记为已登陆
				neigouManager.neigouLogin(openId, wxUser.getDevelopId(), mobile);
			} catch (Exception e) {
				log.error("同步企业内购白名单用户登陆异常 ============>" + e.getMessage());
			}

			return AppResultUtil.createSuccesDto(object);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return AppResultUtil.createErrorDto("100", "登录失败");
	}

	/**
	 * 个人时 同步且绑定企业账号
	 *
	 * @param orgId
	 * @param openId
	 * @throws Exception
	 */
	private void updateUserAccount(String orgId, Integer virtualArchId, String openId) throws Exception {

		String         virtualId = "";
		Long           accId     = null;
		TbOrganization org       = organizationManager.getOrganizationById(Integer.parseInt(orgId));
		if (null != org && org.getAccountType() == 1) {

			VirtualArchitecture vir = virtualArchManager.get(virtualArchId);
			if (null != vir) {
				List<VirtualAccount> listAS = virtualAccountManager.getVirAccountByVirId(vir.getId());
				if (listAS.size() >= 1) {
					VirtualAccount va = listAS.get(0);
					virtualId = va.getId().toString();
					accId = va.getId();
				}
			}
		}
		//先删除 旧登录记录
		//一个公众号下 有多个项目 一个openId
		//就是一个公众号 有多个会议室项目 会议室项目的openid 有可能一样的
		List<UserAccountRecode> atRecodeList = userAccountManager.getUserAccountRecode(orgId, openId);
		for (UserAccountRecode recode : atRecodeList) {
			userAccountManager.remove(recode.getId());
		}
		if (StringUtils.isNotEmpty(virtualId) && null != accId) {
			List<UserAccountRecode> userAccList = userAccountManager.getUserAccountByAccount(orgId, virtualId, openId);
			if (userAccList != null && userAccList.size() > 0) {//如果有记录修改记录
				UserAccountRecode userAcc = userAccList.get(0);
				userAcc.setModifier(openId);
				userAcc.setModifyTime(new Date());
				userAcc.setIsOnline("2");
				userAcc.setOrgId(orgId);
				userAccountManager.updateModel(userAcc);

			} else {//如果没记录需要新增记录
				UserAccountRecode userAcc = new UserAccountRecode();
				userAcc.setAccountId(accId);
				userAcc.setIsOnline("2");
				userAcc.setOpenId(openId);
				userAcc.setUserId("");
				userAcc.setOrgId(orgId);
				userAcc.setCreateTime(new Date());
				userAcc.setCreator(openId);
				userAcc = userAccountManager.save(userAcc);

			}
		}
	}

	/**
	 * 航电注册接口(低权限用户)
	 *
	 * @param mobile
	 * @param openId
	 * @param orgId
	 * @return
	 * @throws Exception
	 */
	private JSONObject hdLogin(String mobile, String openId, String orgId) throws Exception {

		JSONObject object = new JSONObject();

		// 首先判断用户是否已经注册
		// 1.如果已经注册,但是未登录,则去改变登录状态就可以
		WxUser  wxUser    = scWxuserManager.getScWxuserByOpenId(openId);
		AppUser existUser = appUserManager.getAppUsersByPhoneAndOrg(mobile, orgId, null);
		//根据项目id查询绑定的航电项目id
		TbOrganization organization = propertyManager.getTbOrganizationById(Integer.parseInt(orgId));
		String         hdProjectId  = organization.getHdProjectId();
		object.put("hdProjectId", StringUtils.isBlank(hdProjectId) ? "440305001200" : hdProjectId);
		object.put("hdVoiceProjectId", organization.getHdVoiceProjectId());

		// 如果用户存在(被禁用的白名单用户也可以登录π平台)
		if (existUser != null) {
			try {
				// 此手机账号登录成功后将 同项目下相同wxUserid的用户置为下线状态
				appUserManager.updateAppUser(existUser.getId(), wxUser.getId(), Integer.parseInt(orgId));
			} catch (Exception e) {
				log.info("WeChatIndexController hdLogin =======> " + e.getMessage());
			}

			existUser.setIsLogin(1);// 设置用户登录状态
			// 白名单用户设置绑定
			if (StringUtil.isEqual("0", existUser.getUserType()) || StringUtils.isBlank(existUser.getUserType())) {
				existUser.setIsBinding(1);
			}
			existUser.setWxUserId(wxUser.getId());// 绑定用户关系
			appUserManager.saveOrUpdateAppUser(existUser);


			// π平台入口登录,判断该用户是否白名单用户,如果是白名单用户,查询其企业账号信息
			if (StringUtils.isBlank(existUser.getUserType()) || StringUtil.isEqual("0", existUser.getUserType())) {
				//个人时获得企业及企业账号信息 空调加时使用 by qzy
				List<UserAccountRecode> userList = userAccountManager.getUserAccountRecode(orgId, openId);
				if (userList != null && userList.size() > 0) {
					UserAccountRecode userAcc = userList.get(0);
					if (userAcc != null) {
						VirtualAccount virAcc = virtualAccountManager.get(userAcc.getAccountId());
						object.put("accId", virAcc.getId());
						object.put("virId", virAcc.getVirId());
						object.put("account", virAcc.getVirAccount());
					}
				}
			}


			object.put("userId", existUser.getId());
			object.put("hdUserId", existUser.getUserCode());
			object.put("mobile", mobile);
			log.info("hdLogin 用户已存在,更新其状态:======>userId:{},hdUserId:{}", existUser.getId(), existUser.getUserCode());
		} else {
			Map<String, Object> result  = appUserManager.hdRegister(mobile, openId);
			boolean             success = (Boolean) result.get("success");//是否成功

			try {
				// 此账号登录成功后将 其它同项目下相同wxUserid的用户信息还原
				appUserManager.updateAppUser(null, wxUser.getId(), Integer.parseInt(orgId));
			} catch (Exception e) {
				log.info("WeChatIndexController hdLogin =======> " + e.getMessage());
			}

			//注册成功后保存用户信息
			if (success) {
				Map<String, Object> data = (Map<String, Object>) result.get("data");
				AppUser             user = new AppUser();
				user.setUserMobile(mobile);
				user.setCreateTime(new Date());
				user.setWxUserId(wxUser.getId());
				user.setUserCode((String) data.get("userCode"));
				user.setOrganizationId(Integer.parseInt(orgId));
				user.setIsEnabled("1");
				user.setIsBinding(0);
				user.setIsLogin(1);
				user.setUserType("-1");//航电注册用户
				Integer userId = appUserManager.saveOrUpdateAppUser(user);
				object.put("userId", userId);
				object.put("hdUserId", user.getUserCode());
				object.put("mobile", mobile);
			}
		}

		return object;
	}


	/**
	 * 获取天气信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getWeatherInfo")
	@ResponseBody
	public AppResultDto getWeatherInfo(HttpServletRequest request) {
		String lon = request.getParameter("lon");// 经度
		String lat = request.getParameter("lat");// 纬度
		if (org.apache.commons.lang3.StringUtils.isAnyBlank(lon, lat)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		String result = HttpKit.sendGet("https://d7.weather.com.cn/fishing/api/v1/tab", "lon=" + lon + "&lat=" + lat);
		if (StringUtils.isNotBlank(result)) {
			JSONObject object = JSONObject.parseObject(result);
			if ("ok".equalsIgnoreCase((String) object.get("status"))) {
				return AppResultUtil.createSuccesDto(object.get("result"));
			}
		}

		return AppResultUtil.createErrorDto("100", "获取天气信息异常");
	}


	/**
	 * 企业内购获取短信验证码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getNeiGouSmsCode")
	@ResponseBody
	public AppResultDto getNeiGouSmsCode(HttpServletRequest request) {

		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");
		String mobile    = request.getParameter("mobile");
		String oldUrl    = request.getParameter("oldUrl");
		log.info("企业内购获取短信验证码 :WechatIndexController getNeiGouSmsCode openId:{},mobile:{},developId:{},oldUrl{}", openId, mobile, developId, oldUrl);

		if (org.apache.commons.lang3.StringUtils.isAnyBlank(openId, developId, mobile)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
			// 首先查询当前公众号下该用户(手机号)是否有企业购登录权限(即白名单);
			// 根据手机号去查询白名单用户
			List<Map<String, Object>> users = appUserManager.getWhiteUserByMobileAndOrg2(mobile, developId);
			if (users == null || users.size() == 0) {
				log.warn("==== 当前手机号不是白名单用户 === 或者该白名单用户所属项目未在当前公众号下绑定 ===");
				return AppResultUtil.createErrorDto("300", "该手机号权限不足，请联系管理员");
			}
			//生成验证码
			String code    = NumberUtils.getValidateCode();
			String content = "您的验证码为" + code + "，15分钟内有效，如非本人操作，请忽略。";

			//发送短信
			String result = smsAuthCodeManager.smsSendByOrgId(users.get(0).get("organizationId").toString(), content, mobile, code, CodeConstants.SMS_CODE_TYPE);
			if ("Success".equals(result)) {
				return AppResultUtil.createSuccesDto();
			} else if ("3".equalsIgnoreCase(result)) {
				return AppResultUtil.createErrorDto("100", "该项目下未配置短信账号");
			} else {
				return AppResultUtil.createErrorDto("100", "验证码发送失败");
			}
		} catch (Exception e) {
			log.info("WechatIndexController getNeiGouSmsCode获取验证码异常=======>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "验证码发送失败");
	}


	/**
	 * 企业内购用户登录
	 *
	 * @return
	 */
	@RequestMapping("/neigouLogin")
	@ResponseBody
	public AppResultDto neigouLogin(HttpServletRequest request) {
		JSONObject object     = new JSONObject();
		String     openId     = request.getParameter("openId");
		String     mobile     = request.getParameter("mobile");
		String     developId  = request.getParameter("developId");
		String     mobileCode = request.getParameter("mobileCode");
		String     oldUrl     = request.getParameter("oldUrl");
		log.info("企业内购 :WechatIndexController puchaseLogin openId--:{},mobile--:{},mobileCode--:{},oldUrl--:{},developId--:{}", openId, mobile, mobileCode, oldUrl, developId);

		if (org.apache.commons.lang3.StringUtils.isAnyBlank(openId, mobile, developId, mobileCode)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		if (StringUtils.isBlank(mobileCode)) {
			return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入验证码");
		}
		SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(mobile, mobileCode, "1", 15);
		if (smsAuthCode == null) {
			return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
		}

		try {
			neigouManager.neigouLogin(openId, developId, mobile);
			object.put("openId", openId);
			object.put("mobile", mobile);
			object.put("developId", developId);
			object.put("oldUrl", oldUrl);
			return AppResultUtil.createSuccesDto(object);
		} catch (Exception e) {
			log.error("WechatIndexController neigouLogin异常===========>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "登陆失败!");
		}
	}

	/**
	 * 跳转选择企业列表页面
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toSelectCompanyPurchase")
	public ModelAndView toSelectCompanyPurchase(HttpServletRequest request) {
		Model  model     = new ExtendedModelMap();
		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");

		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		return new ModelAndView("wechat/enterprisePurchase/selectCompanyPurchase", model.asMap());
	}

	/**
	 * 获取企业内购白名单用户企业列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getWhiteVirList")
	@ResponseBody
	public AppResultDto getWhiteVirList(HttpServletRequest request) {
		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");
		try {
			InPuchaseUser             puchaseUser = neigouManager.getPuchaseUser(openId, developId, null);
			List<Map<String, Object>> list        = neigouManager.getVirListByUser(puchaseUser);
			return AppResultUtil.createSuccesDto(list);
		} catch (Exception e) {
			log.error("getWhiteVirList error=====>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "获取企业内购白名单用户企业列表失败");
		}
	}

	/**
	 * 删除redis缓存中所有项目的服务列表
	 * 请在微信中打开
	 *
	 * @param request
	 * @return
	 * @url https://superdesk.avic-s.com/super_service/wechat/index/delRedisServiceList
	 */
	@RequestMapping(value = "/delRedisServiceList")
	@ResponseBody
	public AppResultDto delRedisServiceList(HttpServletRequest request) {
		baseRedisService.delKeyLike(CodeConstants.ORG_SERVICE_LIST_KEY);
		baseRedisService.delKeyLike(CodeConstants.ORG_SERVICE_CATEGORY_KEY);
		return AppResultUtil.createSuccesDto();
	}


	/**
	 * 校验当前用户是否拥有该服务功能权限
	 *
	 * @param id          用户id或者企业账号id 如果是未登录,就传空或null
	 * @param serviceCode 服务编码
	 * @param accountType 账号类型 0-企业 1-个人
	 * @return
	 */
	@RequestMapping(value = "/checkedHasFuncPerm")
	@ResponseBody
	public AppResultDto checkedHasFuncPerm(String id,
										   @RequestParam String serviceCode,
										   @RequestParam Integer accountType) {

		// 如果是未登录用户,则不校验
		if (org.apache.commons.lang3.StringUtils.isBlank(id) || Objects.isNull(id) || "null".equalsIgnoreCase(id)) {
			return AppResultUtil.createSuccesDto(true);
		}

		// 如果是登录用户,则需要分个人与企业账号判断
		Boolean result = enterprisePermissionManager.checkedHasFuncPerm(Integer.parseInt(id), serviceCode, accountType);
		return AppResultUtil.createSuccesDto(result);
	}

	/**
	 * 鉴权，二级权限
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/checkedServiceChild")
	@ResponseBody
	public AppResultDto checkedHasFuncPerm(String id) {
		return AppResultUtil.createSuccesDto(enterprisePermissionManager.checkedServiceChild(Integer.parseInt(id)));
	}


	/**
	 * 创建用户token
	 *
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/createToken")
	@ResponseBody
	public AppResultDto createToken(Integer userId) {
		String token    = JwtUtil.getToken(userId + "");
		String oldToken = baseRedisService.get(userId + "");
		if (oldToken != null) {
			baseRedisService.dele(oldToken);
			baseRedisService.dele(userId + "");
		}
		baseRedisService.set(userId + "", token, 60 * 60 * 24 * 7 * 30);
		baseRedisService.set(token, userId + "", 60 * 60 * 24 * 7 * 30);

		return AppResultUtil.createSuccesDto(token);
	}

	/**
	 * 用户认证（根据token返回用户信息）
	 *
	 * @param token
	 * @return
	 */
	@RequestMapping(value = "/userAuth")
	@ResponseBody
	public AppResultDto userAuth(String token) {
		//验证是否合法
		try {
			if (StringUtils.isEmpty(token)) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_NULL, "token为空");
			}
			if (JwtUtil.checkToken(token)) {
				//验证是否在有效期内
				if (baseRedisService.get(token) == null) {
					return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
				}
			} else {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_ILLEGAL, "token无效");
			}
			String userId = baseRedisService.get(token);
			if (userId == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_ILLEGAL, "token无效");
			}
			AppUser user = appUserManager.get(Integer.parseInt(userId));
			if (user == null || user.getUserType().equals("2")) {
				return AppResultUtil.createErrorDto(AppConstants.USER_ILLEGAL, "用户不存在");
			}
			return AppResultUtil.createSuccesDto(appUserService.convertTokenDto(user));
		} catch (ServletException e) {
			e.printStackTrace();
		}
		return AppResultUtil.createErrorDto(AppConstants.TOKEN_ILLEGAL, "token无效");
	}
}
