package com.palmnest.webapp.controller.wechat;


import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.output.DevicePermGroupOutDto;
import com.palmnest.application.dto.output.lingling.VisitorPassRecordVo;
import com.palmnest.model.AppUserOrgnizationRelation;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.lingling.DevicePermGroup;
import com.palmnest.model.lingling.LingLingCurrentset;
import com.palmnest.model.lingling.LingLingDevice;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.estateserve.release.VisitorInFoService;
import com.palmnest.service.lingling.manager.LingLingCurrentsetManager;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.service.ws.FacePlusClient;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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


/**
 * 新增用户信息提交到facePlus后台
 *
 * @author HJY
 */
@Slf4j
@Controller
@RequestMapping("/wechat/visitor/*")
public class VisitorUserInfoController extends BaseFormController {


	@Autowired
	private VisitorInFoManager visitorInFoManager;
	@Autowired
	private WeChatApiManager   weChatApiManager;
	@Autowired
	private ScWxuserManager    scWxuserManager;
	@Autowired
	private AppUserManager     appUserManager;
	@Autowired
	private PublicNoManager    publicNoManager;
	@Autowired
	private PropertyManager    propertyManager;
	@Autowired
	private LingLingManager    lingLingManager;
	@Autowired
	private VirtualArchManager virtualArchManager;
	@Autowired
	private UserManager        userManager;
	@Autowired
	private VisitorInFoService visitorInFoService;
	@Autowired
	private BaseRedisService       baseRedisService;
	@Autowired
	private LingLingCurrentsetManager lingLingCurrentsetManager;

