package com.palmnest.service.estateserve.impl;

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

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.OrgKoalaInfoVo;
import com.palmnest.application.dto.input.LingLingScanVisitorInfo;
import com.palmnest.application.dto.output.lingling.VisitorPassRecordVo;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.estateserve.VisitorInFoDao;
import com.palmnest.dao.lingling.LingLingCurrentsetDao;
import com.palmnest.dao.lingling.LingLingDao;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.model.AppUserOrgnizationRelation;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.lingling.DevicePermGroup;
import com.palmnest.model.lingling.LingLingCurrentset;
import com.palmnest.model.lingling.LingLingDeveloper;
import com.palmnest.model.lingling.LingLingVisitorInfo;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.FaceClientManager;
import com.palmnest.service.estateserve.MemberManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.estateserve.VisitorInFoManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.service.ws.FacePlusClient;
import com.palmnest.service.ws.VistorCodeClient;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 访客模块 业务实现层
 * 
 * @author HJY
 *
 */
@Service("visitorInFoManager")
public class VisitorInFoManagerImpl extends GenericManagerImpl<Object, Integer>
		implements VisitorInFoManager {

	
	public static final String CLIENTNO  = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");
	private Logger LOG = LoggerFactory.getLogger(VisitorInFoManagerImpl.class);
	
	@Autowired
	private VisitorInFoDao visitorInFoDao;

	@Autowired
	private WeChatApiManager weChatApiManager;

	@Autowired
	private ScWxuserDao scWxuserDao;

	@Autowired
	private AppUserDao appUserDao;

	@Autowired
	private PropertyDao propertyDao;
	
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	
	@Autowired
    private LingLingDao lingLingDao; 
	
	@Autowired
	private AppUserManager appUserManager;
	@Autowired
	private LingLingManager lingLingManager;

	@Autowired
	private UserManager userManager;	
	
	@Autowired
	private FaceClientManager faceClientManager;
	
	@Autowired
	private MemberManager memberManager;

	@Autowired
	private LingLingCurrentsetDao lingLingCurrentsetDao;


	@Autowired
	public void setvisitorInFoDao(VisitorInFoDao visitorInFoDao) {
		this.visitorInFoDao = visitorInFoDao;
		this.dao = visitorInFoDao;
	}

	public static final String IMAGE_URL= PropertiesKit.readPropertiesValue("image_server","wechat.properties");

	@Override
	public Map<String, Object> saveVisitorInfo(
			List<VisitorInfo> visitorInfoList, String openId) throws Exception {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer count = null;
		Date startTime = null;
		boolean flag = false;
		String desc = "预约成功！";
		try {
			// 根据openId查询该用户是否已关注公众号
			WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
			if (wxUser == null) {
				return resultMap;
			}

			AppUser appUser = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
			if (appUser == null) {
				return resultMap;
			}
			resultMap.put("userId", appUser.getId());

			VirtualArchitecture virtualArchitecture = propertyDao.getVirtualArchitectureById(appUser.getVirtualArchId());
			if (virtualArchitecture == null) {
				return resultMap;
			}
			if (visitorInfoList != null && visitorInfoList.size() > 0) {
				for (int i = 0; i < visitorInfoList.size(); i++) {
					startTime = visitorInfoList.get(i).getVisitorStartTime();
					String dateTime = DateUtils
							.getTime(startTime, "yyyy-MM-dd");
					if (count == null) {
						count = visitorInFoDao.getVisitorCodeMaxCount(dateTime);
					}
					String str = VistorCodeClient.getPassword(startTime, count,
							wxUser.getOrganizationId());
					if (StringUtils.isNotBlank(str)) {
						// 把生成的大豪密码保存到访客信息中
						visitorInfoList.get(i).setVisitorPassword(str);
					} else {
						flag = true;
						desc = "生成密码出错!";
					}
					VisitorInfo visitorInfo = saveFacePlus(visitorInfoList.get(i),appUser.getOrganizationId(),"2");
					if (visitorInfo == null) {
						flag = true;
						desc = "调用接口出错!";
						break;
					}
					count++;
					updatCode(startTime, count);
					visitorInfoList.set(i, visitorInfo);
				}

				Integer orderId = null;
				if (!flag) {
					VisitorOrder visitorOrder = new VisitorOrder();
					visitorOrder.setVisitorOrderStartTime(visitorInfoList.get(0).getVisitorStartTime());
					visitorOrder.setVisitorOrderEndTime(visitorInfoList.get(0).getVisitorEndTime());
					visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_USER);
					visitorOrder.setVisitorOrderCreateTime(new Date());
					visitorOrder.setVisitorOrderCount(0);
					visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_OK);
					visitorOrder.setVisitorOrderIsEnabled("1");
					visitorOrder.setVisitorUserId(appUser.getId());
					visitorInFoDao.saveObj(visitorOrder);
					orderId = visitorOrder.getVisitorOrderId();
					for (VisitorInfo visitorInfo : visitorInfoList) {
						String imageUrl = visitorInfo.getImageUrL();
						visitorInfo.setVisitorCreateTime(new Date());
						visitorInfo.setVisitorIsEnabled("1");
						visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
						visitorInfo.setVisitorAccount(0);
						visitorInfo.setVisitorStatus("2");
						if (StringUtils.isBlank(imageUrl)) {
							visitorInfo.setVisitorAccount(1);
							visitorInfo.setImageUrL(null);
						}
						visitorInFoDao.saveObj(visitorInfo);
						if (StringUtils.isNotBlank(imageUrl)) {
							UserImageInfo userImageInfo = new UserImageInfo();
							userImageInfo.setUserId(visitorInfo.getVisitorId());
							userImageInfo.setImageFacePlusId(visitorInfo.getImagePlusId());
							userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
							userImageInfo.setImageUrl(imageUrl);
							userImageInfo.setImageType("2");
							visitorInFoDao.saveObj(userImageInfo);
						}
					}
				} else {
					desc = "预约失败！";
					resultMap.put("flag", false);
					resultMap.put("desc", desc);
					return resultMap;
				}

				if (!flag) {
					// 发送短信给访客
					for (VisitorInfo visitorInfo : visitorInfoList) {
						smsMessage(wxUser.getOrganizationId(),visitorInfo.getImageUrL(),
								appUser.getUserName(),
								DateUtils.getTime(
										visitorInfo.getVisitorStartTime(),
										"yyyy年MM月dd日"),
								visitorInfo.getVisitorId(),
								visitorInfo.getVisitorPhone(),
								visitorInfo.getVisitorType(),
								virtualArchitecture.getName());
					}
					desc = "预约成功！";
					if(null != orderId){
						resultMap.put("visitorOrderId",orderId);
					}
					resultMap.put("flag", true);
					resultMap.put("desc", desc);
					return resultMap;
				}
			}
		} catch (Exception e) {
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
		}
		return resultMap;
	}
	
	private String setVisitorLinglingIdAndPerm(String deviceIds,Integer orgId){
		int methedType=lingLingManager.getMethedType(orgId+"");
		LingLingDeveloper developer=lingLingManager.findByOrgId(orgId);
		String lingLingId ="";
		if(1==methedType){
			lingLingId = LingLingUtil.getLingLingId();
		}else{
			lingLingId=LingLingUtil.getRandomValue(8);
			Map param=new HashMap();
			param.put("cardUids", lingLingId.split(","));
			param.put("deviceIds", deviceIds.split(","));
			param.put("endTime", 1);
			param.put("cardType", 2);
			param.put("cardFlag", 1);
			String res=LingLingUtil.addOpenDoorCard(param,developer.getUrl(),developer.getSignature(),developer.getToken(),developer.getOpenToken(),developer.getStrKey(),2);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(res)){
				LOG.error("VisitorInFoManagerImpl setVisitorLinglingIdAndPerm error============>" + res);
			}
		}
		return lingLingId;
	}

	
	@Override
	public Map<String, Object> savePCVisitorInfo(
			List<VisitorInfo> visitorInfoList, int virtualArchId,HttpServletRequest request) throws Exception {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer count = null;
		Date startTime = null;
		boolean flag = false;
		String desc = "预约成功！";
		Integer orderId = null;
		try {
			// 根据openId查询该用户是否已关注公众号
			//WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
			//if (wxUser == null) {
			//	return resultMap;
			//}

			//AppUser appUser = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
			//if (appUser == null) {
			//	return resultMap;
			//}
			//resultMap.put("userId", appUser.getId());
			
			
			String idenNumber=request.getParameter("idenNumber");		
			String censusAddr=request.getParameter("censusAddr");		
			String race=request.getParameter("race");		
			String police=request.getParameter("police");	

			VirtualArchitecture virtualArchitecture=null;
			if(virtualArchId!=0){//非必录
				virtualArchitecture = propertyDao.getVirtualArchitectureById(virtualArchId);
				if (virtualArchitecture == null) {
					return resultMap;
				}
			}

			if (visitorInfoList != null && visitorInfoList.size() > 0) {

				//不需要saveFacePlus
				/*for (int i = 0; i < visitorInfoList.size(); i++) {
					startTime = visitorInfoList.get(i).getVisitorStartTime();
					String dateTime = DateUtils
							.getTime(startTime, "yyyy-MM-dd");
					if (count == null) {
						count = visitorInFoDao.getVisitorCodeMaxCount(dateTime);
					}
					String str = VistorCodeClient.getPassword(startTime, count,
							wxUser.getOrganizationId());
					if (StringUtils.isNotBlank(str)) {
						// 把生成的大豪密码保存到访客信息中
						visitorInfoList.get(i).setVisitorPassword(str);
					} else {
						flag = true;
						desc = "生成密码出错!";
					}
					VisitorInfo visitorInfo = saveFacePlus(visitorInfoList.get(i),virtualArchitecture.getId(),"2");
					if (visitorInfo == null) {
						flag = true;
						desc = "调用接口出错!";
						break;
					}
					count++;
					updatCode(startTime, count);
					visitorInfoList.set(i, visitorInfo);
				}*/

				VisitorOrder visitorOrder = new VisitorOrder();
				visitorOrder.setVisitorOrderStartTime(visitorInfoList.get(0).getVisitorStartTime());
				visitorOrder.setVisitorOrderEndTime(visitorInfoList.get(0).getVisitorEndTime());
				visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_PC);
				visitorOrder.setVisitorOrderCreateTime(new Date());
				visitorOrder.setVisitorOrderCount(0);
				visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_OK);
				visitorOrder.setVisitorOrderIsEnabled("1");
				visitorOrder.setVisitorToOrgId(virtualArchitecture.getOrganizationId());
				//visitorOrder.setVisitorUserId(appUser.getId()); //TODO
				visitorInFoDao.saveObj(visitorOrder);
				orderId = visitorOrder.getVisitorOrderId();
				for (VisitorInfo visitorInfo : visitorInfoList) {
					String imageUrl = visitorInfo.getImageUrL();
					visitorInfo.setVisitorCreateTime(new Date());
					visitorInfo.setVisitorIsEnabled("1");
					visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
					visitorInfo.setVisitorAccount(0);
					visitorInfo.setVisitorStatus("2");
					visitorInfo.setVisitorCompanyName(virtualArchitecture.getName());//以后台为准
					if (StringUtils.isBlank(imageUrl)) {
						visitorInfo.setVisitorAccount(1);
						visitorInfo.setImageUrL(null);
					}
					visitorInFoDao.saveObj(visitorInfo);
					if (StringUtils.isNotBlank(imageUrl)) {
						UserImageInfo userImageInfo = new UserImageInfo();
						userImageInfo.setUserId(visitorInfo.getVisitorId());
						userImageInfo.setImageFacePlusId(visitorInfo.getImagePlusId());
						userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
						userImageInfo.setImageUrl(imageUrl);
						userImageInfo.setImageType("5");
						visitorInFoDao.saveObj(userImageInfo);
					}
					
					
					 // 4.保存/修改(完善)访客信息
		            LingLingVisitorInfo visitor = null;
		            if (StringUtils.isNotBlank(visitorInfo.getVisitorPhone())) {
		                visitor = lingLingDao.getVisitorInfoByTelephone(visitorInfo.getVisitorPhone());
		            }
		            if (Objects.isNull(visitor) && StringUtils.isNotBlank(idenNumber)) {
		                visitor = lingLingDao.getVisitorInfoByIdenNumber(idenNumber);
		            }

		            if (Objects.isNull(visitor)){
		                visitor = new LingLingVisitorInfo();
		            }

		            //if (StringUtils.isNotBlank(inputDTO.getBirthday())){
		                // 访客生日格式解析模板未确定,先注释,需要的时候放开
//		                visitor.setBirthday(DateHelper.parseToDate(inputDTO.getBirthday(), DateHelper.FORMATS[0]));
		            //}
		            visitor.setCardId("B");
		            visitor.setCensusAddr(censusAddr);//户籍地址
		            visitor.setCreateTime(new Date());
		            //visitor.setHeadImgName();
		            //visitor.setIdenActiveFrom(inputDTO.getActiveFrom());
		            //visitor.setIdenActiveTo(inputDTO.getActiveTo());
		            visitor.setIdenNumber(idenNumber);
		            visitor.setPolice(police);//签发机关
		            visitor.setRace(race);//民族
		            //visitor.setSnapshotImgName(inputDTO.getSnapshotImgName());
		            visitor.setTelephone(visitorInfo.getVisitorPhone());
		            visitor.setVisitorName(visitorInfo.getVisitorName());

		            if (visitor.getId() == null) {
		                //visitorInFoManager.save(visitor);
		            	visitorInFoDao.save(visitor);
		            } else {
		                //visitorInFoManager.updateModel(visitor);
		            	visitorInFoDao.updateObj(visitor);
		            }
					
				}


			}
		} catch (Exception e) {
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
		}
		
		
		desc = "预约成功！";
		resultMap.put("flag", true);
		resultMap.put("desc", desc);
		if(null != orderId){
			resultMap.put("visitorOrderId", orderId);
		}
		return resultMap;
	}
	
	public void updatCode(Date startTime, Integer count) {
		try {
			String dateTime = DateUtils.getTime(startTime, "yyyy-MM-dd");
			Map<String, Object> VisitorCode = visitorInFoDao
					.getVisitorCode(dateTime);
			if (VisitorCode != null) {
				VisitorCode vCode = new VisitorCode();
				vCode.setCodeCreateTime(startTime);
				vCode.setCodeNumber(count);
				vCode.setCodeId((Integer) VisitorCode.get("codeId"));
				visitorInFoDao.updateObj(vCode);
			} else {
				VisitorCode tVistorCode = new VisitorCode();
				tVistorCode.setCodeCreateTime(startTime);
				tVistorCode.setCodeNumber(count);
				visitorInFoDao.save(tVistorCode);
			}

		} catch (Exception e) {
			LOG.error("【生成大豪密码异常 信息如下:】" + e.getMessage());
		}
	}

	// 处理 业务接口
	public VisitorInfo saveFacePlus(VisitorInfo visitorInfo,Integer projectId,String type) {
		boolean flag = false;
		List<Integer> list = new ArrayList<Integer>();
		List<Integer> lists = new ArrayList<Integer>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			//CookieStore cookieStore=Constants.FaceMap.get("vis_cookiestore_"+projectId);
			//CookieStore cookieStore = Constants.FaceMap.get("org_cookiestore_" + projectId);
			/*if(cookieStore == null){
				cookieStore = FacePlusClient.authLogin(Constants.KOALOA_PLUS_USER, Constants.KOALOA_PLUS_PASSWORD);
			}*/
			
			
			CookieStore cookieStore = null;
			TbOrganization organization = propertyDao.getTbOrganizationById(projectId);
			OrgKoalaInfoVo orgKoalaInfoVo = memberManager.getOrgKoalaInfoVoByOrgId(projectId);
			if(organization.getPassType().contains("4")){
				cookieStore = faceClientManager.getCookieStoreByOrgId(projectId);			
			}			
			
			String imageUrl = visitorInfo.getImageUrL();
			
			if (StringUtils.isNotBlank(imageUrl) && cookieStore!=null) {
				
				if (visitorInfo.getImagePlusId() == null) {
					paramMap.put("photo", Constants.IMAGE_ROOT + imageUrl);
					Integer id = FacePlusClient.photo(paramMap,cookieStore,orgKoalaInfoVo);
					if (id != null) {
						visitorInfo.setImagePlusId(id);
						list.add(id);
					} else {
						flag = true;
					}
				} else {
					list.add(visitorInfo.getImagePlusId());
				}
				paramMap = new HashMap<String, Object>();
				if("1".equals(visitorInfo.getVisitorType())){
				paramMap.put("subjectType", 2);
				}else{
					paramMap.put("subjectType", 1);
				}
				
				paramMap.put("come_from", visitorInfo.getVisitorCompanyName());
				paramMap.put("interviewee", visitorInfo.getVisitorName());
				paramMap.put("phone", visitorInfo.getVisitorPhone());
				
				if(StringUtils.isNotEmpty(visitorInfo.getVisitorPhone())){
					paramMap.put("extra_id", visitorInfo.getVisitorPhone());
				}				
				
				paramMap.put("obj", visitorInfo);
				paramMap.put("photo_ids", list);
				
				if(StringUtils.isNotEmpty(visitorInfo.getVisitorPhone())){
					
					//一个人两个访客信息 识别时可能找到过期的访客信息
					//以手机号为唯一标示 删除历史访客信息
					Integer subjectId =FacePlusClient.getSubjectList(visitorInfo.getVisitorPhone(), paramMap, orgKoalaInfoVo);
					if(null!=subjectId){
						FacePlusClient.deleteSubject(subjectId, cookieStore);
					}
				}
				
				Integer userId = FacePlusClient.subject(paramMap,cookieStore);
				if (userId != null) {
					visitorInfo.setVisitorSubjectId(userId);
				} else {
					flag = true;
				}
				lists.add(visitorInfo.getVisitorSubjectId());
			}
			int ids[] = new int[lists.size()];
			for (int i = 0; i < lists.size(); i++) {
				if (ids[i] == 0) {
					ids[i] = lists.get(i);
				}
			}
			// 指定访问哪个们禁
			if (lists.size() > 0) {
				paramMap = new HashMap<String, Object>();
				paramMap.put("doorId", "1");
				paramMap.put("ids", ids);
				paramMap.put("allowVisitor", true);
				FacePlusClient.screen(paramMap,cookieStore);
			}
		} catch (Exception e) {
			flag = true;
		}
		if (flag) {
			return null;
		}
		return visitorInfo;
	}

	public void smsMessage(Integer orgId,String imageUrl, String userName,
			String vistroStartTime, Integer visitorId, String phone,
			String vistorType, String companyName) throws KeyManagementException,
			NoSuchAlgorithmException, NoSuchProviderException, IOException {
		if(StringUtils.isEmpty(phone) || null == orgId){
			return;
		}
		String content = "";
		String serverUrl = getPassUrl(visitorId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("format", "json");
		map.put("url", serverUrl);
		LOG.info("VisitorInFoManagerImpl smsMessage    发送短信开始=======> 参数visitorId:{},url:{}",visitorId,serverUrl);
		if(StringUtils.isNotEmpty(companyName)){
			content += companyName + "，";
		}
		if(StringUtils.isNotEmpty(userName)){
			content += userName;
		}
		content += "邀请您来访，您的来访时间是"
				+ vistroStartTime + "，";
		content += "点击获取邀请函\n" + serverUrl;
		smsAuthCodeManager.smsSendByOrgId(orgId+"", content,phone,null, CodeConstants.SMS_VISITOR_TYPE);

		LOG.info("VisitorInFoManagerImpl smsMessage    发送短信结束，发送模板消息开始=======> ");
		//根据电话号码、项目找访客用户
		Integer wxUserId = null;
		String developId = "";
		AppUser appUser = appUserDao.getAppUsersByPhoneAndOrg(phone,orgId);
		if(null != appUser && null != appUser.getWxUserId()){
			wxUserId = appUser.getWxUserId();
			WxUser wxUser = scWxuserDao.getScWxuserByWxUserId(appUser.getWxUserId());
			if(null != wxUser){
				developId = wxUser.getDevelopId();
			}
		}
		if(null == wxUserId || StringUtils.isEmpty(developId)){
			return;
		}
		StringBuilder sb = new StringBuilder();
		if(StringUtils.isNotEmpty(companyName)){
			sb.append(companyName).append(",");
		}
		if(StringUtils.isNotEmpty(userName)){
			sb.append(userName);
		}
		sb.append("邀请您来访，您的来访时间是").append(vistroStartTime) .append(",").append("点击获取邀请函。").append("<a href=\"" + serverUrl + "\">点击获取邀请函</a>");
		content = sb.toString();
		if(StringUtils.isEmpty(content)){
			return;
		}
		LOG.info("VisitorInFoManagerImpl smsMessage    发送模板消息=======> developId:{},wxUserId:{}，content:{}",developId,wxUserId,content);
		weChatApiManager.sendServiceWithOpenId(developId,wxUserId,content);
		LOG.info("VisitorInFoManagerImpl smsMessage    发送模板消息结束=======> ");
	}

	/**
	 * 通行的地址
	 * @param visitorId
	 * @return
	 */
	public String getPassUrl(Integer visitorId){
		byte[] encryptResult =AesUtils.encrypt("id="+visitorId,"palmnest");
		String encryptStr = AesUtils.parseByte2HexStr(encryptResult);
		String serverUrl = Constants.SERVER_ADDRESS
				+ "/wechat/visitor/getVisitorInfo?"+encryptStr;
		LOG.info("VisitorInFoManagerImpl getPassUrl=======> 参数visitorId:{},encryptStr:{},url:{}",visitorId,encryptStr,serverUrl);
		return serverUrl;
	}
	
	public void smsNoMessage(Integer orgId,String userName,
			String vistroStartTime, String phone, String companyName) throws KeyManagementException,
			NoSuchAlgorithmException, NoSuchProviderException, IOException {
		String content = "您"+vistroStartTime+"申请来访"+companyName+"已被"+userName+"拒绝,请联系该处理人！";
		smsAuthCodeManager.smsSendByOrgId(orgId+"", content,phone,null,CodeConstants.SMS_VISITOR_TYPE);
	}

	@Override
	public Map<String, Object> saveWeiXinVisitorInfo(
			List<VisitorInfo> visitorInfoList, String openId) throws Exception {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean flag = false;
		String desc = "";
		try {
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
			// 根据openId查询该用户是否已注册成公司员工
			WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
			if (wxUser == null) {
				return resultMap;
			}
			AppUser appUser = appUserDao.getAppUserByWxUserAndOrg(wxUser.getId(),wxUser.getOrganizationId());
			if (appUser == null) {
				return resultMap;
			}
			// 获取用户项目信息
			TbOrganization organization = propertyDao.getTbOrganizationById(wxUser.getOrganizationId());

			resultMap.put("userId", appUser.getId());
			VirtualArchitecture virtualArchitecture = propertyDao
					.getVirtualArchitectureById(appUser.getVirtualArchId());
			if (virtualArchitecture == null) {
				return resultMap;
			}
			//CookieStore cookieStore=Constants.FaceMap.get("vis_cookiestore_"+appUser.getVirtualArchId());
			//CookieStore cookieStore = Constants.FaceMap.get("org_cookiestore_" + organization.getId());
			CookieStore cookieStore =faceClientManager.getCookieStoreByOrgId(organization.getId());
			OrgKoalaInfoVo orgKoalaInfoVo = memberManager.getOrgKoalaInfoVoByOrgId(organization.getId());
			/*if(cookieStore == null){
				cookieStore = FacePlusClient.authLogin(Constants.KOALOA_PLUS_USER, Constants.KOALOA_PLUS_PASSWORD);
			}*/
			if (visitorInfoList != null && visitorInfoList.size() > 0) {
				for (int i = 0; i < visitorInfoList.size(); i++) {
					VisitorInfo visitorInfo = visitorInfoList.get(i);
					if (StringUtils.isNotBlank(visitorInfo.getImageUrL()) && cookieStore!=null) {
						String imageUrl = Constants.IMAGE_ROOT
								+ visitorInfo.getImageUrL();
						Map<String, Object> paramMap = new HashMap<String, Object>();
						LOG.info("imageUrl="+imageUrl);
						paramMap.put("photo", imageUrl);
						Integer id = FacePlusClient.photo(paramMap,cookieStore,orgKoalaInfoVo);
						if (id != null) {
							visitorInfo.setImagePlusId(id);
							visitorInfoList.set(i, visitorInfo);
						} else {
							flag = true;
							break;
						}
					} 
				}
				if (!flag) {
					for (VisitorInfo visitorInfo : visitorInfoList) {
						VisitorOrder visitorOrder = new VisitorOrder();
						visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_VISTOR);
						visitorOrder.setVisitorOrderCreateTime(new Date());
						visitorOrder.setVisitorOrderCount(0);
						visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_ZEROR);
						visitorOrder.setVisitorOrderIsEnabled("1");
						visitorOrder.setVisitorUserId(appUser.getId());
						visitorOrder.setVisitorOrderStartTime(visitorInfo.getVisitorStartTime());
						visitorOrder.setVisitorOrderEndTime(visitorInfo.getVisitorEndTime());
						visitorInFoDao.saveObj(visitorOrder);
						resultMap.put("visitorOrderId",visitorOrder.getVisitorOrderId());
						visitorInfo.setVisitorCreateTime(new Date());
						visitorInfo.setVisitorIsEnabled("1");
						visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
						visitorInfo.setVisitorAccount(0);
						visitorInfo.setVisitorStatus("1");
						if (StringUtils.isNotBlank(visitorInfo.getImageUrL())) {
							visitorInFoDao.saveObj(visitorInfo);
							UserImageInfo userImageInfo = new UserImageInfo();
							userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
							userImageInfo.setUserId(visitorInfo.getVisitorId());
							userImageInfo.setImageUrl(visitorInfo.getImageUrL());
							userImageInfo.setImageType("2");
							userImageInfo.setImageFacePlusId(visitorInfo.getImagePlusId());
							visitorInFoDao.save(userImageInfo);
						} else {
							visitorInfo.setImageUrL(null);
							visitorInFoDao.saveObj(visitorInfo);
						}
						//-------------- 模板消息推送 ---------------------
//						Map<String, String> paramMap = new HashMap<String, String>();
//						List<Map<String,Object>> templateList=replayContentDao.getWxTemplate("2", appUser.getOrganizationId());
//						if(templateList!=null && templateList.size()>0){
//							String templateId=(String)templateList.get(0).get("templateId");
//							paramMap.put("templateId", templateId);
//						}
//						paramMap.put("openId", openId);
//						paramMap.put(
//								"url",
//								Constants.SERVER_ADDRESS
//										+ "/wechat/visitor/getVisitorInfoList?visitorOrderId="
//										+ visitorOrder.getVisitorOrderId()
//										+ "&type=2&passType="+organization.getPassType());
//						paramMap.put("title", "您有新的访客申请，请审批");
//						paramMap.put("orderNo",visitorOrder.getVisitorOrderId() + "");
//						paramMap.put("vistorName", visitorInfo.getVisitorName());
//						paramMap.put("address",visitorInfo.getVisitorCompanyName());
//						paramMap.put("remak", "来访申请");
//						paramMap.put("startTime",DateUtils.formatDate(visitorInfo.getVisitorStartTime(), ""));
//						paramMap.put("developId", wxUser.getDevelopId());
//						weChatApiManager.sendTemplateMsg01(paramMap);
						//-------------- 模板消息推送 ---------------------

						//-------------- 客服消息推送 ---------------------
						String url=Constants.SERVER_ADDRESS + "/wechat/visitor/getVisitorInfoList?visitorOrderId="
								+ visitorOrder.getVisitorOrderId() + "&type=2&passType="+organization.getPassType();
						String content="您有新的访客申请，请及时审批!访客姓名:"+visitorInfo.getVisitorName()+
								",到访时间:"+DateUtils.formatDate(visitorInfo.getVisitorStartTime(), "yyyy-MM-dd")+"," + "<a href='"+url+"'>查看详情</a>";
						weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
						//-------------- 客服消息推送 ---------------------
					}
					resultMap.put("flag", true);
					resultMap.put("desc", "预约成功！");
					return resultMap;
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		resultMap.put("flag", false);
		resultMap.put("desc", "预约失败！");
		return resultMap;
	}


	@Override
	public Map<String, Object> saveVisInfo(List<VisitorInfo> visitorInfoList, String openId,AppUser toUser,Integer orgId) throws Exception {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean flag = false;
		String desc = "";
		try {
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);

			WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
			if (wxUser == null  || null == wxUser.getOrganizationId()) {
				return resultMap;
			}
			// 访客的信息(非白名单用户)
			AppUser fromUser = appUserDao.getAppUserByWxUserAndOrg(wxUser.getId(),wxUser.getOrganizationId());
//			if (fromUser == null || toUser == null) {
//				return resultMap;
//			}

			if (fromUser == null) {
				return resultMap;
			}

			// 获取被访人项目信息
			TbOrganization organization = propertyDao.getTbOrganizationById(wxUser.getOrganizationId());
			resultMap.put("userId", fromUser.getId());
			// 获取被访人企业信息
			VirtualArchitecture virtualArchitecture = null;
			if(null != toUser){
				virtualArchitecture = propertyDao.getVirtualArchitectureById(toUser.getVirtualArchId());
				if (virtualArchitecture == null) {
					return resultMap;
				}
			}


			// 获取被访人face++企业账号信息
			CookieStore cookieStore = null;
			OrgKoalaInfoVo orgKoalaInfoVo = new OrgKoalaInfoVo();
			if (organization.getPassType().contains("4")){
				//cookieStore=Constants.FaceMap.get("vis_cookiestore_"+toUser.getVirtualArchId());
				 //cookieStore = Constants.FaceMap.get("org_cookiestore_" + organization.getId());
				/*if(cookieStore == null){
					cookieStore = FacePlusClient.authLogin(Constants.KOALOA_PLUS_USER, Constants.KOALOA_PLUS_PASSWORD);
				}*/
				
				cookieStore =faceClientManager.getCookieStoreByOrgId(organization.getId());
				orgKoalaInfoVo = memberManager.getOrgKoalaInfoVoByOrgId(organization.getId());
			}

			if (visitorInfoList != null && visitorInfoList.size() > 0) {
				// ---------- 处理face++人脸逻辑 ----------
				for (int i = 0; i < visitorInfoList.size(); i++) {
					
					VisitorInfo visitorInfo = visitorInfoList.get(i);
					if (StringUtils.isNotBlank(visitorInfo.getImageUrL()) && cookieStore!=null) {
						String imageUrl = Constants.IMAGE_ROOT + visitorInfo.getImageUrL();
						Map<String, Object> paramMap = new HashMap<String, Object>();
						LOG.info("imageUrl="+imageUrl);
						paramMap.put("photo", imageUrl);
						Integer id = FacePlusClient.photo(paramMap,cookieStore,orgKoalaInfoVo);
						if (id != null) {
							visitorInfo.setImagePlusId(id);
							visitorInfoList.set(i, visitorInfo);
						} else {
							flag = true;
							break;
						}
					}
				}
				// --------------------------------------

				if (!flag) {
					int isLingLingAudit = 0;
					if(null != organization && null != organization.getId()){
						LingLingCurrentset lingLingCurrentset = lingLingCurrentsetDao.getByOrgId(organization.getId());
						LOG.info("saveVisInfo-lingLingCurrentset:{}",JsonUtils.toJson(lingLingCurrentset));
						if(null != lingLingCurrentset && null != lingLingCurrentset.getIsLinglingAudit() && 1 == lingLingCurrentset.getIsLinglingAudit().intValue()){
							isLingLingAudit = 1;
						}
					}
					VisitorOrder visitorOrder = new VisitorOrder();
					visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_THREE);
					visitorOrder.setVisitorOrderCreateTime(new Date());
					visitorOrder.setVisitorOrderCount(0);

					if(1 == isLingLingAudit){
						visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_OK);
					}else{
						visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_ZEROR);
					}
					
					visitorOrder.setVisitorOrderIsEnabled("1");
					if(null != toUser){
						visitorOrder.setVisitorUserId(toUser.getId());
					}
					visitorOrder.setVisitorToOrgId(orgId);
					visitorOrder.setVisitorOrderStartTime(visitorInfoList.get(0).getVisitorStartTime());
					visitorOrder.setVisitorOrderEndTime(visitorInfoList.get(0).getVisitorEndTime());
					visitorOrder.setFromUserId(fromUser.getId());
					visitorInFoDao.saveObj(visitorOrder);
					resultMap.put("visitorOrderId",visitorOrder.getVisitorOrderId());

					for (VisitorInfo visitorInfo : visitorInfoList) {
						visitorInfo.setVisitorCreateTime(new Date());
						visitorInfo.setVisitorIsEnabled("1");
						visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
						visitorInfo.setVisitorAccount(0);
						visitorInfo.setVisitorStatus("1");
						if (StringUtils.isNotBlank(visitorInfo.getImageUrL())) {
							visitorInFoDao.saveObj(visitorInfo);
							UserImageInfo userImageInfo = new UserImageInfo();
							userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
							userImageInfo.setUserId(visitorInfo.getVisitorId());
							userImageInfo.setImageUrl(visitorInfo.getImageUrL());
							//userImageInfo.setImageType("3");
							userImageInfo.setImageType("2");//访问的都是2
							userImageInfo.setImageFacePlusId(visitorInfo.getImagePlusId());
							visitorInFoDao.save(userImageInfo);
						} else {
							visitorInfo.setImageUrL(null);
							visitorInFoDao.saveObj(visitorInfo);
						}
					}


					String virtName = "";
					if(null != virtualArchitecture){
						virtName = virtualArchitecture.getName();
					}

					if (1 == isLingLingAudit) {
						String userName = "";
						if(null != visitorOrder.getVisitorUserId()){
							AppUser appUser = appUserDao.get(visitorOrder.getVisitorUserId());
							if(null != appUser){
								userName = appUser.getUserName();
							}
						}
						// 发送短信给访客==========访客自己申请，推送的内容就是自己推送给自己
						for (VisitorInfo visitorInfo : visitorInfoList) {
							smsMessage(wxUser.getOrganizationId(),visitorInfo.getImageUrL(),userName,
									DateUtils.getTime(
											visitorInfo.getVisitorStartTime(),
											"yyyy年MM月dd日"),
									visitorInfo.getVisitorId(),
									visitorInfo.getVisitorPhone(),
									visitorInfo.getVisitorType(),
									virtName);

						}
					}else{
						// 不为空才推送模板消息
						if (toUser.getWxUserId() != null){
							WxUser wxUser1 = scWxuserDao.get(toUser.getWxUserId());
							if (wxUser1 != null && StringUtils.isNotBlank(wxUser1.getOpenId())){

								//-------------- 客服消息推送 ---------------------
								String url=Constants.SERVER_ADDRESS + "/wechat/visitor/getVisitorInfoList?visitorOrderId="
										+ visitorOrder.getVisitorOrderId() + "&type=2&passType="+organization.getPassType();
								String content="您有新的访客申请，请及时审批!访客姓名:"+visitorInfoList.get(0).getVisitorName()+
										",到访时间:"+DateUtils.formatDate(visitorInfoList.get(0).getVisitorStartTime(), "yyyy-MM-dd")+"," + "<a href='"+url+"'>查看详情</a>";
								weChatApiManager.sendServiceWithOpenId(wxUser1.getDevelopId(), wxUser1.getId(), content);
								//-------------- 客服消息推送 ---------------------
							}
						}
					}

					desc = "预约成功！";
					resultMap.put("flag", true);
					resultMap.put("desc", desc);
					return resultMap;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		resultMap.put("flag", false);
		resultMap.put("desc", "预约失败！");
		return resultMap;
	}



	@Override
	public VisitorInfo getVisitorInfo(String visitorId) {
		VisitorInfo visitorInfo = visitorInFoDao.getVisitorInfo(visitorId);
		if (visitorInfo != null) {
			Integer count = visitorInFoDao.getVistorInfoCount(visitorInfo
					.getVisitorOrderId() + "");
			if (count != null) {
				visitorInfo.setCount(count);
			}
			Map<String, Object> map = visitorInFoDao.getVistorInfo(visitorId);
			if (map.get("imageFaceUrl") != null) {
				String imageFaceUrl = map.get("imageFaceUrl").toString();
				visitorInfo.setImageUrL(imageFaceUrl);
			}
			visitorInfo
					.setWeek(DateUtils.getWeekOfDate(visitorInfo.getVisitorStartTime()));
			visitorInfo.setStartTime(DateUtils.getTime(
					visitorInfo.getVisitorStartTime(), "HH:mm"));
			visitorInfo.setEndTime(DateUtils.getTime(
					visitorInfo.getVisitorEndTime(), "HH:mm"));
			visitorInfo.setToDate(DateUtils.getTime(
					visitorInfo.getVisitorEndTime(), "yyyy-MM-dd"));
			VisitorOrder visitorOrder = visitorInFoDao
					.getVisitorOrder(visitorInfo.getVisitorOrderId());
			if (visitorOrder != null) {
				Integer userId = visitorOrder.getVisitorUserId();

				if (userId != null) {
					AppUser appUser = appUserDao.get(userId);
					TbOrganization tbOrganization=propertyDao.getTbOrganizationById(appUser.getOrganizationId());
					visitorInfo.setClientUserName(appUser.getUserName());
					visitorInfo.setClientPhone(appUser.getUserMobile());
					visitorInfo.setClientAddress(tbOrganization.getAddress());
				}
			}
		}
		return visitorInfo;
	}

	@Override
	public Map<String, Object> updateVisitorInfo(String visitorId,
			String imageUrl, String updatImageUrl,String updateShowImageUrl,String updateImageFacePlusId) {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean flag = false;
		VisitorInfo visitorInfo = null;
		try {
			visitorInfo = visitorInFoDao.getVisitorInfo(visitorId);
			if (visitorInfo == null) {
				flag = true;
			}
			VisitorOrder visitorOrder=visitorInFoDao.getVisitorOrder(visitorInfo.getVisitorOrderId());
			Integer orgId = null;
			if(null != visitorOrder.getVisitorUserId()){
				AppUser appUser=appUserDao.get(visitorOrder.getVisitorUserId());
				if(null != appUser && null != appUser.getOrganizationId()){
					orgId = appUser.getOrganizationId();
				}
			}else{
				orgId = visitorOrder.getVisitorToOrgId();
			}

			if (StringUtils.isNotBlank(updatImageUrl)) {
				visitorInfo.setImageUrL(updatImageUrl);
				visitorInfo.setShowimageUrl(updateShowImageUrl);
				visitorInfo.setImagePlusId(Integer.parseInt(updateImageFacePlusId));
				visitorInfo = saveFacePlus(visitorInfo,orgId,"2");
				if (visitorInfo == null) {
					flag = true;
				}
			}
			if (!flag) {
				visitorInfo
						.setVisitorAccount(visitorInfo.getVisitorAccount() - 1);
				if (StringUtils.isNotBlank(visitorInfo.getImageUrL())) {
					// 保存图片的实体类
					UserImageInfo userImageInfo = new UserImageInfo();
					userImageInfo.setImageUrl(updatImageUrl);
					userImageInfo.setUserId(visitorInfo.getVisitorId());
					userImageInfo.setImageType("2");
					userImageInfo.setImageFacePlusId(visitorInfo
							.getImagePlusId());
					userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
					visitorInFoDao.save(userImageInfo);
				}
				visitorInFoDao.updateObj(visitorInfo);
			} else {
				resultMap.put("flag", false);
				resultMap.put("desc", "编辑资料失败！");
				return resultMap;
			}
		} catch (Exception e) {
			resultMap.put("flag", false);
			resultMap.put("desc", "编辑资料失败！");
			return resultMap;
		}
		resultMap.put("flag", true);
		resultMap.put("desc", "编辑资料成功！");
		return resultMap;
	}
	
	@Override
	public Map<String, Object> scanUpdateVisitorInfo(LingLingScanVisitorInfo scanVisitorInfo,HttpServletRequest request) {
		// 业务返回结果
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean flag = false;
		VisitorInfo visitorInfo = null;
		try {
			visitorInfo = visitorInFoDao.getVisitorInfo(scanVisitorInfo.getVisitorId());
			if (visitorInfo == null) {
				flag = true;
			}
			
			visitorInFoDao.save(visitorInfo);
			visitorInfo.setLeaveTime(scanVisitorInfo.getLeaveTime());
			
			User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
			
			String nodeStr=visitorInfo.getNodeStr();
			if(org.apache.commons.lang3.StringUtils.isNotEmpty(nodeStr) && nodeStr.indexOf("打印访客单") ==-1){
				visitorInfo.setNodeStr(nodeStr+";"+DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm")+"  "+user.getFullName()+" 打印访客单");
			}
			
			
			 // 4.保存/修改(完善)访客信息
            LingLingVisitorInfo visitor = null;
            if (StringUtils.isNotBlank(visitorInfo.getVisitorPhone())) {
                visitor = lingLingDao.getVisitorInfoByTelephone(visitorInfo.getVisitorPhone());
            }
            if (Objects.isNull(visitor) && StringUtils.isNotBlank(scanVisitorInfo.getIdenNumber())) {
                visitor = lingLingDao.getVisitorInfoByIdenNumber(scanVisitorInfo.getIdenNumber());
            }

            if (Objects.isNull(visitor)){
                visitor = new LingLingVisitorInfo();
            }

            visitor.setCardId("B");
            visitor.setCensusAddr(scanVisitorInfo.getCensusAddr());//户籍地址
            visitor.setCreateTime(new Date());
            visitor.setIdenNumber(scanVisitorInfo.getIdenNumber());
            visitor.setPolice(scanVisitorInfo.getPolice());//签发机关
            visitor.setRace(scanVisitorInfo.getRace());//民族
            visitor.setTelephone(visitorInfo.getVisitorPhone());
            visitor.setVisitorName(visitorInfo.getVisitorName());

            if (visitor.getId() == null) {
                //visitorInFoManager.save(visitor);
            	visitorInFoDao.save(visitor);
            } else {
                //visitorInFoManager.updateModel(visitor);
            	visitorInFoDao.updateObj(visitor);
            }		
			
			
		} catch (Exception e) {
			resultMap.put("flag", false);
			resultMap.put("desc", "编辑资料失败！");
			return resultMap;
		}
		resultMap.put("flag", true);
		resultMap.put("desc", "编辑资料成功！");
		return resultMap;
	}

	@Override
	public Map<String, Object> getVisitorInfoList(String visitorOrderId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		VisitorOrder visitorOrder = visitorInFoDao.getVisitorOrder(Integer
				.parseInt(visitorOrderId));
		if (visitorOrder.getVisitorOrderStatus().equals("2")) {
			map.put("status", "到访");
		} else if (visitorOrder.getVisitorOrderStatus().equals("0")) {
			map.put("status", "未授权");
		} else {
			map.put("status", "未到访");
		}

		if(null != visitorOrder && null != visitorOrder.getVisitorOrderId() && StringUtils.isNotEmpty(visitorOrder.getVisitorQrCode())){
			List<VisitorPassRecordVo> passList = lingLingCurrentsetDao.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_QRCODE);
			if(CollectionUtils.isEmpty(passList) && StringUtils.isNotEmpty(visitorOrder.getLinglingId())){
				passList = lingLingCurrentsetDao.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_LINGLINGID);
			}
			map.put("passList",passList);
		}else if(null != visitorOrder  && null != visitorOrder.getVisitorOrderId() && StringUtils.isNotEmpty(visitorOrder.getLinglingId())){
			List<VisitorPassRecordVo> passList = lingLingCurrentsetDao.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_LINGLINGID);
			if(CollectionUtils.isEmpty(passList) && StringUtils.isNotEmpty(visitorOrder.getVisitorQrCode())){
				passList = lingLingCurrentsetDao.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_QRCODE);
			}
			map.put("passList",passList);
		}
		
		if(StringUtils.isEmpty(visitorOrder.getVisitorQrCode())){			
			
			Integer orgId = null;
			if (visitorOrder.getVisitorUserId() != null) {
				AppUser appUser = appUserManager.get(visitorOrder.getVisitorUserId());
				orgId = appUser.getOrganizationId();
			} else {
				// 访客机访客处理
				Long                             userId = visitorOrder.getUserId();
				if(null != userId){
					List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(userId);
					orgId = list.get(0).getOrgId();
				}
			}
			if(null == orgId){
				orgId = visitorOrder.getVisitorToOrgId();
			}
			if(null!=orgId){
				String visitorQrCode = createVisitorQrCode(orgId, visitorOrder);
				map.put("visitorQrCode", visitorQrCode);//令令二维码
				map.put("orgId", orgId);//令令二维码
			}			
		}else{
			map.put("visitorQrCode", visitorOrder.getVisitorQrCode());//令令二维码
		}
		
		
		
//		map.put("dateTime", DateUtils.formatDate(
//				visitorOrder.getVisitorOrderStartTime(), "yyyy年MM月dd日"));
//		map.put("week", DateUtils.getWeekOfDate(visitorOrder
//				.getVisitorOrderStartTime()));
		map.put("stareTime", DateUtils.formatDate(
				visitorOrder.getVisitorOrderStartTime(), "yyyy-MM-dd HH:mm"));
		map.put("endTime", DateUtils.formatDate(
				visitorOrder.getVisitorOrderEndTime(), "yyyy-MM-dd HH:mm"));
		map.put("visitorTime", DateUtils.formatDate(
				visitorOrder.getVisitorOrderEndTime(), "yyyy-MM-dd"));
		map.put("visitorOrderStatus", visitorOrder.getVisitorOrderStatus());
		List<VisitorInfo> resultList = visitorInFoDao
				.getVisitorInfoList(Integer.parseInt(visitorOrderId));
		if (resultList != null) {
			map.put("compayName", resultList.get(0).getVisitorCompanyName());
			map.put("count", resultList.size());
			map.put("visitorId", resultList.get(0).getVisitorId());
		}
		for (int i = 0; i < resultList.size(); i++) {
			if ("1".equals(resultList.get(i).getVisitorType())) {
				map.put("remak", resultList.get(i).getVisitorWelcoming());
			}
			UserImageInfo userImageInfo = visitorInFoDao
					.getUserImageInfo(resultList.get(i).getVisitorId());
			if (userImageInfo != null) {
				resultList.get(i).setImageUrL(userImageInfo.getImageFaceUrl());
			}
		}
		map.put("resultList", resultList);
		return map;
	}

	@Override
	public String updateVisitorOrder(Integer visitorId,
			String visitorOrderStatus) {

		Integer count = null;
		Date startTime = null;
		VisitorInfo visitorInfo = null;
		VisitorOrder visitorOrder = null;
		UserImageInfo userImageInfo = null;
		AppUser appUser = null;
		try {
			visitorInfo = visitorInFoDao.getVisitorInfo(visitorId + "");
			if (visitorInfo == null) {
				return null;
			}
			visitorOrder = visitorInFoDao.getVisitorOrder(visitorInfo.getVisitorOrderId());
			if (visitorOrder == null) {
				return null;
			}
			if(null != visitorOrder.getVisitorUserId()){
				appUser = appUserDao.get(visitorOrder.getVisitorUserId());
			}

			String userName = "";
			String virtName = "";
			Integer orgId = null;
			if(null != appUser){
				userName = appUser.getUserName();
				orgId = appUser.getOrganizationId();
				VirtualArchitecture virtualArchitecture = propertyDao
						.getVirtualArchitectureById(appUser.getVirtualArchId());
				if(null != virtualArchitecture){
					virtName = virtualArchitecture.getName();
				}
			}else{
				orgId = visitorOrder.getVisitorToOrgId();
			}


			visitorOrder.setVisitorOrderStatus(Integer.parseInt(visitorOrderStatus));

			if (Constants.VISITOR_ORDER_STATUS.equals(visitorOrderStatus)) {
				visitorInfo.setVisitorStatus(Constants.VISITOR_TWO_STATUS);
				startTime = visitorInfo.getVisitorStartTime();
				String dateTime = DateUtils.getTime(
						visitorInfo.getVisitorStartTime(), "yyyy-MM-dd");
				if (count == null) {
					count = visitorInFoDao.getVisitorCodeMaxCount(dateTime);
				}
				String str = VistorCodeClient.getPassword(startTime, count,
						orgId);
				if (StringUtils.isNotBlank(str)) {
					// 把生成的大豪密码保存到访客信息中
					visitorInfo.setVisitorPassword(str);
				} else {
					return null;
				}
				userImageInfo = visitorInFoDao.getUserImageInfo(visitorInfo.getVisitorId());//这里默认找的访客类型的头像Id
				if (userImageInfo != null) {
					visitorInfo.setImageUrL(userImageInfo.getImageUrl());
					visitorInfo.setImagePlusId(userImageInfo.getImageFacePlusId());
				}
				visitorInfo = saveFacePlus(visitorInfo,orgId,"2");
				if (visitorInfo == null) {
					return null;
				}
				updatCode(startTime, count);

			} else {
				// 不通过
				visitorInfo.setVisitorStatus(Constants.VISITOR_TREE_STATUS);
				visitorInfo.setVisitorIsEnabled("0");
				visitorOrder.setVisitorOrderIsEnabled("1");
			}
			visitorInFoDao.updateObj(visitorInfo);
			visitorInFoDao.updateObj(visitorOrder);
			if (Constants.VISITOR_ORDER_STATUS.equals(visitorOrderStatus)) {
				// 发送短信给访客
				smsMessage(orgId,visitorInfo.getImageUrL(),
						userName, DateUtils.getTime(
								visitorInfo.getVisitorStartTime(),
								"yyyy年MM月dd日"), visitorInfo.getVisitorId(),
						visitorInfo.getVisitorPhone(),
						visitorInfo.getVisitorType(),
						virtName);
			}else{
				smsNoMessage(orgId,userName,DateUtils.getTime(visitorInfo.getVisitorStartTime(),"yyyy年MM月dd日")
						,visitorInfo.getVisitorPhone(),virtName);
			}

		} catch (Exception e) {
			LOG.error("错误信息:" + e.getMessage());
			return null;
		}
		if(null != appUser){
			return appUser.getId()+"";
		}
		return "";
	}

	@Override
	public List<Map<String, Object>> getVisitorOrderList(String userId,String userType) {
		try {
			// 获得预约记录日期的集合
			List<Map<String, Object>> list = visitorInFoDao.getVisitorTime(userId,userType);

			if (list != null && list.size()>0) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, Object> map = list.get(i);
					String dateTime = map.get("dateTime") + "";
					if (dateTime.equals(DateUtils.formatDate(new Date(),
							"yyyy-MM-dd"))) {
						map.put("week", "今天");
					}
					String weekDay = DateUtils.getWeekOfDate(DateUtils
							.StrToDate(dateTime, "yyyy-MM-dd"));
					map.put("weekDay", weekDay);
					List<Map<String, Object>> orderList = visitorInFoDao.getVisitorList(dateTime, userId,userType);

					for (int j = 0; j < orderList.size(); j++) {
						Map<String, Object> orderMap = orderList.get(j);
						Integer visitorOrderId = (Integer) orderMap
								.get("visitorOrderId");
						List<VisitorInfo> resultList = visitorInFoDao
								.getVisitorInfoList(visitorOrderId);
						if (resultList != null) {
							orderMap.put("visitorInfo", resultList.get(0));
							orderMap.put("count", resultList.size());
							orderList.set(j, orderMap);
						}
					}
					if (orderList != null) {
						map.put("orderList", orderList);
						list.set(i, map);
					}
				}
				return list;
			}

		} catch (Exception e) {
			LOG.error("错误信息:" + e.getMessage());
			return null;
		}
		return null;
	}

	@Override
	public VisitorInfo getVisitorInfo(String visitorOpenId,
			String visitorIdentification) {
		return visitorInFoDao.getVisitorInfo(visitorOpenId, visitorIdentification);
	}

	@Override
	public AppResultDto exportVisitorOrder(Map<String, String> params,
			String orgIdS) {
		
		HSSFWorkbook wb = new HSSFWorkbook();
		List<Map<String,Object>> mapList=visitorInFoDao.expVisitorOrderInfoList(params,orgIdS);
		
		
		if (!CollectionUtils.isEmpty(mapList)) {
			for (Map<String, Object> map : mapList) {
				String type = (String) map.get("visitorOrderType");
				if ("4".equalsIgnoreCase(type)){
					
					
					Iterator it = map.keySet().iterator();
					while(it.hasNext()){
						String key = (String)it.next();
						if(Objects.isNull(map.get(key))){
							map.put(key, "");
						}
					}
					
					// 访客机用户记录某些字段需要重新塞值,不然查不到
					// 1.项目名称
					if (!Objects.isNull(map.get("visitorToOrgId"))){
						Integer orgId = (Integer) map.get("visitorToOrgId");
						TbOrganization organization = propertyDao.getTbOrganizationById(orgId);
						map.put("organizationName",organization.getName());
					}
   
					// 2.头像,从系统取,imageFaceUrl
					String headUrl = (String) map.get("userHeadUrl");
					if (StringUtils.isNotBlank(headUrl) && !"null".equalsIgnoreCase(headUrl)){
						// 获取日期格式
						String dateStr = DateHelper.formatDate((Date) map.get("visitorStartTime"), DateHelper.FORMATS[5]);
						map.put("imageFaceUrl",IMAGE_URL
								.concat(File.separator)
								.concat(LingLingUtil.SNAPIMG)
								.concat(File.separator)
								.concat(dateStr)
								.concat(File.separator)
								.concat(map.get("userHeadUrl").toString())
								.concat(".jpeg"));

					}

					// 3.到访公司
					map.put("virName",map.get("visitorToCompany"));

				}else{
					if (!Objects.isNull(map.get("visitorToOrgId"))){
						Integer orgId = (Integer) map.get("visitorToOrgId");
						TbOrganization organization = propertyDao.getTbOrganizationById(orgId);
						map.put("organizationName",organization.getName());
					}
				}
				if(null!=map&&map.containsKey("visitorOrderStatus")&&null!=map.get("visitorOrderStatus")){
					String visitorOrderStatus = map.get("visitorOrderStatus").toString();
					//2-令令开门;3-访客;4-考拉
					if("1".equals(visitorOrderStatus)){
						map.put("visitorOrderStatus", "待审核");
					}else if("3".equals(visitorOrderStatus)){
						map.put("visitorOrderStatus", "已授权");
					}else if("4".equals(visitorOrderStatus)){
						map.put("visitorOrderStatus", "未通过");
					}
				}
				
				map.put("visitorStartTime", DateHelper.formatDate((Date) map.get("visitorStartTime"), DateHelper.CURRENT_DATE));
				map.put("visitor", map.get("visitorName")+ " "+ map.get("visitorPhone") + " " +map.get("visitorCompanyName"));   
				map.put("passivePerson", map.get("userName")+ " "+ map.get("userMobile") + " " +map.get("virName"));   
				
				
			}
		}
			String path=setPath("upload/ExportVisitorOrder.xls");

			try {
				if(mapList!=null&&mapList.size()>0){
					String sheetName="通行记录";
					File file =new File( new ExcelUtils().getPath(path));
					String[] titles={"项目","访客(姓名、手机号、企业)","被访人（姓名、手机号、企业）","到访目的","状态","申请时间","访问时间"};
					String [] fieldNames={"organizationName","visitor","passivePerson","visitorReason","visitorOrderStatus","visitorCreateTime","visitorStartTime"};
					ExcelUtils.exportExcel(file,wb, sheetName, mapList, titles, fieldNames);         
				}
			} catch (Exception e) {
				LOG.error(e.getMessage());
				e.printStackTrace();
				return AppResultUtil.createErrorDto("100", "导出异常");
			}
			
			return AppResultUtil.createSuccesDto(path);
	}
		
		
		private String setPath(String fileName) {
			String classpath = getClass().getResource("/").getPath();
			LOG.info("begin exportExcel  classpath:" + classpath);
			if (StringUtils.isNotEmpty(classpath)) {
				LOG.info("begin exportExcel  CLIENTNO:" + CLIENTNO);
				if ("dev".equals(CLIENTNO)) {
					String str = classpath.substring(0, 1);
					if ("/".equals(str)) {
						classpath = classpath.replaceFirst("/", "");
					}
				}
			}
			LOG.info("path:" + classpath);
			String webappRoot = classpath.replaceAll("WEB-INF/classes", "");
			LOG.info("path:" + webappRoot);
			//"upload/OrderExcel.xls"
			String path = webappRoot + fileName;
			if (StringUtils.isNotEmpty(path)) {
				path = path.replace("//", "/");
			}

			LOG.info("path:" + path);
			return path;
		}
	
	
	@Override
	public Page getVisitorOrderInfoList(Map<String,String> params, String orgIdS, Integer pageNo) {

		Page infoList = visitorInFoDao.getVisitorOrderInfoList(params, orgIdS, pageNo);
		List<Map<String,Object>> items = infoList.getItems();
		List<Map<String,Object>> list =new ArrayList<Map<String,Object>>();
		for (Map<String,Object> map : items){
			if(null == map || !map.containsKey("visitorId") || null == map.get("visitorId")){
				continue;
			}
			String type = (String) map.get("visitorOrderType");
			if ("4".equalsIgnoreCase(type)){
				Iterator it = map.keySet().iterator();
				while(it.hasNext()){
					String key = (String)it.next();
					if(Objects.isNull(map.get(key))){
						map.put(key, "");
					}
				}
				
				// 访客机用户记录某些字段需要重新塞值,不然查不到
				// 1.项目名称
				if (!Objects.isNull(map.get("visitorToOrgId"))){
					Integer orgId = (Integer) map.get("visitorToOrgId");
					TbOrganization organization = propertyDao.getTbOrganizationById(orgId);
					map.put("organizationName",null == organization ? "" : organization.getName());
				}

				// 2.头像,从系统取,imageFaceUrl
				String headUrl = (String) map.get("userHeadUrl");
				if (StringUtils.isNotBlank(headUrl) && !"null".equalsIgnoreCase(headUrl)){
					// 获取日期格式
					if(map != null && map.containsKey("visitorStartTime") && null != map.get("visitorStartTime")){
						String dateStr = DateHelper.formatDate((Date) map.get("visitorStartTime"), DateHelper.FORMATS[5]);
						map.put("imageFaceUrl",IMAGE_URL
								.concat(File.separator)
								.concat(LingLingUtil.SNAPIMG)
								.concat(File.separator)
								.concat(dateStr)
								.concat(File.separator)
								.concat(map.get("userHeadUrl").toString())
								.concat(".jpeg"));
					}
					

				}

				// 3.到访公司
				map.put("virName",map.get("visitorToCompany"));

			}else{
				if (!Objects.isNull(map.get("visitorToOrgId"))){
					Integer orgId = (Integer) map.get("visitorToOrgId");
					TbOrganization organization = propertyDao.getTbOrganizationById(orgId);
					map.put("organizationName",null == organization ? "" : organization.getName());
				}
			}
			if(map != null && map.containsKey("visitorStartTime") && null != map.get("visitorStartTime")){
				map.put("visitorStartTime", DateHelper.formatDate((Date) map.get("visitorStartTime"), DateHelper.CURRENT_DATE));
			}
			
			list.add(map);
		}
		infoList.setItems(list);
		return infoList;
	}

	@Override
	public List<UserImageInfo> getUserImageInfo(Integer userId, String type) {
		return visitorInFoDao.getUserImageInfo(userId, type);
	}

	@Override
	public UserImageInfo getUserImageInfoById(Integer imageUrlId) {
		return visitorInFoDao.getUserImageInfoById(imageUrlId);
	}

	@Override
	public Map<String, Object> saveSubmitTemporayVisitor(VisitorInfo visitorInfo) {
		Map<String, Object> resultMap = new HashMap<String, Object>();//业务返回结果
		String desc = "";
		try{
			desc = "预约失败！";
			resultMap.put("flag", false);
			resultMap.put("desc", desc);
			AppUser appUser=appUserDao.getAppUsersByPhone(visitorInfo.getUserPhone());
			VirtualArchitecture virtualArchitecture = propertyDao.getVirtualArchitectureById(appUser.getVirtualArchId());
			resultMap.put("userId", appUser.getId());
			WxUser wxUser=scWxuserDao.getScWxuserByUserId(appUser.getId());
			VisitorOrder visitorOrder = new VisitorOrder();
			visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_VISTOR);
			visitorOrder.setVisitorOrderCreateTime(new Date());
			visitorOrder.setVisitorOrderCount(0);
			visitorOrder.setVisitorOrderStatus(Constants.VISITOR_ORDER_STATUS_ZEROR);
			visitorOrder.setVisitorOrderIsEnabled("1");
			visitorOrder.setVisitorUserId(appUser.getId());
			visitorOrder.setVisitorOrderStartTime(visitorInfo.getVisitorStartTime());
			visitorOrder.setVisitorOrderEndTime(visitorInfo.getVisitorEndTime());
			visitorInFoDao.saveObj(visitorOrder);
			resultMap.put("visitorOrderId",visitorOrder.getVisitorOrderId());
			visitorInfo.setVisitorCreateTime(new Date());
			visitorInfo.setVisitorIsEnabled("1");
			visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
			visitorInfo.setVisitorAccount(0);
			visitorInfo.setVisitorStatus("1");
			visitorInfo.setVisitorCompanyName(virtualArchitecture.getName());
			visitorInFoDao.saveObj(visitorInfo);
			UserImageInfo userImageInfo = new UserImageInfo();
			userImageInfo.setImageFaceUrl(visitorInfo.getShowimageUrl());
			userImageInfo.setUserId(visitorInfo.getVisitorId());
			userImageInfo.setImageUrl(visitorInfo.getImageUrL());
			userImageInfo.setImageType("2");
			userImageInfo.setImageFacePlusId(visitorInfo.getImagePlusId());
			visitorInFoDao.save(userImageInfo);

			// 获取用户项目信息
			TbOrganization organization = propertyDao.getTbOrganizationById(wxUser.getOrganizationId());

//			Map<String, String> paramMap = new HashMap<String, String>();
//			List<Map<String,Object>> templateList=replayContentDao.getWxTemplate("2",appUser.getOrganizationId());
//			if(templateList!=null){
//				String templateId=(String)templateList.get(0).get("templateId");
//				paramMap.put("templateId", templateId);
//			}
//			paramMap.put("openId",wxUser.getOpenId());
//			paramMap.put(
//					"url",
//					Constants.SERVER_ADDRESS
//							+ "/wechat/visitor/getVisitorInfoList?visitorOrderId="
//							+ visitorOrder.getVisitorOrderId()
//							+ "&type=2&passType="+organization.getPassType());
//			paramMap.put("title", "您有新的访客申请，请审批");
//			paramMap.put("orderNo",visitorOrder.getVisitorOrderId() + "");
//			paramMap.put("vistorName", visitorInfo.getVisitorName());
//			paramMap.put("address",visitorInfo.getVisitorCompanyName());
//			paramMap.put("remak", "来访申请");
//			paramMap.put("startTime",DateUtils.formatDate(visitorInfo.getVisitorStartTime(), ""));
//			paramMap.put("developId", wxUser.getDevelopId());
//			weChatApiManager.sendTemplateMsg01(paramMap);

			//-------------- 客服消息推送 ---------------------
			String url=Constants.SERVER_ADDRESS + "/wechat/visitor/getVisitorInfoList?visitorOrderId="
					+ visitorOrder.getVisitorOrderId() + "&type=2&passType="+organization.getPassType();
			String content="您有新的访客申请，请及时审批!访客姓名:"+visitorInfo.getVisitorName()+
					",到访时间:"+DateUtils.formatDate(visitorInfo.getVisitorStartTime(), "yyyy-MM-dd")+"," + "<a href='"+url+"'>查看详情</a>";
			weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
			//-------------- 客服消息推送 ---------------------

		resultMap.put("flag", true);
		resultMap.put("desc", "预约成功！");
		return resultMap;
		}catch(Exception e){
			e.printStackTrace();
			LOG.error("submitTemporayVisitor:"+e.getMessage());
		}
		resultMap.put("flag", false);
		resultMap.put("desc", "预约失败！");
		return resultMap;
	}

	@Override
	public VisitorInfo getVisItorInfo(String visitorOpenId) {
		return visitorInFoDao.getVisItorInfo(visitorOpenId);
	}

	@Override
	public FaceProjectInfo getFaceProjectInfo(Integer projectId, String type) {
		return visitorInFoDao.getFaceProjectInfo(projectId, type);
	}

	@Override
	public VisitorOrder getVisitorOrder(Integer visitorOrderId) {
		return visitorInFoDao.getVisitorOrder(visitorOrderId);
	}

	@Override
	public void deleteUserImageInfoByUserId(Integer userId, String type) {
		visitorInFoDao.deleteUserImageInfoByUserId(userId,type);
	}

	@Override
	public String createVisitorQrCode(Integer organizationId,VisitorOrder visitorOrder) {

		// 获取该项目下的访客权限组
		List<DevicePermGroup> groups = lingLingManager.getDevicePermGroupByOrgId(organizationId, 2);

//		List<LingLingDevice> devices = new ArrayList<LingLingDevice>();
//		// 获取该权限组所关联设备id
//		if (groups != null && groups.size()>0){
//			for (DevicePermGroup group : groups){
//				if (group.getDevices() != null && group.getDevices().size()>0){
//					devices.addAll(group.getDevices());
//				}
//			}
//		}
		Integer groupId=null;
		if(CollectionUtils.isEmpty(groups)){
			return "";
		}
		
		if(null == groups.get(0)){
			return "";
		}
		groupId=Integer.parseInt(groups.get(0).getId().toString());
		if(null == groupId){
			return "";
		}
		
		String  deviceIds = lingLingDao.getDeviceIdsByGroupId(groupId);
		LOG.info("createVisitorQrCode-deviceIds",JsonUtils.toJson( deviceIds));
		
		LingLingDeveloper developer=lingLingManager.findByOrgId(organizationId);
		if(null==developer){
			return "";
		}
		
		int methedType=lingLingManager.getMethedType(organizationId+"");
		// 获取令令id
		String lingLingId ="";
		if(1==methedType){
			lingLingId = LingLingUtil.getLingLingId();
		}else{
			lingLingId=LingLingUtil.getRandomValue(8);
			Map param=new HashMap();
			param.put("cardUids", lingLingId.split(","));
			param.put("deviceIds", deviceIds.split(","));
			param.put("endTime", 1);
			param.put("cardType", 2);
			param.put("cardFlag", 1);
			String res=LingLingUtil.addOpenDoorCard(param,developer.getUrl(),developer.getSignature(),developer.getToken(),developer.getOpenToken(),developer.getStrKey(),2);
			if(org.apache.commons.lang3.StringUtils.isNotBlank(res)){
				LOG.error("VisitorInFoManagerImpl createVisitorQrCode error============>" + res);
				return "";
			}
		}
		if (org.apache.commons.lang3.StringUtils.isBlank(lingLingId)){
			return "";
		}
		
		String url="";
		Map<String,Object> map = new HashMap<String, Object>();
		if(1==methedType){
			// 获取设备生成的密匙
			String sdkkeys =lingLingDao.getSdkkeyByGroupId(groups.get(0).getId());
			if (StringUtils.isBlank(sdkkeys)) {
				return "";
			}
			url = developer.getUrl()+"/qrcode/addVisitorQrCode/"+developer.getOpenToken();
			map.put("lingLingId",lingLingId);
			map.put("sdkKeys",sdkkeys.split(","));
			// 设置有效时间  为结束时间当晚12点整
			map.put("endTime",LingLingUtil.getVisitorEndTime(visitorOrder.getVisitorOrderStartTime(),visitorOrder.getVisitorOrderEndTime()));// 有效时间
			map.put("strKey",developer.getStrKey());
			map.put("effecNumber",LingLingUtil.EFFEC_NUMBER_10);// 访客设置10次
			map.put("startTime",visitorOrder.getVisitorOrderStartTime().getTime());// 来访时间
		}else{
			url = developer.getUrl()+"/qrcode/addQrcodeCard/"+developer.getOpenToken();
			map.put("funcFlag", 0);
			map.put("userFlag", lingLingId);
			map.put("userType", 1);
			map.put("startTime",visitorOrder.getVisitorOrderStartTime().getTime());
			map.put("endTime", visitorOrder.getVisitorOrderEndTime().getTime());
			map.put("strKey", developer.getStrKey());
			map.put("effecNumber", LingLingUtil.EFFEC_NUMBER_10);
		}
		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());

		if (org.apache.commons.lang3.StringUtils.isBlank(params)){
			return "";
		}

		try {
			String result = HttpKit.HttpPost(params, url);
			LOG.error("VisitorInFoManagerImpl createVisitorQrCode result============>" + result);
			JSONObject object = JSONObject.parseObject(result);
			LOG.error("VisitorInFoManagerImpl createVisitorQrCode object============>" + JsonUtils.toJson(object));
			if (null != object && object.containsKey("statusCode") && null != object.get("statusCode") && "1".equals(object.getString("statusCode"))){
				JSONObject responseResult = (JSONObject) object.get("responseResult");
				LOG.error("VisitorInFoManagerImpl createVisitorQrCode responseResult============>" + JsonUtils.toJson(responseResult));
				String codeId = responseResult.getString("codeId");
				String qrcodeKey = responseResult.getString("qrcodeKey");
				visitorOrder.setLinglingId(lingLingId);
				visitorOrder.setVisitorQrCode(qrcodeKey);
				visitorOrder.setVisitorQrCodeId(Integer.parseInt(codeId));
				//Integer orderId,String linglingId,String qrcodeKey,Integer codeId
				visitorInFoDao.updateVisitorOrder(visitorOrder.getVisitorOrderId(),visitorOrder.getLinglingId(),visitorOrder.getVisitorQrCode(),visitorOrder.getVisitorQrCodeId());
				return qrcodeKey;
			}
		}catch (Exception e){
			LOG.error("VisitorInFoManagerImpl createVisitorQrCode error============>" + e.getMessage());
		}

		return "";
	}

	@Override
	public String delVisitorQrCode(Integer visitorId, String visitorOrderStatus) {

		VisitorInfo visitorInfo = null;
		VisitorOrder visitorOrder = null;

		try {
			visitorInfo = visitorInFoDao.getVisitorInfo(visitorId + "");
			if (visitorInfo == null) {
				return "";
			}
			visitorOrder = visitorInFoDao.getVisitorOrder(visitorInfo.getVisitorOrderId());
			if (visitorOrder == null) {
				return "";
			}

			// 作废二维码
			String code = visitorOrder.getVisitorQrCode();
			Integer codeId = visitorOrder.getVisitorQrCodeId();

			if (codeId == null || StringUtils.isBlank(code)){
				return "";
			}

			LOG.info("VisitorInFoManagerImpl delVisitorQrCode:codeId{},qrCode{}",codeId,code);

			String url = LingLingUtil.preUrl+"/qrcode/delVisitorQrCode/"+LingLingUtil.openToken;

			Map<String,Object> map = new HashMap<String, Object>();
			map.put("codeId",codeId);

			String params = LingLingUtil.linglingParams(map,1);

			if (org.apache.commons.lang3.StringUtils.isBlank(params)){
				return "";
			}

			String result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if (!"1".equalsIgnoreCase((String) object.get("statusCode"))){
				LOG.error("令令端删除二维码异常!=======>" + object.getString("responseResult"));
//				throw new RuntimeException("令令端删除二维码异常!");
			}

			// Lingling端删除成功后,同步本地数据库
			visitorOrder.setVisitorOrderStatus(Integer.parseInt(visitorOrderStatus));
			visitorInfo.setVisitorStatus(Constants.VISITOR_TREE_STATUS);
			visitorInfo.setVisitorIsEnabled("0");
			visitorOrder.setVisitorOrderIsEnabled("1");
			visitorInFoDao.updateObj(visitorInfo);
			visitorInFoDao.updateObj(visitorOrder);
			return Constants.SUCCESS_FLAG;
		}catch (Exception e){
			LOG.error("删除访客二维码异常!===========>" + e.getMessage());
			return "删除访客二维码异常!";
		}
	}

	@Override
	public VisitorOrder getOrderByQrcodeKey(String qrcodeKey) {
		return visitorInFoDao.getOrderByQrcodeKey(qrcodeKey);
	}

	@Override
	public VisitorInfo getLastVisitorInfoByMobile(String telephone) {
		return visitorInFoDao.getLastVisitorInfoByMobile(telephone);
	}

	@Override
	public List<VisitorInfo> getVisitorInfoList(Integer visitorOrderId) {
		return visitorInFoDao.getVisitorInfoList(visitorOrderId);
	}

	@Override
	public VisitorInfo getVisitorInfo(Integer visitorId) {
		return visitorInFoDao.getVisitorInfo(visitorId.toString());
	}

	@Override
	public VisitorInfo getVisitorInfoByQrCode(String qrCode) {
		return visitorInFoDao.getVisitorInfoByQrCode(qrCode);
	}


	@Override
	public VisitorOrder getOrderByLingLingId(String linglingId) {
		return visitorInFoDao.getOrderByLingLingId(linglingId);
	}

	@Override
	public List<VisitorPassRecordVo> getVisitorPassInfo(Integer orderId,int type) {
		return lingLingCurrentsetDao.getVisitorPassInfo(orderId,type);
	}
}