	/**
	 * 邀约访客
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/authorVisitor")
	public ModelAndView authorVisitor(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");

		log.info("VisitorUserInfoController authorVisitor======>openId:{},developId:{},userId:{}", openId, developId, userId);

		model.addAttribute("openId", openId);
		model.addAttribute("userId", userId);
		model.addAttribute("developId", developId);
		if (StringUtils.isBlank(userId)) {
			log.info("========= 用户id为空 ==========");
			model.addAttribute("msg", "获取用户信息失败");
			return new ModelAndView("wechat/noPage", model.asMap());
		}
		Integer userIds=Integer.parseInt(userId);
		AppUser appUser = null;
		if(appUserManager.exists(userIds)){
			log.info("旧框架获取--------");
			appUser=appUserManager.get(userIds);
		}else{
			String database=Constants.DATABASE;
			if(StringUtils.isNotBlank(database)){
				log.info("新框架获取--------database:{}",database);
				appUser=appUserManager.findUserByNewFramework(userIds, database);
			}
		}
		log.info("authorVisitor--------appUser:{}",JsonUtils.toJson(appUser));
		if(null == appUser){
			model.addAttribute("msg", "未获取到用户信息，请联系管理员");
			return new ModelAndView("wechat/noPage", model.asMap());
		}
		
		model.addAttribute("webUrl", Constants.SERVER_ADDRESS);

		List<Map<String, Object>> reslutMap = visitorInFoManager.getVisitorOrderList(userId, appUser.getUserType());// 获取当前用户的访客记录列表

		model.addAttribute("reslutMap", reslutMap);
		model.addAttribute("status", appUser.getStatus());
		model.addAttribute("organizationId", appUser.getOrganizationId());
		// type 访客来源 1-企业员工分享出去,由访客填写 2-企业员工自己填写访客信息 3-访客自己发起,自己填写
		if ("0".equals(appUser.getUserType())) {
			// 白名单用户
			model.addAttribute("type", "2");
		} else {
			// 低权限用户/或者被禁用的白名单用户
			model.addAttribute("type", "3");
		}

		TbOrganization organization = propertyManager.getTbOrganizationById(appUser.getOrganizationId());
		if (organization == null) {
			log.info("========= 当前用户未绑定项目 ==========");
			model.addAttribute("msg", "当前用户未绑定项目");
			return new ModelAndView("wechat/noPage", model.asMap());
		}
		model.addAttribute("passType", organization.getPassType());// 当前项目配置的通行方式 1-face++  2-二维码
		// 获取该项目下的访客权限组,如果没有配置  则不能使用访客功能; 并且访客权限组下必须有可用的设备
		List<DevicePermGroup> groups = lingLingManager.getDevicePermGroupByOrgId(organization.getId(), 2);

		//2-令令开门 3-访客单 4-koala
		if (organization.getPassType().contains("2")) {
			// 如果该项目设置的是二维码通行且被访人设置了权限组(即有关联设备),则不需要face++相关账号与操作
			if (groups != null && groups.size() > 0) {
				DevicePermGroup      group   = groups.get(0);
				List<LingLingDevice> devices = lingLingManager.getDevicesByGroup(group.getId(), 1);
				if (devices == null || devices.size() == 0) {
					log.info("========= 访客权限组未配置可用设备 ==========");
					model.addAttribute("msg", "访客权限组未配置可用设备");
					return new ModelAndView("wechat/noPage", model.asMap());
				}
			} else {
				log.info("========= 未配置访客权限组 ==========");
				model.addAttribute("msg", "未配置访客权限组");
				return new ModelAndView("wechat/noPage", model.asMap());
			}
			return new ModelAndView("wechat/visitorlist", model.asMap());
		}
		if (organization.getPassType().contains("1")) {
			// 如果该项目设置的是face++ 通行方式,则需要加载对应企业的face++账号
			CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
			if (cookieStore != null) {
				return new ModelAndView("wechat/visitorlist", model.asMap());
			} else {
				log.info("========= 当前企业没有配置face++账号 ==========");
				return new ModelAndView("wechat/noPage", model.asMap());
			}
		}
		if (organization.getPassType().contains("3")) {
			return new ModelAndView("wechat/visitorlist", model.asMap());
		}		
		if (organization.getPassType().contains("4")) {
			return new ModelAndView("wechat/visitorlist", model.asMap());
		}
		if(StringUtils.isEmpty(organization.getPassType())){
			return new ModelAndView("wechat/noPage", model.asMap());
		}
		return new ModelAndView("wechat/noPage", model.asMap());
		//else {
		//	log.info("========= 当前项目通行权限不是二维码通行 ==========");
		//	return new ModelAndView("wechat/noPage", model.asMap());
		//}
	}

	@RequestMapping(value = "/visitorlist")
	public ModelAndView visitorlist(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model  = new ExtendedModelMap();
		String userId = request.getParameter("userId");
		String openId = request.getParameter("openId");
		log.info("VisitorUserInfoController visitorlist ==========>userId{},openId{}", userId, openId);
		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		model.addAttribute("userId", userId);
		model.addAttribute("status", appUser.getStatus());
		model.addAttribute("type", "2");
		List<Map<String, Object>> reslutMap = visitorInFoManager.getVisitorOrderList(userId, appUser.getUserType());
		model.addAttribute("reslutMap", reslutMap);
		model.addAttribute("openId", openId);

		TbOrganization organization = propertyManager.getTbOrganizationById(appUser.getOrganizationId());
		if (organization.getPassType().contains("1")) {
			// 如果该项目设置的是face++ 通行方式,则需要加载对应企业的face++账号
			CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
			if (cookieStore == null) {
				log.info("========= 当前企业没有配置face++账号 ==========");
				return new ModelAndView("wechat/noPage", model.asMap());
			}
		}
		return new ModelAndView("wechat/visitorlist", model.asMap());
	}

	/**
	 * 访客微信分享入口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addweiXinVisitor")
	public ModelAndView addweiXinVisitor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String code  = request.getParameter("code");
			String state = request.getParameter("state");
			if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(state)) {
				String     str[]      = state.split(",");
				WxPublicno wxPublicno = publicNoManager.getByDevelopId(str[2]);
				if (wxPublicno == null) {
					log.info("找不到微信配置！state=" + state);
					return null;
				}
				String openId = getUserOpenId(wxPublicno, code, "2");
				if (StringUtils.isBlank(openId)) {
					return null;
				}
				model.addAttribute("openId", str[0]);
				String visitorIdentification = str[1];
				model.addAttribute("visitorIdentification", visitorIdentification);
				VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfo(openId, visitorIdentification);
				
				if(StringUtils.isNotEmpty(str[3])){
					model.addAttribute("passType", str[3].replaceAll("-", ","));
				}else{
					model.addAttribute("passType", str[3]);// 当前项目访客/员工通行方式
				}
			
				if (visitorInfo != null) {
					model.addAttribute("visitorOrderId", visitorInfo.getVisitorOrderId());
					model.addAttribute("type", "1");
					return new ModelAndView("redirect:getVisitorInfoList", model.asMap());
				}

				String orgId = str[4];
				model.addAttribute("orgId", orgId);
				model.addAttribute("type", "1");
				model.addAttribute("visitorOpenId", openId);
				model.addAttribute("developId", wxPublicno.getDevelopId());
				model.addAttribute("imageServer", Constants.IMAGE_SERVER);
				return new ModelAndView("redirect:addweiXinVisitorForm", model.asMap());
			}
		} catch (Exception e) {
			log.error("addweiXinVisitor 异常:=" + e.getMessage());
		}
		return null;
	}

	/**
	 * 访客微信路口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addweiXinVisitorForm")
	public ModelAndView addweiXinVisitorForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model                 = new ExtendedModelMap();
		String type                  = request.getParameter("type");
		String visitorOpenId         = request.getParameter("visitorOpenId");
		String developId             = request.getParameter("developId");
		String imageServer           = request.getParameter("imageServer");
		String visitorIdentification = request.getParameter("visitorIdentification");
		String openId                = request.getParameter("openId");
		String passType              = request.getParameter("passType");
		String orgId                 = request.getParameter("orgId");
		model.addAttribute("orgId", orgId);
		model.addAttribute("passType", passType);
		model.addAttribute("type", type);
		model.addAttribute("visitorIdentification", visitorIdentification);
		model.addAttribute("visitorOpenId", visitorOpenId);
		model.addAttribute("developId", developId);
		model.addAttribute("imageServer", imageServer);
		model.addAttribute("openId", openId);
		model.addAttribute("webUrl", Constants.SERVER_ADDRESS);
		return new ModelAndView("wechat/visitorform", model.asMap());
	}

	/**
	 * 跳转到预约 信息提交的页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addVisitor")
	public ModelAndView addVisitor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String openId = request.getParameter("openId");
		Model  model  = new ExtendedModelMap();
		if(StringUtils.isEmpty(openId)){
			return null;
		}
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (wxUser == null) {
			return null;
		}
		AppUser appUser = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
		if (appUser == null) {
			appUser = appUserManager.get(wxUser.getUserId());
			if (appUser == null) return null;
		} else if (appUser.getVirtualArchId() != null) {
			VirtualArchitecture virtualArchitecture = propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId());
			if (virtualArchitecture != null) {
				model.addAttribute("companyName", virtualArchitecture.getName());
			}
		}

//		WxPublicno wxPublicno = publicNoManager.getByDevelopId(wxUser.getDevelopId());
//		if (wxPublicno == null) {
//			return null;
//		}
		model.addAttribute("openId", openId);
		model.addAttribute("orgId", wxUser.getOrganizationId());
		model.addAttribute("developId", wxUser.getDevelopId());
		model.addAttribute("visitorIdentification", UUID.randomUUID().toString());
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());

		model.addAttribute("visitedCompType", 1);
		model.addAttribute("visitedMobileType", 1);
		model.addAttribute("visitCompType", 1);
		model.addAttribute("visitNameType", 1);
		model.addAttribute("orderAffirm", 0);
		if(null != wxUser && null != wxUser.getOrganizationId()){
			LingLingCurrentset lingLingCurrentset= lingLingCurrentsetManager.getByOrgId(wxUser.getOrganizationId());
			if(null != lingLingCurrentset){
				model.addAttribute("visitedCompType", lingLingCurrentset.getVisitedCompType() == null ? 1 : lingLingCurrentset.getVisitedCompType());
				model.addAttribute("visitedMobileType", lingLingCurrentset.getVisitedMobileType() == null ? 1 : lingLingCurrentset.getVisitedMobileType());
				model.addAttribute("visitCompType", lingLingCurrentset.getVisitCompType() == null ? 1 : lingLingCurrentset.getVisitCompType());
				model.addAttribute("visitNameType", lingLingCurrentset.getVisitNameType() == null ? 1 : lingLingCurrentset.getVisitNameType());
				model.addAttribute("orderAffirm", lingLingCurrentset.getOrderAffirm() == null ? 0 : lingLingCurrentset.getOrderAffirm());
			}
		}
		if ("0".equals(appUser.getUserType())) {// 白名单用户
			model.addAttribute("type", "2");
		} else if ("-1".equals(appUser.getUserType()) || "2".equals(appUser.getUserType())) {// 低权限访客用户或者被禁用的人
			model.addAttribute("type", "3");
		}
		model.addAttribute("userName", appUser.getUserName());
		model.addAttribute("webUrl", Constants.SERVER_ADDRESS);
		return new ModelAndView("wechat/visitorform", model.asMap());
	}


	@RequestMapping(value = "getAddVisitorInfo")
	@ResponseBody
	public AppResultDto getAddVisitorInfo(HttpServletRequest request, HttpServletResponse response) {
		String openId = request.getParameter("openId");

		Map<String,Object> model = new HashMap<>();
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (wxUser == null) {
			return null;
		}
		AppUser appUser = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
		if (appUser == null) {
			appUser = appUserManager.get(wxUser.getUserId());
			if (appUser == null) return null;
		} else if (appUser.getVirtualArchId() != null) {
			VirtualArchitecture virtualArchitecture = propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId());
			if (virtualArchitecture != null) {
				model.put("companyName", virtualArchitecture.getName());
			}
		}

//		WxPublicno wxPublicno = publicNoManager.getByDevelopId(wxUser.getDevelopId());
//		if (wxPublicno == null) {
//			return null;
//		}
		model.put("openId", openId);
		model.put("orgId", wxUser.getOrganizationId());
		model.put("developId", wxUser.getDevelopId());
		model.put("visitorIdentification", UUID.randomUUID().toString());
		model.put("imageServer", FileUploadUtils.getVisitPrefix());

		model.put("visitedCompType", 1);
		model.put("visitedMobileType", 1);
		model.put("visitCompType", 1);
		model.put("visitNameType", 1);
		model.put("orderAffirm", 0);
		if(null != wxUser && null != wxUser.getOrganizationId()){
			LingLingCurrentset lingLingCurrentset= lingLingCurrentsetManager.getByOrgId(wxUser.getOrganizationId());
			if(null != lingLingCurrentset){
				model.put("visitedCompType", lingLingCurrentset.getVisitedCompType() == null ? 1 : lingLingCurrentset.getVisitedCompType());
				model.put("visitedMobileType", lingLingCurrentset.getVisitedMobileType() == null ? 1 : lingLingCurrentset.getVisitedMobileType());
				model.put("visitCompType", lingLingCurrentset.getVisitCompType() == null ? 1 : lingLingCurrentset.getVisitCompType());
				model.put("visitNameType", lingLingCurrentset.getVisitNameType() == null ? 1 : lingLingCurrentset.getVisitNameType());
				model.put("orderAffirm", lingLingCurrentset.getOrderAffirm() == null ? 0 : lingLingCurrentset.getOrderAffirm());
			}
		}
		if ("0".equals(appUser.getUserType())) {// 白名单用户
			model.put("type", "2");
		} else if ("-1".equals(appUser.getUserType()) || "2".equals(appUser.getUserType())) {// 低权限访客用户或者被禁用的人
			model.put("type", "3");
		}
		model.put("userName", appUser.getUserName());
		model.put("webUrl", Constants.SERVER_ADDRESS);
		return AppResultUtil.createSuccesDto(model);
	}

	/**
	 * 保存用户信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveVisitorUserInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String saveVisitorUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {


		Map<String, Object> resultMap = visitorInFoService.saveVisitorUserInfo(request, response);
		return net.sf.json.JSONObject.fromObject(resultMap).toString();
	}

	/**
	 * 根据公司名称获取公司
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/virList")
	@ResponseBody
	public AppResultDto virList(HttpServletRequest request) {
		String orgId   = request.getParameter("orgId");
		String virName = request.getParameter("virName");

		if (org.apache.commons.lang3.StringUtils.isAnyBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目id为空");
		}

		List<Map<String, String>> list = virtualArchManager.getVirByOrgIdAndVirName(null, null, Integer.parseInt(orgId), virName);
		return AppResultUtil.createSuccesDto(list);
	}

	/**
	 * 校验该公司下是否有该用户
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/checkEmployee")
	@ResponseBody
	public AppResultDto checkEmployee(HttpServletRequest request) {
		String employeeCompanyId = request.getParameter("employeeCompanyId");
		String employeePhone     = request.getParameter("employeePhone");

		String flag = checkEmployee(employeeCompanyId, employeePhone);
		if (Constants.FAIL_FLAG.equals(flag)) {
			return AppResultUtil.createErrorDto("100", "到访公司或访问人手机号有误");
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 校验该公司下是否有该用户
	 *
	 * @param employeeCompanyId
	 * @param employeePhone
	 * @return
	 */
	private String checkEmployee(String employeeCompanyId, String employeePhone) {
		if (org.apache.commons.lang3.StringUtils.isAnyBlank(employeeCompanyId, employeePhone)) {
			return Constants.FAIL_FLAG;
		}
		// 根据企业id和员工电话查询白名单用户
		AppUser appUser = appUserManager.getWhiteUserByMobileAndVirt(Integer.parseInt(employeeCompanyId), employeePhone);
		if (appUser != null) {
			return Constants.SUCCESS_FLAG;
		}
		return Constants.FAIL_FLAG;
	}


	/**
	 * 查询访客信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getVisitorInfo")
	public ModelAndView getVisitorInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		long beginTime=System.currentTimeMillis();
		log.info("VisitorUserInfoController-getVisitorInfo-beginTime:{}",beginTime);
		Model model = new ExtendedModelMap();
		try {
			String params = request.getQueryString();
			//解密
			String ids = new String(AesUtils.decrypt(AesUtils.parseHexStr2Byte(params), "palmnest"));

			log.info("VisitorUserInfoController getVisitorInfo =====> 接收参数:{},解密后参数:{}", params, ids);

			String      id[]        = ids.split("=");
			VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfo(id[1]);
			model.addAttribute("visitorInfo", visitorInfo);
			model.addAttribute("dateweek", DateUtils.getTime(visitorInfo.getVisitorEndTime(), "MM月dd日"));
			VisitorOrder visitorOrder = visitorInFoManager.getVisitorOrder(visitorInfo.getVisitorOrderId());

			Integer orgId = null;
			if (visitorOrder.getVisitorUserId() != null) {
				AppUser appUser = appUserManager.get(visitorOrder.getVisitorUserId());
				if(null != appUser.getWxUserId()){
					WxUser  wxUser  = scWxuserManager.getScWxuserByWxUserId(appUser.getWxUserId());
					model.addAttribute("openId", wxUser == null ? "" : wxUser.getOpenId());
				}
				orgId = appUser.getOrganizationId();
			} else {
				// 访客机访客处理
				Long                             userId = visitorOrder.getUserId();
				if(null==userId){
					orgId=visitorOrder.getVisitorToOrgId();
				}else{
					List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(userId);
					orgId = list.get(0).getOrgId();
				}
				
			}

			// 获取项目信息
			TbOrganization organization = propertyManager.getTbOrganizationById(orgId);
			model.addAttribute("organization", organization);
			model.addAttribute("passType", organization.getPassType());
			String content = "二维码当日有效";
			if (null != organization) {
				DevicePermGroup group = lingLingManager.getByUserInfo(orgId);
				if (null == group || (StringUtils.isBlank(group.getBeginTime()) && StringUtils.isBlank(group.getEndTime()))) {
					content = "二维码当日有效，截止当日时间23:59:59";
				} else {
					if (StringUtils.isBlank(group.getBeginTime()) && StringUtils.isNotBlank(group.getEndTime())) {
						content = "二维码当日有效，截止当日时间" + group.getEndTime();
					} else if (StringUtils.isNotBlank(group.getBeginTime()) && StringUtils.isBlank(group.getEndTime())) {
						content = "二维码当日有效，开始时间当日时间" + group.getBeginTime();
					} else if (StringUtils.isNotBlank(group.getBeginTime()) && StringUtils.isNotBlank(group.getEndTime())) {
						content = "二维码当日" + group.getBeginTime() + "~" + group.getEndTime() + "有效";
					}
				}
			}
			model.addAttribute("content", content);
			
			String visitorCode="";
			if (organization != null && organization.getPassType() != null && organization.getPassType().contains("2")) {
				// 如果该项目设置的二维码通行,则需要生成对应的访客二维码
				if (org.apache.commons.lang3.StringUtils.isNotBlank(visitorOrder.getVisitorQrCode())) {
					// 如果该访客已有二维码,则不需要生成
					model.addAttribute("visitorQrCode", visitorOrder.getVisitorQrCode());
					visitorCode=visitorOrder.getVisitorQrCode();
					log.info("VisitorUserInfoController-getVisitorInfo-有二维码");
				} else {
					String visitorQrCode = visitorInFoManager.createVisitorQrCode(organization.getId(), visitorOrder);
					model.addAttribute("visitorQrCode", visitorQrCode);
					visitorCode=visitorQrCode;
					log.info("VisitorUserInfoController-getVisitorInfo-新增二维码");
				}

			}
			
			if (organization != null && organization.getPassType() != null && organization.getPassType().contains("3")) {//访客单
				model.addAttribute("qrCode", visitorOrder.getVisitorOrderId());//visitorOrderId
			}
			if (organization != null && organization.getPassType() != null && organization.getPassType().contains("2")&&org.apache.commons.lang3.StringUtils.isBlank(visitorCode)) {//令令开门
				return null;
			}
			long endTime=System.currentTimeMillis();
			log.info("VisitorUserInfoController-getVisitorInfo-endTime:{}",endTime);
			return new ModelAndView("wechat/visitorinfo", model.asMap());
		} catch (Exception e) {
			log.error("redirectFacePlusInfo:" + e.getMessage());
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 编辑访客信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateVisitorInfo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String updateVisitorInfo(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {
		Map<String, Object> resultMap = null;
		try {
			String      visitorId             = request.getParameter("visitorId");
			String      imageUrl              = request.getParameter("imageUrl");
			String      updateImageUrl        = request.getParameter("updateImageUrl");
			String      updateShowImageUrl    = request.getParameter("updateShowImageUrl");
			String      updateImageFacePlusId = request.getParameter("updateImageFacePlusId");
			VisitorInfo visitorInfo           = visitorInFoManager.getVisitorInfo(visitorId);
			if (visitorInfo.getVisitorAccount() != 0) {
				resultMap = visitorInFoManager.updateVisitorInfo(visitorId, imageUrl, updateImageUrl, updateShowImageUrl, updateImageFacePlusId);
				resultMap.put("visitorId", visitorId);
				net.sf.json.JSONObject.fromObject(resultMap).toString();
			} else {
				resultMap = new HashMap<String, Object>();
				resultMap.put("flag", false);
				resultMap.put("desc", "修改的次数已上限！");
			}
		} catch (Exception e) {
			resultMap.put("flag", true);
			resultMap.put("desc", "编辑失败，请稍候在试！");
			log.error("redirectFacePlusInfo:" + e.getMessage());
		}
		return net.sf.json.JSONObject.fromObject(resultMap).toString();
	}

	/**
	 * 查询访客信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getResultVisitorInfo")
	public ModelAndView getResultVisitorInfo(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			Map<String, String> map         = (Map<String, String>) redirectAttributes.getFlashAttributes();
			String              visitorId   = map.get("visitorId");
			VisitorInfo         visitorInfo = visitorInFoManager.getVisitorInfo(visitorId);
			model.addAttribute("visitorInfo", visitorInfo);
			VisitorOrder visitorOrder = visitorInFoManager.getVisitorOrder(visitorInfo.getVisitorOrderId());
			if(null != visitorOrder.getVisitorUserId()){
				AppUser      appUser      = appUserManager.get(visitorOrder.getVisitorUserId());
				if(null != appUser){
					WxUser       wxUser       = scWxuserManager.getScWxuserByUserId(appUser.getId());
					model.addAttribute("openId", wxUser.getOpenId());
				}
			}
			model.addAttribute("dateweek", DateUtils.getTime(visitorInfo.getVisitorEndTime(), "MM月dd日"));

			return new ModelAndView("wechat/visitorinfo", model.asMap());
		} catch (Exception e) {
			log.error("redirectFacePlusInfo:" + e.getMessage());
		}
		return null;
	}

	/*@RequestMapping(value = "/validateImage", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String validateImage(HttpServletRequest request) throws IOException, ParseException, JSONException {
		String     imageUrl     = request.getParameter("imageUrl");
		String     openId       = request.getParameter("openId");
		JSONObject jsonObject   = new JSONObject();
		String     relativePath = "";
		try {
			relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
			if (StringUtils.isNotBlank(relativePath) && StringUtils.isNotBlank(openId)) {
				WxUser              wxUser      = scWxuserManager.getScWxuserByOpenId(openId);
				AppUser             appUser     = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
				CookieStore         cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
				Map<String, Object> map         = FacePlusClient.photos(Constants.IMAGE_ROOT + relativePath, cookieStore);
				if (map == null) {
					FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
					jsonObject.put("desc", "没有检测到人脸！");
					jsonObject.put("flag", false);
				} else {
					jsonObject.put("imageUrl", relativePath);
					jsonObject.put("url", map.get("url") + "");
					jsonObject.put("id", map.get("id"));
					jsonObject.put("flag", true);
				}
			} else if (StringUtils.isNotBlank(relativePath) && StringUtils.isBlank(openId)) {
				CookieStore         cookieStore = FacePlusClient.authLogin(Constants.FACE_PLUS_USER, Constants.FACE_PLUS_PASSWORD);
				Map<String, Object> map         = FacePlusClient.photos(Constants.IMAGE_ROOT + relativePath, cookieStore);
				if (map == null) {
					FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
					jsonObject.put("desc", "没有检测到人脸！");
					jsonObject.put("flag", false);
				} else {
					jsonObject.put("imageUrl", relativePath);
					jsonObject.put("url", map.get("url") + "");
					jsonObject.put("id", map.get("id"));
					jsonObject.put("flag", true);
				}
			} else {
				jsonObject.put("flag", false);
				jsonObject.put("desc", "没有检测到图片！");
			}
		} catch (Exception e) {
			FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT + relativePath);
			log.error("检测图片接口错误:" + e.getMessage());
			jsonObject.put("flag", false);
			jsonObject.put("desc", "网络超时！");
		}
		return jsonObject.toString();
	}*/

	/**
	 * 查詢訪客預約單列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getVisitorInfoList")
	public ModelAndView getVisitorInfoList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String visitorOrderId = request.getParameter("visitorOrderId");
			String type           = request.getParameter("type");
			String passType       = request.getParameter("passType");

			Map<String, Object> map = visitorInFoManager.getVisitorInfoList(visitorOrderId);
			model.addAttribute("passType", passType);
			model.addAttribute("result", map);
			model.addAttribute("type", type);
			model.addAttribute("qrCode", visitorOrderId);
			List<VisitorPassRecordVo> passList = new ArrayList<>();
			if(null != map && map.containsKey("passList") && null != map.get("passList")){
				passList = (List<VisitorPassRecordVo>)map.get("passList");
			}
			model.addAttribute("passList", passList);

			if(null != map && map.containsKey("orgId")){
				model.addAttribute("orgId", map.get("orgId"));
			}

			return new ModelAndView("wechat/visitordetails", model.asMap());
		} catch (Exception e) {
			log.error("redirectFacePlusInfo:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 审核访客申请
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateVisitorOrder", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String updateVisitorOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String     userId     = "";
		JSONObject jsonObject = new JSONObject();
		try {
			String vistorId           = request.getParameter("visitorId");
			String visitorOrderStatus = request.getParameter("visitorOrderStatus");
			userId = visitorInFoManager.updateVisitorOrder(Integer.parseInt(vistorId), visitorOrderStatus);
			if (userId == null) {
				jsonObject.put("flag", false);
				jsonObject.put("desc", "审核失败！");
			} else {
				VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfo(vistorId);
				String      auStr       = "审核：通过";
				if ("1".equals(visitorOrderStatus)) {
					jsonObject.put("desc", visitorInfo.getVisitorName() + "预约审核已通过！");
				}
				if ("2".equals(visitorOrderStatus)) {
					jsonObject.put("desc", visitorInfo.getVisitorName() + "预约审核已拒绝！");
					auStr = "审核：不通过";
				}

				String userMobile = "";
				if (null != visitorInfo.getVisitorOrderId()) {
					VisitorOrder visitorOrder = visitorInFoManager.getVisitorOrder(visitorInfo.getVisitorOrderId());
					if (null != visitorOrder && null != visitorOrder.getVisitorUserId()) {
						AppUser appUser = appUserManager.get(visitorOrder.getVisitorUserId());
						if (null != appUser && org.apache.commons.lang3.StringUtils.isNotEmpty(appUser.getUserMobile())) {
							userMobile = appUser.getUserMobile();
						}
					}

				}

				//User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
				String nodeStr = visitorInfo.getNodeStr();
				visitorInfo.setNodeStr(nodeStr + ";" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm") + "  " + userMobile + " " + auStr);
				visitorInFoManager.save(visitorInfo);


				jsonObject.put("flag", true);
				jsonObject.put("userId", userId);
			}
		} catch (Exception e) {
			log.error("redirectFacePlusInfo:" + e.getMessage());
			jsonObject.put("flag", false);
			jsonObject.put("desc", "审核失败！");
		}
		return jsonObject.toJSONString();
	}

	/**
	 * 异步注入分享接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/fenxiang", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String fenxiang(HttpServletRequest request, HttpServletResponse response) {
		try {
			String              developId  = request.getParameter("developId");
			String              url        = request.getParameter("url");
//			String              jsapi_tike = Constants.CacheMap.get("jsapi_" + developId);
			String              jsapi_tike = baseRedisService.get(Constants.JSAPI+developId);
			WxPublicno          wxPublicno = publicNoManager.getByDevelopId(developId);
			Map<String, String> wxMap      = WxConfigUtil.sign(jsapi_tike, url);
			wxMap.put("appid", wxPublicno.getAppId());
			return net.sf.json.JSONObject.fromObject(wxMap).toString();
		} catch (Exception e) {
			log.error("分享信息错误:" + e.getMessage());
		}
		return null;

	}

	/**
	 * 临时访客扫二维码入口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/temporayVisitorForm")
	public ModelAndView temporayVisitorForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String              code      = request.getParameter("code");
			String              state     = request.getParameter("state");
			Map<String, String> retMap    = weChatApiManager.oauth2(code, state);
			Map<String, Object> map       = JSON.parseObject(retMap.get("jsonStr"), Map.class);
			String              openId    = (String) map.get("openid");
			String              developId = (String) retMap.get("developid");
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			return new ModelAndView("redirect:saveTemporayVisitorForm", model.asMap());
		} catch (Exception e) {
			log.error("temporayVisitorForm:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 临时访客跳转到信息提交页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveTemporayVisitorForm")
	public ModelAndView saveTemporayVisitorForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String      openId      = request.getParameter("openId");
			VisitorInfo visitorInfo = visitorInFoManager.getVisItorInfo(openId);
			if (visitorInfo != null) {
				Date now = new Date();
				if (now.getTime() < visitorInfo.getVisitorEndTime().getTime() && "1".equals(visitorInfo.getVisitorStatus())) {
					model.addAttribute("visitorOrderId", visitorInfo.getVisitorOrderId());
					model.addAttribute("type", "1");
					return new ModelAndView("redirect:getVisitorInfoList", model.asMap());
				} else {
					model.addAttribute("visitorInfo", visitorInfo);
				}
			}
			String developId = request.getParameter("request");
			model.addAttribute("openId", openId);
			model.addAttribute("developId", developId);
			return new ModelAndView("/wechat/temporayvisitorform", model.asMap());
		} catch (Exception e) {
			log.error("saveTemporayVisitorForm:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 保存临时用户信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitTemporayVisitor", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String submitTemporayVisitor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> resultMap = null;
		try {
			String  userPhone = request.getParameter("userPhone");//被访人手机号码
			AppUser appUser   = appUserManager.getAppUsersByPhone(userPhone);
			if (appUser == null) {
				resultMap = new HashMap<String, Object>();
				resultMap.put("flag", false);
				resultMap.put("desc", "您输入的被访人号码不存在！");
				return net.sf.json.JSONObject.fromObject(resultMap).toString();
			}
			CookieStore cookieStore = Constants.FaceMap.get("vis_cookiestore_" + appUser.getVirtualArchId());
			if (cookieStore == null) {
				resultMap = new HashMap<String, Object>();
				resultMap.put("flag", false);
				resultMap.put("desc", "您输入的被访人号码没有该权限！");
				return net.sf.json.JSONObject.fromObject(resultMap).toString();
			}
			String              visitorName      = request.getParameter("visitorName");//访客姓名
			String              visitorPhone     = request.getParameter("visitorPhone");//访客电话
			String              imageUrl         = request.getParameter("imageUrl");//服务器图片地址
			Map<String, Object> map              = FacePlusClient.photos(Constants.IMAGE_ROOT + imageUrl, cookieStore,null);
			String              imageFacePlusId  = map.get("id") + "";//人脸识别唯一标识
			String              imageFacePlusUrl = map.get("url") + "";//访客人脸识别图片路径
			String              visitorOpenId    = request.getParameter("visitorOpenId");//访客唯一openId
			VisitorInfo         visitorInfo      = new VisitorInfo();//访客对象
			visitorInfo.setVisitorName(visitorName);
			visitorInfo.setVisitorOpenId(visitorOpenId);
			visitorInfo.setImagePlusId(Integer.parseInt(imageFacePlusId));
			visitorInfo.setVisitorPhone(visitorPhone);
			visitorInfo.setShowimageUrl(imageFacePlusUrl);
			visitorInfo.setImageUrL(imageUrl);
			visitorInfo.setUserPhone(userPhone);
			visitorInfo.setVisitorStartTime(new Date());
			visitorInfo.setVisitorCreateTime(new Date());
			Date afterDate = new Date(visitorInfo.getVisitorStartTime().getTime() + 600000);
			visitorInfo.setVisitorEndTime(afterDate);
			resultMap = visitorInFoManager.saveSubmitTemporayVisitor(visitorInfo);
		} catch (Exception e) {
			resultMap = new HashMap<String, Object>();
			resultMap.put("flag", false);
			resultMap.put("desc", "提交失败，请稍候在试！");
			log.error("redirectFacePlusInfo:" + e.getMessage());
		}
		return net.sf.json.JSONObject.fromObject(resultMap).toString();
	}

	/**
	 * 访客预约分享页面点击访问
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/visitorUserAuthor")
	public ModelAndView visitorUserAuthor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			String code  = request.getParameter("code");
			String appid = request.getParameter("appid");
			String state = request.getParameter("state");
			if (StringUtils.isNotBlank(code)) {
				model.addAttribute("code", code);
				model.addAttribute("state", state);
				return new ModelAndView("redirect:addweiXinVisitor", model.asMap());
			} else {
				String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + URLEncoder.encode(Constants.SERVER_ADDRESS + "/wechat/visitor/addweiXinVisitor", "utf-8")
						+ "&response_type=code&scope=snsapi_base&state=" + state + "#wechat_redirect";
				return new ModelAndView("redirect:" + url);
			}
		} catch (Exception e) {
			log.error("visitorUserAuthor:" + e.getMessage());
		}
		return null;
	}

	public String getUserOpenId(WxPublicno wxPublicno, String code, String type) {
		String openId = null;
		try {
			String url = Constants.OAUTHOR_OPENID_URL.replace("val1", wxPublicno.getAppId())
					.replace("val2", wxPublicno.getAppSecret()).replace("val3", code);
			String jsonStr = HttpKit.get(url);
			if (jsonStr != null && jsonStr.trim().length() > 0) {
				JSONObject obj = JSONObject.parseObject(jsonStr);
				if (obj != null && obj.get("errcode") == null) {
					openId = obj.getString("openid");
					if (StringUtils.isNotBlank(openId)) {
						log.info("openId=" + openId);
						if ("1".equals(type)) {
							WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
							if (wxUser == null || wxUser.getUserId() == null) {
								return null;
							}
							AppUser appUser = appUserManager.get(wxUser.getUserId());
							if (appUser == null || !"1".equals(appUser.getStatus())) {
								return null;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("获取openId异常！");
		}
		return openId;
	}

	/**
	 * 根据访客人获取访客人所对应的权限组是否设置了可用时段限制
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getIsUesLimit")
	@ResponseBody
	public AppResultDto getIsUesLimit(Integer orgId) {
		DevicePermGroup       group = lingLingManager.getByUserInfo(orgId);
		DevicePermGroupOutDto dto   = new DevicePermGroupOutDto();
		if (group != null) {
			dto.setOrgId(group.getOrgId());
			dto.setIsHoliday(group.getIsHoliday());
			dto.setIsUseLimit(group.getIsUseLimit());
			dto.setIsWeek(group.getIsWeek());
			dto.setIsWorkday(group.getIsWorkday());
			dto.setBeginTime(group.getBeginTime());
			dto.setEndTime(group.getEndTime());
		}
		return AppResultUtil.createSuccesDto(dto);
	}

	/**
	 * 根据项目获取访客允许的日期
	 *
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "/getDateInfoByOrgId")
	@ResponseBody
	public AppResultDto getDateInfoByOrgId(Integer orgId) {
		if(null == orgId){
			return AppResultUtil.createSuccesDto(null);
		}
		return AppResultUtil.createSuccesDto(lingLingManager.getDateInfoByOrgId(orgId));
	}
}
