package com.palmnest.service.lingling.manager.impl;

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

import com.alibaba.fastjson.JSONArray;
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.LinglingPassDto;
import com.palmnest.application.dto.input.LingLingVisitorMachineInputDto;
import com.palmnest.application.dto.input.lingling.QrcodeInsInputDTO;
import com.palmnest.application.dto.output.DevicePermGroupOutDto;
import com.palmnest.application.dto.output.VisitorInfoVO;
import com.palmnest.application.dto.output.lingling.*;
import com.palmnest.dao.OrganizationDao;
import com.palmnest.dao.estateserve.ScWxuserDao;
import com.palmnest.dao.lingling.LingLingDao;
import com.palmnest.model.AppUserOrgnizationRelation;
import com.palmnest.model.DateTypeInfo;
import com.palmnest.model.FloorInfo;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.lingling.*;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.UserManager;
import com.palmnest.service.dinner.service.impl.PlaceAnOrderServiceImpl;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.impl.GenericManagerImpl;
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 lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import javassist.bytecode.analysis.Type;

/**
 * @Author HIAPAD
 * @Description TODO
 * @Date 2018/12/7 12:03
 **/
@Slf4j
@Service(value = "lingLingManager")
public class LingLingManagerImpl extends GenericManagerImpl<Object, Long> implements LingLingManager {

	private LingLingDao lingLingDao;

	public static final String IMAGE_URL = PropertiesKit.readPropertiesValue("image_server", "wechat.properties");
	public static final String CLIENTNO  = PropertiesKit.readPropertiesValue("clientNo", "wechat.properties");
	
	@Autowired
	public void setLingLingDao(LingLingDao lingLingDao) {
		this.lingLingDao = lingLingDao;
		dao = lingLingDao;
	}

	@Autowired
	private AppUserManager     appUserManager;
	
	@Autowired
	private VisitorInFoManager visitorInFoManager;
	
	@Autowired
	private UserManager        userManager;
	
	@Autowired
	private PropertyManager    propertyManager;
	
	@Autowired
	private SmsAuthCodeManager smsAuthCodeManager;
	
	@Autowired
	private FloorInfoManager   floorInfoManager;

	@Autowired
	private DateTypeInfoManager dateTypeInfoManager;
	
	@Autowired
	private BaseRedisService                baseRedisService;
	@Autowired
	private OrganizationDao       organizationDao;
	@Autowired
	private WeChatApiManager weChatApiManager;

	@Autowired
	private ScWxuserDao scWxuserDao;

	@Override
	public LingLingDevice getByDeviceId(Integer deviceId,Integer orgId) {
		LingLingDevice byDeviceId = lingLingDao.getByDeviceId(deviceId,orgId);
		return byDeviceId;
	}

	@Override
	public LingLingDevice getById(Long id) {
		return lingLingDao.getById(id);
	}

	@Override
	public AppResultDto saveDevice(LingLingDevice device, String url,LingLingDeveloper developer) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("deviceName", device.getDeviceName());
		map.put("deviceCode", device.getDeviceCode());
//		if(2==device.getMethedType().intValue()){
//			map.put("strKey", LingLingUtil.NEWSTRKEY);
//		}
		if(2==device.getMethedType().intValue()){
			map.put("strKey", developer.getStrKey());
		}
		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());

		if (StringUtils.isBlank(params)) {// 参数异常
			return AppResultUtil.createErrorDto("100", "参数有误");
		}
		// 请求令令接口
		try {
			String     result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				JSONObject responseResult = (JSONObject) object.get("responseResult");
				// 获取设备id
				Integer deviceId = responseResult.getInteger("deviceId");
				// 添加成功后,需要同步到数据库
				device.setDeviceId(deviceId);
				device.setCreateTime(new Date());
				device.setDeviceStatus(0);// 默认设置离线,如果在线的话,日志回调更改其状态
				device.setIsEnable(1);
				// 如果数据库已存在该设备,则不能保存
				LingLingDevice byDeviceId = lingLingDao.getByDeviceId(deviceId,device.getOrgId());
				if (null != byDeviceId) {
					return AppResultUtil.createErrorDto("100", "设备已存在");
				}
				// 同步到数据库
				this.saveModel(device);
				map.put("deviceId", deviceId.toString());
				if(1==device.getMethedType().intValue()){
					saveDeviceSdk(device);
				}
				return AppResultUtil.createSuccesDto(map);
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}

		} catch (Exception e) {
			log.error("添加令令设备异常 LingLingManagerImpl saveDevice======>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "添加令令设备异常");
		}
	}
	
	/**
	 * 旧设备需要产生sdkkey
	 * @param device
	 */
	@Override
	public void saveDeviceSdk(LingLingDevice device){
		String deviceIds=device.getDeviceId().toString();
		String[]   ids    = deviceIds.split(",");
		JSONObject object = LingLingUtil.makeSdkKey(ids);
		String obj=object.toJSONString();
		if (object != null&&!"{}".equals(obj)) {
			for (int i = 0; i < ids.length; i++) {
				// 把sdkKey同步到本地数据库
				device.setSdkKey(object.getString(ids[i]));
				lingLingDao.updateObj(device);
			}
		}
	}

	@Override
	public AppResultDto delDevice(Integer deviceId, String url,Integer orgId) {
		LingLingDevice byDeviceId = lingLingDao.getByDeviceId(deviceId,orgId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("deviceId", deviceId);
		
		//拿项目对应的开发者信息
		LingLingDeveloper developer=findByOrgId(byDeviceId.getOrgId());
		if(null==developer){
			return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
		}
		
		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());
		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "令令接口参数异常");
		}
		try {
//			if(1==byDeviceId.getMethedType()){
//				url = LingLingUtil.preUrl + "/device/delDevice/" + LingLingUtil.openToken;
//			}else{
//				url = LingLingUtil.newPreUrl + "/device/delDevice/" + LingLingUtil.newOpenToken;
//			}
			url =developer.getUrl() + "/device/delDevice/" + developer.getOpenToken();
			String     result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				// 删除成功后同步禁用本地数据库设备状态
				byDeviceId.setIsEnable(0);
				byDeviceId.setDeviceStatus(0);
				lingLingDao.updateObj(byDeviceId);
				return AppResultUtil.createSuccesDto("删除成功");
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}
		} catch (Exception e) {
			log.error("删除令令设备异常 LingLingManagerImpl delDevice======>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "删除令令设备异常");
		}

	}

	@Override
	public AppResultDto updateDevice(Map<String, String> map, String url,LingLingDeveloper developer,Integer orgId) {

		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());
		try {
			String     result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				// 更新成功后同步更新本地数据库
				LingLingDevice byDeviceId = lingLingDao.getByDeviceId(Integer.parseInt(map.get("deviceId")),orgId);
				byDeviceId.setDeviceName(map.get("newDeviceName"));
				byDeviceId.setDeviceCode(map.get("newDeviceCode"));
				lingLingDao.updateObj(byDeviceId);
				return AppResultUtil.createSuccesDto("更新设备成功");
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}
		} catch (Exception e) {
			log.error("更新令令设备异常 LingLingManagerImpl updateDevice======>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "更新设备异常");
		}
	}

	@Override
	public Page getDeviceList(Map<String, String> paramMap) {

		List<LingLingDeviceOutDto> list  = new ArrayList<LingLingDeviceOutDto>();
		Page                       page  = lingLingDao.getDeviceList(paramMap);
		List<Map<String, Object>>  items = page.getItems();
		if (items != null && items.size() > 0) {
			// 对结果进行处理
			for (Map<String, Object> groupMap : items) {
				String deviceId = groupMap.get("id").toString();
				if (StringUtils.isNotBlank(deviceId)) {
					LingLingDevice       byId   = lingLingDao.getById(Long.parseLong(deviceId));
					LingLingDeviceOutDto outDto = convertDeviceDto(byId);
					list.add(outDto);
				}
			}
		}

		page.setItems(list);
		return page;
	}

	@Override
	public List<LingLingDevice> getDeviceList(Integer isEnable, Integer orgId) {
		return lingLingDao.getDeviceList(isEnable, orgId);
	}

	@Override
	public void updateDeviceGroup(DevicePermGroup group,Set<LingLingDevice>  setLingLingDevice) {
		// 先删除之前的绑定关系,再新增关系
      
		updateModel(group);
		
		lingLingDao.deleteByGroupId(group.getId());
		for(LingLingDevice d:setLingLingDevice){
			lingLingDao.savePermGroupDevice(group.getId(),d.getId());
		}
	}

	@Override
	public Page getDeviceGroupList(Map<String, String> paramMap) {
		Page                        page = lingLingDao.getDeviceGroupList(paramMap);
		List<DevicePermGroupOutDto> list = new ArrayList<DevicePermGroupOutDto>();

		List<Map<String, Object>> items = page.getItems();
		if (items != null && items.size() > 0) {
			// 对结果进行处理
			for (Map<String, Object> groupMap : items) {

				String groupId = groupMap.get("ID").toString();
				if (StringUtils.isNotBlank(groupId)) {
					DevicePermGroup       group       = lingLingDao.getDeviceGroupById(Long.parseLong(groupId));
//					Set<LingLingDevice>   devices     = group.getDevices();
//					String                deviceNames = LingLingUtil.getDeviceNames(devices);
					String deviceNames=lingLingDao.getDeviceNamesByGroupId(groupId);
					DevicePermGroupOutDto dto         = new DevicePermGroupOutDto();
					dto.setId(group.getId());
					dto.setCreateTime(DateHelper.toDateTimeString(group.getCreateTime()));
					dto.setDeviceNames(deviceNames);
					dto.setGroupName(group.getGroupName());
					dto.setGroupType(group.getGroupType());
					dto.setRemark(group.getRemark());
					list.add(dto);
				}
			}
		}

		page.setItems(list);
		return page;
	}

	@Override
	public DevicePermGroup getDeviceGroupById(Long id) {
		return lingLingDao.getDeviceGroupById(id);
	}

//    @Override
//    public void updateUserPerm(DevicePermGroup group) {
//        // 先删除之前 员工-权限组的的绑定关系,再新增关系,一个员工只能绑定一个权限组
//        Set<AppUser> users = group.getUsers();
//        if (users != null && users.size() > 0) {
//            String userIds = "";
//            for (AppUser user : users) {
//                userIds += user.getId() + ",";
//            }
//
//            userIds = userIds.substring(0, userIds.length() - 1);
//            lingLingDao.deleteUserGroupByUserIds(userIds);
//        }
//        updateModel(group);
//    }

	@Override
	public void updateUserPerm(String groupId, String userIds) {

		try {
			// 1.先查询该权限组原有用户集合 listOld
			List<Integer> listOld = lingLingDao.getUserIdsByGroupId(Long.parseLong(groupId));
			// 2.前台接收到的用户ID参数 listNew
			String[]      split   = userIds.split(";");
			List<Integer> listNew = new ArrayList<>();
			for (String str : split) {
				listNew.add(Integer.parseInt(str));
			}

			List<Integer> deleteIds = new ArrayList<>();
			for (Integer id : listOld) {
				if (!listNew.contains(id)) {
					deleteIds.add(id);
				}
			}

			// 3.执行 更新/新增操作
			// 3.1 listOld与listNew求差集,listOld中有的数据,listNew中没有则删除;
			for (Integer id : deleteIds) {
				lingLingDao.deleteUserGroup(id, Long.parseLong(groupId));
			}
			// 3.2 listNew中有,listOld没有,新增;
			listNew.removeAll(listOld);
			for (Integer id : listNew) {
				lingLingDao.saveUserGroup(id, groupId);
			}
		} catch (Exception e) {
			log.error("updateUserPerm error:{}=====>", e.getMessage());
		}

	}


	@Override
	public void updateUserPermNew(String groupId, String userIds, boolean isInsert,int methedType,Integer orgId) {

		try {

			String[]      split     = userIds.split(";");
			List<Integer> listUsers = new ArrayList<>();
			for (String str : split) {
				if(StringUtils.isBlank(str)){
					continue;
				}
				listUsers.add(Integer.parseInt(str));
			}

			if (isInsert) {//新增
				String userIdList=userIds.replace(";", ",");
				log.info("updateUserPermNew-userIdList:"+userIdList);
				if(StringUtils.isBlank(userIdList)){
					return;
				}
				lingLingDao.deleteUserGroupByUserIds(userIdList);
				if(1 == methedType){
					for (Integer id : listUsers) {
						lingLingDao.saveUserGroup(id, groupId);
					}
				}
				//设置linglingId
				List<AppUser> appUsers=appUserManager.getAppUserByIds(userIdList);
				String lingLingIds =setUserLinglingId(methedType,appUsers);
				//设置权限，只有新的会需要调用
				if(2==methedType){
					if(StringUtils.isBlank(lingLingIds)){
						return;
					}
					log.info("updateUserPermNew-lingLingIds:{}",JsonUtils.toJson(lingLingIds));
					List<String> list=StringUtil.indexStr(lingLingIds);
					log.info("updateUserPermNew-list:{}",JsonUtils.toJson(list));
					if(CollectionUtils.isEmpty(list)){
						return;
					}
					asyncPerm(list,groupId,orgId,userIds);
					//PC端设置权限的时候需要设置用户的卡的权限
					setCardPerm(groupId,orgId,userIdList);
				}
			} else {//删除
				for (Integer id : listUsers) {
					lingLingDao.deleteUserGroup(id, Long.parseLong(groupId));
				}
			}

		} catch (Exception e) {
			log.error("updateUserPerm error:{}=====>", e.getMessage());
			e.printStackTrace();
		}

	}
	
	private void setCardPerm(String groupId,Integer orgId,String userIds){
		List<Map<String, Object>> cardList=lingLingDao.getCardByUserIds(userIds);
		if(CollectionUtils.isEmpty(cardList)){
			return;
		}
		StringBuilder sb=new StringBuilder("");
		for(int i=0;i<cardList.size();i++){
			Map<String, Object> map=cardList.get(i);
			if(null == map || !map.containsKey("card_code") || null == map.get("card_code") || StringUtils.isEmpty(map.get("card_code").toString())){
				continue;
			}
			sb.append(map.get("card_code").toString());
			sb.append(",");
		}
		
		String cards=sb.toString();
		if(StringUtils.isNotEmpty(cards)){
			cards=cards.substring(0,cards.length()-1);
		}
		List<String> list=StringUtil.indexStr(cards);
		for(int i=0;i<list.size();i++){
			String cardIds=list.get(i);
			String res=saveUserPerm(Integer.parseInt(groupId), cardIds,orgId,1);
			if(StringUtils.isNotBlank(res)){
				continue;
			}
		}
		
	}
	
	private void asyncPerm(List<String> list,String groupId,Integer orgId,String userIds){
		List<String> sucList=new ArrayList<String>();
		for(int i=0;i<list.size();i++){
			String lingLingIds=list.get(i);
			String res=saveUserPerm(Integer.parseInt(groupId), lingLingIds,orgId,2);
			if(StringUtils.isNotBlank(res)){
				continue;
			}
			lingLingIds="'"+lingLingIds.replace(",", "','")+"'";
			sucList.add(lingLingIds);
		}
		log.info("asyncPerm-sucList:{}",JsonUtils.toJson(sucList));
		if(!CollectionUtils.isEmpty(sucList)){
			List<UserPermGroup> retGroupList=new ArrayList<UserPermGroup>();
			for(String lingLingIds:sucList){
				log.info("manager-asyncPerm-lingLingIds:"+lingLingIds);
				List<Integer> userList=lingLingDao.getUserIdByLingLingIds(lingLingIds);
				log.info("manager-asyncPerm-userList:"+JsonUtils.toJson(userList));
				if(CollectionUtils.isEmpty(userList)){
					continue;
				}
				for(Integer id:userList){
//					lingLingDao.saveUserGroup(id, groupId);
					UserPermGroup userPermGroup=new UserPermGroup();
					userPermGroup.setGroupId(Long.parseLong(groupId));
					userPermGroup.setLastUpdateTime(new Date());
					userPermGroup.setUserId(id);
					UserPermGroup retUG=(UserPermGroup) this.saveModel(userPermGroup);
					retGroupList.add(retUG);
				}
			}
			log.info("manager-asyncPerm-retGroupList:"+JsonUtils.toJson(retGroupList));
		}
	}
	
	/**
	 * 给用户创建linglingId
	 * @param methedType
	 * @param appUsers
	 */
	private String setUserLinglingId(int methedType,List<AppUser> appUsers){
		String lingLingIds = "";
		for(AppUser appUser:appUsers){
			if(StringUtils.isNotBlank(appUser.getLingLingId())){
				lingLingIds=lingLingIds+appUser.getLingLingId()+",";
				continue;
			}
			String linglingId="";
			if(1==methedType){
				// 同步到user表中
				linglingId=LingLingUtil.getLingLingId();
			}else{
				// 同步到user表中
				linglingId=LingLingUtil.getRandomValue(8);
			}
			if(StringUtils.isEmpty(linglingId)){
				continue;
			}
			appUser.setLingLingId(linglingId);
			appUser.setModifyTime(new Date());
			appUserManager.updateModel(appUser);
			lingLingIds=lingLingIds+linglingId+",";
		}
		return lingLingIds;
	}
	
	/**
	 * 保存用户的权限
	 */
	@Override
	public String saveUserPerm(Integer groupId,String lingLingIds,Integer orgId,int cardType){
		long beginTime=System.currentTimeMillis();
		log.info("批量设置令令权限时间11111:"+beginTime+";lingLingIds:"+lingLingIds);
		log.info("批量设置令令权限时间11111:"+beginTime+";groupId:"+groupId);
		log.info("批量设置令令权限时间11111:"+beginTime+";orgId:"+orgId);
		log.info("批量设置令令权限时间11111:"+beginTime+";cardType:"+cardType);
		if(StringUtils.isEmpty(lingLingIds)){
			return "用户不能为空";
		}
		//拿项目对应的开发者信息
		LingLingDeveloper developer=findByOrgId(orgId);
		String deviceIds=lingLingDao.getDeviceIdsByGroupId(groupId);
		if(StringUtils.isEmpty(deviceIds)){
			return "设备不能为空";
		}
		Map param=new HashMap();
		param.put("cardUids", lingLingIds.split(","));
		param.put("deviceIds", deviceIds.split(","));
		param.put("endTime", LingLingUtil.endTime);
		param.put("cardType", cardType);
		param.put("cardFlag", 0);
		String res=LingLingUtil.addOpenDoorCard(param,developer.getUrl(),developer.getSignature(),developer.getToken(),developer.getOpenToken(),developer.getStrKey(),cardType);
		long endTime=System.currentTimeMillis();
		log.info("批量设置令令权限时间11111:"+(endTime-beginTime)+"----------lingLingIds:"+lingLingIds+"--------res:"+res);
		return res;
	}


	@Override
	public List<DevicePermGroup> getDevicePermGroupByOrgId(Integer orgId, Integer groupType) {

		return lingLingDao.getDevicePermGroupByOrgId(orgId, groupType);
	}

//	@Override
//	public AppResultDto provideCard(String cardCode, String userId) {
//
//		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
//		// 查询该用户关联权限组对应的设备列表
//		if (appUser == null || appUser.getGroup() == null || appUser.getGroup().getGroupType() != 1) {
//			// 权限组为员工权限组
//			return AppResultUtil.createErrorDto("100", "用户不存在或者用户没有权限组");
//		}
//		
//		LingLingCard ling=lingLingDao.getCardByCardId(cardCode);
//		if(null!=ling){
//			return AppResultUtil.createErrorDto("100", "cardUids有重复添加的数据");
//		}
//
////		Set<LingLingDevice> devices   = appUser.getGroup().getDevices();
////		String              deviceIds = LingLingUtil.handleDevice(devices);
//		
//		String oldDevices=lingLingDao.getDeviceIdsByMethedType(1, Integer.parseInt(userId));
//		
//		String newDevices=lingLingDao.getDeviceIdsByMethedType(2, Integer.parseInt(userId));
//
//		if (StringUtils.isBlank(oldDevices)&&StringUtils.isBlank(newDevices)) {
//			return AppResultUtil.createErrorDto("100", "该权限组未绑定设备");
//		}
//		
//		StringBuilder sb=new StringBuilder();
//		int msgCount=0;
//		String url="";
//		String params = "";
//		try{
//			if(StringUtils.isNotBlank(oldDevices)){
//				url = LingLingUtil.preUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.openToken;
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("cardUids", cardCode.split(","));
//				map.put("deviceIds", oldDevices.split(","));
//				map.put("endTime", LingLingUtil.MAX_TIME);
//				params = LingLingUtil.linglingParam(map);
//				
//				if (StringUtils.isBlank(params)) {
//					return AppResultUtil.createErrorDto("100", "令令接口参数异常");
//				}
//
//				String     result = HttpKit.HttpPost(params, url);
//				JSONObject object = JSONObject.parseObject(result);
//				if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//				} else {
//					String responseResult = object.getString("responseResult");
//					sb.append("------------oldFail-"+responseResult);
//					msgCount++;
//				}
//			}
//			
//			if(StringUtils.isNotBlank(newDevices)){
//				url = LingLingUtil.newPreUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.newOpenToken;
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("cardUids", cardCode.split(","));
//				map.put("deviceIds", newDevices.split(","));
//				map.put("endTime", LingLingUtil.MAX_TIME);
//				//新增加的字段
//				map.put("cardType",1);
//				map.put("effecNumber",1);
////				map.put("uidType", 1);
////				map.put("sectorIndex",1);
////				map.put("cardFlag", 0);
//				params = LingLingUtil.linglingParam(map);
//				
//				if (StringUtils.isBlank(params)) {
//					return AppResultUtil.createErrorDto("100", "令令接口参数异常");
//				}
//
//				String     result = HttpKit.HttpPost(params, url);
//				JSONObject object = JSONObject.parseObject(result);
//				if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//					
//				} else {
//					String responseResult = object.getString("responseResult");
//					sb.append("------------newFail-"+responseResult);
//					msgCount++;
//				}
//			}
//			
//			if(msgCount>0){
//				log.error("添加门禁卡失败 LingLingManagerImpl provideCard ===========>" + sb.toString());
//				return AppResultUtil.createErrorDto("100", sb.toString());
//			}else{
//				LingLingCard card = new LingLingCard();
//				card.setCardCode(cardCode);
//				card.setUser(appUser);
//				card.setCreateTime(new Date());
//				saveModel(card);
//				return AppResultUtil.createSuccesDto("发卡成功");
//			}
//		}catch (Exception e) {
//			log.error("添加门禁卡失败 LingLingManagerImpl provideCard ===========>" + e.getMessage());
//			return AppResultUtil.createErrorDto("100", "发卡异常");
//		}
//		
//	}
	
	
	@Override
	public AppResultDto provideCard(String cardCode, String userId) {

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		// 查询该用户关联权限组对应的设备列表
//		if (appUser == null || appUser.getGroup() == null || appUser.getGroup().getGroupType() != 1) {
//			// 权限组为员工权限组
//			return AppResultUtil.createErrorDto("100", "用户不存在或者用户没有权限组");
//		}
		
		Map<String, Object> userGroupMap=getUserGroupInfo(appUser.getId());
		
		if (appUser == null || null==userGroupMap) {
			// 权限组为员工权限组
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		
		if (!userGroupMap.containsKey("groupId") || !userGroupMap.containsKey("groupType") ||null == userGroupMap.get("groupId")) {
			// 权限组为员工权限组
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		
		if(StringUtils.isBlank(userGroupMap.get("groupType").toString()) || 1 != Integer.parseInt(userGroupMap.get("groupType").toString())){
			return AppResultUtil.createErrorDto("100", "用户不存在或者用户权限组为空");
		}
		
		int methedType=getMethedType(appUser.getOrganizationId()+"");

//		Set<LingLingDevice> devices   = appUser.getGroup().getDevices();
//		String              deviceIds = LingLingUtil.handleDevice(devices);

		String              deviceIds =lingLingDao.getDeviceIdsByUserId(appUser.getId());
		if (StringUtils.isBlank(deviceIds)) {
			return AppResultUtil.createErrorDto("100", "该权限组未绑定设备");
		}
		
		//拿项目对应的开发者信息
		LingLingDeveloper developer=findByOrgId(appUser.getOrganizationId());
		if(null==developer){
			return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
		}
		
		String url=developer.getUrl() + "/openDoorCard/addOpenDoorCard/" + developer.getOpenToken();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cardUids", cardCode.split(","));
		map.put("deviceIds", deviceIds.split(","));
		map.put("endTime", LingLingUtil.endTime);//无期限
		if(1==methedType){
//			url=LingLingUtil.preUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.openToken;
		}else{
//			url=LingLingUtil.newPreUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.newOpenToken;
			map.put("cardType",1);
			map.put("effecNumber",LingLingUtil.endTime);
		}

		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());
		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "令令接口参数异常");
		}

		try {
			String     result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				LingLingCard card = new LingLingCard();
				card.setCardCode(cardCode);
				card.setCreateTime(new Date());
				saveModel(card);
				if(null!=card.getId()){
					lingLingDao.saveCardAndUser(appUser.getId(), card.getId());
				}
				return AppResultUtil.createSuccesDto("发卡成功");
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}
		} catch (Exception e) {
			log.error("添加门禁卡失败 LingLingManagerImpl provideCard ===========>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "添加门禁卡异常");
		}
	}

	@Override
	public AppResultDto recycleCard(String cardId, String cardCode,int methedType,LingLingDeveloper developer) {

		String url = developer.getUrl()+ "/openDoorCard/delOpenDoorCard/" + developer.getOpenToken();
		
//		if(1==methedType){
//			url = LingLingUtil.preUrl + "/openDoorCard/delOpenDoorCard/" + LingLingUtil.openToken;
//		}else{
//			url = LingLingUtil.newPreUrl + "/openDoorCard/delOpenDoorCard/" + LingLingUtil.newOpenToken;
//		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cardUids", cardCode.split(","));

		String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());
		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "令令接口参数异常");
		}

		try {
			String     result = HttpKit.HttpPost(params, url);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				LingLingCard card = new LingLingCard();
				card.setId(Long.parseLong(cardId));
				lingLingDao.delCardAndUser(Long.parseLong(cardId));
				remove(card);
				return AppResultUtil.createSuccesDto("收卡成功");
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}
		} catch (Exception e) {
			log.error("删除门禁卡失败 LingLingManagerImpl recycleCard ===========>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "收卡异常");
		}
	}

	@Override
	public String delDeviceGroup(String groupId) {

		DevicePermGroup group = lingLingDao.getDeviceGroupById(Long.parseLong(groupId));
		if (group == null) {
			return Constants.FAIL_FLAG;
		}

		lingLingDao.remove(group);
		return Constants.SUCCESS_FLAG;
	}

	/**
	 * 设备实体转换
	 *
	 * @param byDeviceId
	 * @return
	 */
	public LingLingDeviceOutDto convertDeviceDto(LingLingDevice byDeviceId) {
		if (byDeviceId != null) {
			LingLingDeviceOutDto dto = new LingLingDeviceOutDto();
			dto.setId(byDeviceId.getId());
			dto.setAddress(byDeviceId.getAddress());
			dto.setDeviceCode(byDeviceId.getDeviceCode());
			dto.setDeviceId(byDeviceId.getDeviceId());
			dto.setDeviceName(byDeviceId.getDeviceName());
			dto.setDeviceStatus(byDeviceId.getDeviceStatus());
			dto.setDeviceType(byDeviceId.getDeviceType());
			dto.setIsEnable(byDeviceId.getIsEnable());

			if (byDeviceId.getModify() != null) {
				dto.setModify(byDeviceId.getModify().toString());
			}
			if (byDeviceId.getCreator() != null) {
				dto.setCreator(byDeviceId.getCreator().toString());
			}

			dto.setModifyTime(DateHelper.toDateTimeString(byDeviceId.getCreateTime()));
			dto.setCreateTime(DateHelper.toDateTimeString(byDeviceId.getCreateTime()));

			dto.setOrgId(byDeviceId.getOrgId());
			dto.setRemark(byDeviceId.getRemark());
			return dto;
		} else {
			return null;
		}
	}

	@Override
	public List<Map<String, Object>> getGroupUser(String groupId) {

//		DevicePermGroup group = lingLingDao.getDeviceGroupById(Long.parseLong(groupId));
//		Set<AppUser>    users = group.getUsers();
//		String userIds=lingLingDao.getUserIdsByGroupId(groupId);
//		List<AppUser> appUsers=appUserManager.getAppUserByIds(userIdList);
		List<Map<String, Object>> list = lingLingDao.getGroupUser(groupId);

//		if (users != null && users.size() > 0) {
//			for (AppUser user : users) {
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("userId", user.getId());
//				map.put("mobile", user.getUserMobile());
//				map.put("userName", user.getUserName());
//				list.add(map);
//			}
//		}

//		Collections.sort(list, new Comparator<Map<String, Object>>() {
//			@Override
//			public int compare(Map<String, Object> map1, Map<String, Object> map2) {
//				int userId1 = (int) map1.get("userId");
//				int userId2 = (int) map2.get("userId");
//				return userId1 - userId2;
//			}
//		});

		return list;
	}


	@Override
	public List<String> makeSdkKey(Collection<LingLingDevice> devices) {

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

		if (devices == null || devices.size() < 1) {
			return null;
		}

		Integer orgId=null;
		String deviceIds = "";
		for (LingLingDevice device : devices) {
			orgId=device.getOrgId();
			if (device.getIsEnable() == 1) {
				// 设备是可用状态
				if (StringUtils.isNotBlank(device.getSdkKey())) {
					// 如果该设备已经生成了sdkKey,则直接获取
					sdk.add(device.getSdkKey());
				} else {
					// 还没有生成sdkKey的设备id串
					deviceIds += device.getDeviceId() + ",";
				}
			}
		}

		try {
			if (StringUtils.isNotBlank(deviceIds)) {
				String[]   ids    = deviceIds.split(",");
				JSONObject object = LingLingUtil.makeSdkKey(ids);
				String obj=object.toJSONString();
				if (object != null&&!"{}".equals(obj)) {
					for (int i = 0; i < ids.length; i++) {
						sdk.add(object.getString(ids[i]));
						// 把sdkKey同步到本地数据库
						LingLingDevice byDeviceId = lingLingDao.getByDeviceId(Integer.parseInt(ids[i]),orgId);
						byDeviceId.setSdkKey(object.getString(ids[i]));
						lingLingDao.updateObj(byDeviceId);
					}
				}
			}
			return sdk;
		} catch (Exception e) {
			log.error("LingLingManagerImpl makeSdkKey======>生成sdkkey异常:" + e.getMessage());
			return null;
		}
	}
	
	
	@Override
	public AppResultDto createQrCode(AppUser appUser,Long groupId) {
		try {
			int methedType=getMethedType(appUser.getOrganizationId()+"");
			if (StringUtils.isBlank(appUser.getLingLingId())) {
				return AppResultUtil.createErrorDto("100", "令令id为空");
			}
			String lingLingId = appUser.getLingLingId();
			
			//拿项目对应的开发者信息
			LingLingDeveloper developer=findByOrgId(appUser.getOrganizationId());
			if(null==developer){
				return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
			}
			

			if (StringUtils.isBlank(lingLingId)) {
				return AppResultUtil.createErrorDto("100", "令令id为空");
			}

			log.info("LingLingWechatController createQrCode:lingLingId{}", lingLingId);
			String url ="";
			Map<String, Object> map = new HashMap<String, Object>();
			if(1==methedType){
				//根据这个查询
				String sdkkeys =lingLingDao.getSdkkeyByGroupId(groupId);
				if (StringUtils.isBlank(sdkkeys)) {
					return AppResultUtil.createErrorDto("100", "密匙为空");
				}
//
				url = developer.getUrl() + "/qrcode/addOwnerQrCode/" + developer.getOpenToken();
				map.put("lingLingId", lingLingId);
				map.put("sdkKeys", sdkkeys.split(","));
				map.put("endTime", LingLingUtil.OWNER_QRCODE_FLUSH_TIME);
				map.put("strKey", developer.getStrKey());
				map.put("effecNumber", LingLingUtil.EFFEC_NUMBER_1);
			}else{
				url = developer.getUrl() + "/qrcode/addQrcodeCard/" +developer.getOpenToken();
				map.put("funcFlag", 0);
				map.put("userFlag", lingLingId);
				map.put("userType", 0);
				Calendar nowTime = Calendar.getInstance();
				Long startTime=nowTime.getTimeInMillis();
				System.out.println("当前时间       -"+startTime);
				nowTime.add(Calendar.MINUTE, 10);
				Long endTime=nowTime.getTimeInMillis();
				System.out.println("当前时间+10m-"+endTime);
				map.put("startTime",startTime);
				map.put("endTime", endTime);
				map.put("strKey", developer.getStrKey());
				map.put("effecNumber", LingLingUtil.EFFEC_NUMBER_1);
			}

			String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());

			if (StringUtils.isBlank(params)) {
				return AppResultUtil.createErrorDto("100", "令令参数错误");
			}

			long beginTime=System.currentTimeMillis();
			log.info("createQrCode-业主请求令令接口创建二维码开始时间:"+beginTime);
			String     result = HttpKit.HttpPost2(params, url,methedType);
			long endTime=System.currentTimeMillis();
			log.info("createQrCode-业主请求令令接口创建二维码结束时间:"+endTime);
			log.info("createQrCode-业主请求令令接口创建二维码计算时间:"+(endTime-beginTime));
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				JSONObject responseResult = (JSONObject) object.get("responseResult");
				String     qrcodeKey      = responseResult.getString("qrcodeKey");
				return AppResultUtil.createSuccesDto(qrcodeKey);
			} else {
				String responseResult = object.getString("responseResult");
				return AppResultUtil.createErrorDto("100", responseResult);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			log.error("LingLingManagerImpl createQrCode error 生成员工二维码异常==请求令令接口超时==========>" + e.getMessage());
			return AppResultUtil.createErrorDto("500", "通行系统请求超时");
		}catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingManagerImpl createQrCode error 生成员工二维码异常============>" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "生成员工二维码异常");
		}
	}

	@Override
	public void uploadLogMsg(JSONObject noticeMsg) {

		String     noticeName = noticeMsg.getString("noticeName");// 方法名
		JSONObject msg        = noticeMsg.getJSONObject("msg");
		Long       openTime   = msg.getLong("openTime");
		Integer    deviceId   = msg.getInteger("deviceId");
		String     deviceCode = msg.getString("deviceCode");

		LingLingLog lingLingLog = new LingLingLog();
		lingLingLog.setPassType(2);

		VisitorOrder tempOrder = null;


		lingLingLog.setCreateTime(new Date());
		if (openTime != null) {
			lingLingLog.setOpenTime(new Date(openTime));
		}
		lingLingLog.setDeviceId(deviceId);
		lingLingLog.setDeviceCode(deviceCode);

		if (noticeName.equals(LingLingUtil.OWNER_QRCODE_OPEN)) {// 业主二维码开门
			lingLingLog.setType(LingLingUtil.OWNER_LOG_TYPE);
			String lingLingId = msg.getString("lingLingId");
			lingLingLog.setLingLingId(lingLingId);
			// 业主二维码开门即白名单用户开门,可以根据lingLingId查询到该用户信息
			AppUser appUser = appUserManager.getAppUserByLingLingId(lingLingId);
			if (appUser != null) {
				lingLingLog.setUserName(appUser.getUserName());
				lingLingLog.setMobile(appUser.getUserMobile());
			}
		} else if (noticeName.equals(LingLingUtil.VISITOR_QRCODE_OPEN)) {// 访客二维码开门
			lingLingLog.setType(LingLingUtil.VISITOR_LOG_TYPE);
			String qrcodeKey = msg.getString("qrcodeKey");
			lingLingLog.setQrcodeKey(qrcodeKey);

			// 根据二维码key查询访客订单,根据访客订单查询访客信息,如果访客有多个,则取第一个访客的信息就可以了!
			VisitorOrder visitorOrder = visitorInFoManager.getOrderByQrcodeKey(qrcodeKey);
			if (visitorOrder != null) {
				List<VisitorInfo> visitorInfoList = visitorInFoManager.getVisitorInfoList(visitorOrder.getVisitorOrderId());
				if (Objects.nonNull(visitorInfoList) && visitorInfoList.size() > 0) {
					lingLingLog.setMobile(visitorInfoList.get(0).getVisitorPhone());
					lingLingLog.setUserName(visitorInfoList.get(0).getVisitorName());
				}
			}
		} else if (noticeName.equals(LingLingUtil.NFC_OPEN)) {// 实体卡开门
			lingLingLog.setType(LingLingUtil.NFC_LOG_TYPE);
			String cardUid = msg.getString("cardUid");
			lingLingLog.setCardUid(cardUid);

			// 实体卡开门可以根据实体卡cardUid查询到该用户信息
			LingLingCard card = lingLingDao.getCardByCardId(cardUid);
			if (card != null) {
//				AppUser appUser = card.getUser();
				Map<String,Object> cardMap=lingLingDao.getUserCardInfo(card.getId());
				if (null != cardMap) {
					if(cardMap.containsKey("userName") && null != cardMap.get("userName")){
						lingLingLog.setUserName(cardMap.get("userName").toString());
					}
					
					if(cardMap.containsKey("userMobile") && null != cardMap.get("userMobile")){
						lingLingLog.setMobile(cardMap.get("userMobile").toString());
					}
					
				}
			}
		} else if (noticeName.equals(LingLingUtil.DEVICE_STATUS)) {// 设备状态回调
			lingLingLog.setType(LingLingUtil.DEVICE_LOG_TYPE);
			String  version = msg.getString("version");
			Integer status  = msg.getInteger("status");
			lingLingLog.setDeviceVersion(version);
			lingLingLog.setDeviceStatus(status);

			// 同时更新设备状态信息
			LingLingDevice byDeviceId = lingLingDao.getByDeviceCode(deviceCode);
			if (byDeviceId != null) {
				byDeviceId.setDeviceStatus(status);
				lingLingDao.updateObj(byDeviceId);
			}
		}else if(noticeName.equals(LingLingUtil.USER_QRCODE_OPEN)){
			String userFlag=msg.getString("userFlag");
			int userType=msg.getIntValue("userType");
			if(0==userType){
				//业主
				lingLingLog.setType(LingLingUtil.OWNER_LOG_TYPE);
				lingLingLog.setLingLingId(userFlag);
				// 业主二维码开门即白名单用户开门,可以根据lingLingId查询到该用户信息
				AppUser appUser = appUserManager.getAppUserByLingLingId(userFlag);
				if (appUser != null) {
					lingLingLog.setUserName(appUser.getUserName());
					lingLingLog.setMobile(appUser.getUserMobile());
				}
			}else{
				//访客
				log.info("访客二维码设备通行-uploadLogMsg:"+JsonUtils.toJson(msg));
				lingLingLog.setType(LingLingUtil.VISITOR_LOG_TYPE);
				// 根据二维码key查询访客订单,根据访客订单查询访客信息,如果访客有多个,则取第一个访客的信息就可以了!
				VisitorOrder visitorOrder = visitorInFoManager.getOrderByLingLingId(userFlag);
				lingLingLog.setLingLingId(userFlag);
				if (visitorOrder != null) {
					List<VisitorInfo> visitorInfoList = visitorInFoManager.getVisitorInfoList(visitorOrder.getVisitorOrderId());
					if (Objects.nonNull(visitorInfoList) && visitorInfoList.size() > 0) {
						lingLingLog.setMobile(visitorInfoList.get(0).getVisitorPhone());
						lingLingLog.setUserName(visitorInfoList.get(0).getVisitorName());
					}
					if(null != visitorOrder.getVisitorUserId()){
						tempOrder = visitorOrder;
					}
				}
			}
		}else{
			return;
		}

		lingLingDao.save(lingLingLog);

		if(null != tempOrder && null != tempOrder.getVisitorUserId()){
			//推送模板消息给被访人
			sendWxTempMsgByVisitor(tempOrder,lingLingLog);
		}
	}

	/**
	 * 访客通行时需要给被访人发送模板消息
	 */
	public void sendWxTempMsgByVisitor(VisitorOrder visitorOrder,LingLingLog lingLingLog){
		if(null == lingLingLog || StringUtils.isEmpty(lingLingLog.getMobile()) || StringUtils.isEmpty(lingLingLog.getDeviceCode())){
			return;
		}
		if(null == visitorOrder || null == visitorOrder.getVisitorUserId()){
			return;
		}
		LingLingDevice device = lingLingDao.getByDeviceCode(lingLingLog.getDeviceCode());
		if(null == device){
			return;
		}
		//推送的人(被访人)，谁通行，手机号码，在什么时候，在哪个设备上通行的；
		//log表获取通行时间和通行设备，通行人姓名、手机号
		//tb_visitororder表获取被访人
		Integer userId = visitorOrder.getVisitorUserId();//被访人
		if(!appUserManager.exists(userId)){
			return;
		}
		AppUser user = appUserManager.get(userId);
		if(null == user || null == user.getWxUserId()){
			return;
		}
		WxUser wxUser = scWxuserDao.getScWxuserByWxUserId(user.getWxUserId());
		if(null == wxUser || null == wxUser.getId() || StringUtils.isEmpty(wxUser.getDevelopId())){
			return;
		}
		StringBuilder sb = new StringBuilder();
		if(StringUtils.isNotEmpty(lingLingLog.getUserName())){
			sb.append(lingLingLog.getUserName());
			sb.append(" ");
		}else{
			sb.append("手机号为");
		}
		sb.append(lingLingLog.getMobile());
		sb.append(" 的访客通行码于");
		String time = DateHelper.formatDate(new Date(),DateHelper.DATE_TIME_STRING);
		if(null != lingLingLog.getOpenTime()){
			time = DateHelper.formatDate(lingLingLog.getOpenTime(),DateHelper.DATE_TIME_STRING);
		}
		sb.append(time);
		sb.append(" 在");
		sb.append(device.getDeviceName());
		sb.append(" 扫码通行，请知悉！");
		String content = sb.toString();
		weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(),wxUser.getId(),content);
	}

	@Override
	public Page getPassHistory(Map<String, String> params) {
		
		Page                      page  = lingLingDao.getPassHistory(params);
		List<Map<String, Object>> items = page.getItems();

		if (items != null && items.size() > 0) {
			for (Map<String, Object> map : items) {
				if(null!=map&&map.containsKey("type")&&null!=map.get("type")){
					Integer type = Integer.parseInt(map.get("type").toString());
					if (type.equals(2) &&map.containsKey("userName") &&null == map.get("userName")) {
						// 通行记录为访客通行且手机号为空,说明是访客机访客,姓名与手机号需要另行去填充,根据通行二维码code
						if(map.containsKey("qrcodeKey")&&null!=map.get("qrcodeKey")){
							VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfoByQrCode(map.get("qrcodeKey").toString());
							if (null != visitorInfo) {
								map.put("userName", visitorInfo.getVisitorName());
								map.put("mobile", visitorInfo.getVisitorPhone());
							}
						}
					}
				}
				Date openTime = (Date) map.get("openTime");
				map.put("openTime", DateHelper.formatDate(openTime, DateHelper.DATE_TIME_STRING));
			}
		}
		page.setItems(items);
		return page;
	}

	@Override
	public List<LingLingDevice> getDevicesByGroup(Long groupId, Integer isEnable) {
		return lingLingDao.getDevicesByGroup(groupId, isEnable);
	}

	@Override
	public void deleteUserGroupByUserIds(String userIds) {
		lingLingDao.deleteUserGroupByUserIds(userIds);
	}

	@Override
	public boolean addUpdateVisitorMachine(LingLingVisitorMachineInputDto visitorMachine, User user) {

		try {
			VisitorMachine machine = lingLingDao.getVisitorMachineByOrgId(visitorMachine.getOrgId());
			if (Objects.isNull(machine)) {
				machine = new VisitorMachine();
				// 新增
				machine.setCreateTime(new Date());
				machine.setCreator(user.getId());
				machine.setEnable(1);
				machine.setOrgId(visitorMachine.getOrgId());
			} else {
				// 修改
				machine = lingLingDao.getVisitorMachine(visitorMachine.getMachineId());
				machine.setModifier(user.getId());
				machine.setModifyTime(new Date());
			}

			machine.setRequiredIdenNumber(visitorMachine.getIsRequiredIdenNumber());
			machine.setTakePhoto(visitorMachine.getIsTakePhoto());
			machine.setUploadIdenphoto(visitorMachine.getIsUploadIdenphoto());
			machine.setIsNewVersion(visitorMachine.getIsNewVersion());
			machine.setDeviceCode(visitorMachine.getDeviceCode());
			machine.setMachineJson(visitorMachine.getMachineJson());
			
			machine.setVisitReason(visitorMachine.getVisitReasonStr());
			
			// 访问目的需要拼接成字符串存储,用分号';'分割
			/*String[] visitReason = visitorMachine.getVisitReason();
			if (ArrayUtils.isNotEmpty(visitReason)) {
				String reasonStr = StringUtils.join(visitReason, ";");
				machine.setVisitReason(reasonStr);
			}*/

			if (machine.getId() == null) {
				lingLingDao.save(machine);
			} else {
				lingLingDao.updateObj(machine);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("新增/修改 访客机配置异常======>{}", e.getMessage());
			return false;
		}

		return true;
	}

	@Override
	public LingLingVisitorMachineInputDto getVisitorMachine(Integer orgId) {

		VisitorMachine                 visitorMachine = lingLingDao.getVisitorMachineByOrgId(orgId);
		LingLingVisitorMachineInputDto dto            = new LingLingVisitorMachineInputDto();

		if (Objects.isNull(visitorMachine)) {
			return null;
		}
		dto.setMachineId(visitorMachine.getId());
		dto.setIsRequiredIdenNumber(visitorMachine.getRequiredIdenNumber());
		dto.setIsTakePhoto(visitorMachine.getTakePhoto());
		dto.setIsUploadIdenphoto(visitorMachine.getUploadIdenphoto());
		dto.setOrgId(visitorMachine.getOrgId());
		/*if (StringUtils.isNotBlank(visitorMachine.getVisitReason())) {
			dto.setVisitReason(visitorMachine.getVisitReason().split(";"));
		}*/
		dto.setVisitReasonStr(visitorMachine.getVisitReason());
		dto.setIsNewVersion(visitorMachine.getIsNewVersion());
		dto.setDeviceCode(visitorMachine.getDeviceCode());
		dto.setMachineJson(visitorMachine.getMachineJson());
		return dto;
	}
	
	@Override
	public LingLingVisitorMachineInputDto getVisitorMachineByDeviceCode(String deviceCode) {

		VisitorMachine                 visitorMachine = lingLingDao.getVisitorMachineByDeviceCode(deviceCode);
		LingLingVisitorMachineInputDto dto            = new LingLingVisitorMachineInputDto();

		if (Objects.isNull(visitorMachine)) {
			return null;
		}
		dto.setMachineId(visitorMachine.getId());
		dto.setIsRequiredIdenNumber(visitorMachine.getRequiredIdenNumber());
		dto.setIsTakePhoto(visitorMachine.getTakePhoto());
		dto.setIsUploadIdenphoto(visitorMachine.getUploadIdenphoto());
		dto.setOrgId(visitorMachine.getOrgId());
		if (StringUtils.isNotBlank(visitorMachine.getVisitReason())) {
			dto.setVisitReason(visitorMachine.getVisitReason().split(";"));
		}
		dto.setDeviceCode(visitorMachine.getDeviceCode());
		dto.setIsNewVersion(visitorMachine.getIsNewVersion());
		dto.setMachineJson(visitorMachine.getMachineJson());
		return dto;
	}

	@Override
	public LoginWinVO getVisitorMachineByOrgId(Integer orgId) {
		VisitorMachine machine    = lingLingDao.getVisitorMachineByOrgId(orgId);
		LoginWinVO     loginWinVO = new LoginWinVO();
		if (Objects.isNull(machine)) {
			return null;
		}
		loginWinVO.setDefaultEffectNumber(LingLingUtil.EFFEC_NUMBER_10);
		loginWinVO.setIsRequiredIdenNumber(machine.getRequiredIdenNumber());
		loginWinVO.setIsTakePhoto(machine.getTakePhoto());
		loginWinVO.setIsUploadIdenphoto(machine.getUploadIdenphoto());
		return loginWinVO;
	}

	@Override
	public SelectVisitorVO getVisitorInfo(String telephone, String idenNumber) {

		// 查询访客基本信息
		LingLingVisitorInfo visitorInfo = null;
		if (StringUtils.isNotBlank(telephone)) {
			visitorInfo = lingLingDao.getVisitorInfoByTelephone(telephone);
		}
		if (StringUtils.isNotBlank(idenNumber) && Objects.isNull(visitorInfo)) {
			visitorInfo = lingLingDao.getVisitorInfoByIdenNumber(idenNumber);
		}

		SelectVisitorVO visitorVO = new SelectVisitorVO();
		if (!Objects.isNull(visitorInfo)) {
			// 查询访客记录(取最后最新一条数据)
			VisitorInfo lastVisitor = visitorInFoManager.getLastVisitorInfoByMobile(telephone);
			visitorVO.setIdenNumber(visitorInfo.getIdenNumber());
			visitorVO.setActiveFrom(visitorInfo.getIdenActiveFrom());
			visitorVO.setActiveTo(visitorInfo.getIdenActiveTo());
			visitorVO.setBirthday(visitorInfo.getBirthday() == null ? "" : DateHelper.formatDate(visitorInfo.getBirthday(), DateHelper.FORMATS[0]));
			visitorVO.setCardId(visitorInfo.getCardId());
			visitorVO.setCensusAddr(visitorInfo.getCensusAddr());
			visitorVO.setCreateTime(visitorInfo.getCreateTime() == null ? "" : DateUtils.paseDateToLong(DateHelper.formatDate(visitorInfo.getCreateTime(), DateHelper.FORMATS[2])));
			visitorVO.setName(visitorInfo.getVisitorName());
			visitorVO.setPolice(visitorInfo.getPolice());
			visitorVO.setRace(visitorInfo.getRace());
			visitorVO.setTelephone(visitorInfo.getTelephone());
			if (!Objects.isNull(lastVisitor)) {
				visitorVO.setSnapshotImgName(lastVisitor.getUserHeadUrl());
				visitorVO.setHeadImgName(lastVisitor.getVisitorIdenHeadImg());
			}
		}

		visitorVO.setLlingId(LingLingUtil.getLingLingId());
		return visitorVO;
	}
	
	@Override
	public NewSelectVisitorVO getNewVisitorInfo(String telephone, String idenNumber) {


	
	/**
	 * //1 如是身份证头像 photoType 会传值：headImg
		//2 如是抓拍图片 photoType 会传值：SnapImg
	 */
		// 查询访客基本信息
		LingLingVisitorInfo visitorInfo = null;
		if (StringUtils.isNotBlank(telephone)) {
			visitorInfo = lingLingDao.getVisitorInfoByTelephone(telephone);
		}
		if (StringUtils.isNotBlank(idenNumber) && Objects.isNull(visitorInfo)) {
			visitorInfo = lingLingDao.getVisitorInfoByIdenNumber(idenNumber);
		}

		NewSelectVisitorVO visitorVO = new NewSelectVisitorVO();
		if (!Objects.isNull(visitorInfo)) {
			
			// 查询访客记录(取最后最新一条数据)
			VisitorInfo lastVisitor = visitorInFoManager.getLastVisitorInfoByMobile(telephone);
			visitorVO.setIdenNumber(visitorInfo.getIdenNumber());
			visitorVO.setActiveFrom(visitorInfo.getIdenActiveFrom());
			visitorVO.setActiveTo(visitorInfo.getIdenActiveTo());
			visitorVO.setBirthday(visitorInfo.getBirthday() == null ? "" : DateHelper.formatDate(visitorInfo.getBirthday(), DateHelper.FORMATS[0]));
			visitorVO.setCardId(visitorInfo.getCardId());
			visitorVO.setCensusAddr(visitorInfo.getCensusAddr());
			visitorVO.setStart_time(visitorInfo.getCreateTime() == null ? "" : DateUtils.paseDateToLong(DateHelper.formatDate(visitorInfo.getCreateTime(), DateHelper.FORMATS[2])));
			visitorVO.setName(visitorInfo.getVisitorName());
			visitorVO.setPolice(visitorInfo.getPolice());
			visitorVO.setRace(visitorInfo.getRace());
			visitorVO.setPhoneNo(visitorInfo.getTelephone());
			if (!Objects.isNull(lastVisitor)) {
				visitorVO.setSnapshotImgName(lastVisitor.getUserHeadUrl());
				visitorVO.setHeadImgName(lastVisitor.getVisitorIdenHeadImg());
			}
		}

		visitorVO.setLlingId(LingLingUtil.getLingLingId());
		return visitorVO;
	}

	@Override
	public void uploadPhoto(String photo, String photoName, String photoType) throws Exception {

		String prePath = LingLingUtil.SNAPIMG;// 默认值为抓拍图片
		if (photoType.equalsIgnoreCase(LingLingUtil.HEADIMG)) {
			prePath = LingLingUtil.HEADIMG;
		}

		StringBuffer filePath = new StringBuffer("");
		filePath.append(File.separator)
				.append(prePath)
				.append(File.separator)
				.append(DateHelper.formatDate(new Date(), DateHelper.FORMATS[5]));

		String imageUrl = FileUploadUtils.getBase64ImageUrl(photo, photoName, filePath.toString());

		if (StringUtils.isBlank(imageUrl)) {
			// 上传图片异常
			throw new Exception("uploadPhoto 上传照片异常!");
		}
		File file = new File(FileUploadUtils.getATTACHMENT_ROOT() + imageUrl);
		if (file != null && file.length() > (500 * 1024)) {
			log.info("图片大小为 =========>:" + file.length());
			FileUploadUtils.compressPic(file);
		}
	}

	@Override
	public QrcodeInsVo createVisitorMachineQrCode(QrcodeInsInputDTO inputDTO,int methedType) {

		try {

			QrcodeInsVo vo = new QrcodeInsVo();
			// 1. 生成访客二维码
			// 1.1 获取该项目下的访客权限组
			Integer orgId=null;
			if(null!=inputDTO.getOrgnaisationId()){
				orgId=inputDTO.getOrgnaisationId();
			}else if(1==methedType){
				List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(Long.parseLong(inputDTO.getUserId()));
				orgId=list.get(0).getOrgId();
			}
			
			if(null==orgId){
				log.warn("createVisitorMachineQrCode 项目为空");
				return null;
			}
			
			
			//拿项目对应的开发者信息
			LingLingDeveloper developer=findByOrgId(orgId);
			if(null==developer){
				log.warn("createVisitorMachineQrCode 未获取到开发者信息，请联系管理员");
				return null;
			}
			
			
			List<DevicePermGroup>            groups = getDevicePermGroupByOrgId(orgId, 2);
			if (CollectionUtils.isEmpty(groups)) {
				log.warn("createVisitorMachineQrCode 当前项目未设置访客权限组=============>userId:{},orgId:{}", inputDTO.getUserId(), orgId);
				return null;
			}

			// 1.2 获取访客权限组下的全部设备
			List<LingLingDevice> devices = new ArrayList<LingLingDevice>();
			for (DevicePermGroup group : groups) {
				List<LingLingDevice> deviceList=lingLingDao.getDevicesByGroup(group.getId(), 1);
				if (!CollectionUtils.isEmpty(deviceList)) {
					devices.addAll(deviceList);
				}
			}

			if (CollectionUtils.isEmpty(devices)) {
				log.warn("createVisitorMachineQrCode 访客权限组下未绑定设备=============>userId:{},orgId:{}", inputDTO.getUserId(), orgId);
				return null;
			}
			String lingLingId ="";
			Long    startTime =null;
			Map<String, String> qrCodeMap =new HashMap<String, String>();
			//,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey
			if(1==methedType){
				// 1.3 获取设备生成的密匙
				List<String> sdkkeys = makeSdkKey(devices);
				// 1.4 获取令令id
				lingLingId = LingLingUtil.getLingLingId();
				// 1.5 二维码有效时间:结束时间减去起始时间(当前时间),转换为分钟
				startTime = System.currentTimeMillis();
				Integer endTime   = Math.toIntExact((Long.parseLong(inputDTO.getEndtime()) - startTime) / (1000 * 60));
				qrCodeMap = LingLingUtil.createVisitorQrCode(lingLingId,
						sdkkeys.toArray(new String[sdkkeys.size()]),
						Integer.parseInt(inputDTO.getEffective()),
						endTime, startTime,developer.getUrl(),developer.getSignature(),developer.getToken(),developer.getOpenToken(),developer.getStrKey());
			}else{
				Calendar nowTime = Calendar.getInstance();
				startTime=nowTime.getTimeInMillis();
				System.out.println("当前时间       -"+startTime);
				//nowTime.add(Calendar.MINUTE, 2);
				//Long endTime=nowTime.getTimeInMillis();
				
				//查证 visitorOrder.setVisitorOrderEndTime(new Date(Long.parseLong(inputDTO.getEndtime()))); 对应值是对的 line 1401
				Long endTime = Long.parseLong(inputDTO.getEndtime());//取访客机二维码截止时间 
				System.out.println("结束时间-"+endTime);
				lingLingId=LingLingUtil.getRandomValue(8);
				List<String> devicesIds=new ArrayList<String>();
				if(!CollectionUtils.isEmpty(devices)){
					for(LingLingDevice d:devices){
						if(null==d||null==d.getDeviceId()){
							continue;
						}
						devicesIds.add(d.getDeviceId()+"");
					}
				}
				qrCodeMap = LingLingUtil.createNewVisitorQrCode(lingLingId,startTime,endTime,Integer.parseInt(inputDTO.getEffective()),devicesIds
						,developer.getUrl(),developer.getSignature(),developer.getToken(),developer.getOpenToken(),developer.getStrKey());
			}
			if(null==qrCodeMap||!qrCodeMap.containsKey("codeId")||!qrCodeMap.containsKey("qrcodeKey")){
				log.warn("createVisitorMachineQrCode 获取令令返回的二维码失败");
				return null;
			}
			String codeId    = qrCodeMap.get("codeId");// 二维码id
			String qrcodeKey = qrCodeMap.get("qrcodeKey");// 二维码串
			vo.setCodeId(codeId);
			vo.setQrcodeKey(qrcodeKey);

			// 2.生成访客订单
			VisitorOrder visitorOrder = new VisitorOrder();
			visitorOrder.setVisitorOrderType(Constants.VISITOR_ORDER_TYPE_MACHINE);// 设置订单类型为访客机发起
			visitorOrder.setVisitorQrCodeId(Integer.parseInt(codeId));
			visitorOrder.setVisitorQrCode(qrcodeKey);
			visitorOrder.setVisitorOrderCreateTime(new Date());
			visitorOrder.setVisitorOrderIsEnabled(Constants.VISITOR_ORDER_STATUS);
			visitorOrder.setVisitorOrderEndTime(new Date(Long.parseLong(inputDTO.getEndtime())));
			visitorOrder.setVisitorOrderStartTime(new Date(startTime));
			visitorOrder.setVisitorOrderStatus(Integer.parseInt(Constants.VISITOR_ORDER_STATUS));
			visitorOrder.setVisitorReason(inputDTO.getAutoAim());
			visitorOrder.setVisitorToCompany(inputDTO.getAutoCompany());
			visitorOrder.setVisitorToFloor(inputDTO.getAutoFloor());
			if(StringUtils.isNotBlank(inputDTO.getUserId())){
				visitorOrder.setUserId(Long.valueOf(inputDTO.getUserId()));
			}
			
			if(StringUtils.isNotEmpty(inputDTO.getOwnerId())){
				visitorOrder.setVisitorUserId(Integer.valueOf(inputDTO.getOwnerId()));
			}			
			
			visitorOrder.setVisitorToOrgId(orgId);
			visitorOrder = (VisitorOrder) visitorInFoManager.save(visitorOrder);

			vo.setVisitorId(visitorOrder.getVisitorOrderId()+"");
			vo.setVisitorType("0");
			vo.setReason("");
			// 3.生成访客记录信息
			VisitorInfo visitorInfo = new VisitorInfo();
			visitorInfo.setVisitorOrderId(visitorOrder.getVisitorOrderId());
			visitorInfo.setVisitorPhone(inputDTO.getTelephone());
			visitorInfo.setVisitorName(inputDTO.getName());
			visitorInfo.setVisitorStartTime(new Date(startTime));
			visitorInfo.setVisitorEndTime(new Date(Long.parseLong(inputDTO.getEndtime())));
			visitorInfo.setVisitorCreateTime(new Date());
			visitorInfo.setVisitorIsEnabled(Constants.VISITOR_ORDER_STATUS);
			visitorInfo.setVisitorStatus(Constants.VISITOR_TWO_STATUS);
			visitorInfo.setVisitorType("0");

			// 照片名称为36位长度的英文字符串;不设置图片必填的时候,会传'暂无图片';
			if (StringUtils.isNotBlank(inputDTO.getSnapshotImgName()) &&
					inputDTO.getSnapshotImgName().length() > 20) {
				visitorInfo.setUserHeadUrl(inputDTO.getSnapshotImgName());
			}
			if (StringUtils.isNotBlank(inputDTO.getHeadImgName()) &&
					inputDTO.getHeadImgName().length() > 20) {
				visitorInfo.setVisitorIdenHeadImg(inputDTO.getHeadImgName());
			}

			visitorInFoManager.save(visitorInfo);

			// 4.保存/修改(完善)访客信息
			LingLingVisitorInfo visitor = null;
			if (StringUtils.isNotBlank(inputDTO.getTelephone())) {
				visitor = lingLingDao.getVisitorInfoByTelephone(inputDTO.getTelephone());
			}
			if (Objects.isNull(visitor) && StringUtils.isNotBlank(inputDTO.getIdenNumber())) {
				visitor = lingLingDao.getVisitorInfoByIdenNumber(inputDTO.getIdenNumber());
			}

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

			if (StringUtils.isNotBlank(inputDTO.getBirthday())) {
				// 访客生日格式解析模板未确定,先注释,需要的时候放开
//                visitor.setBirthday(DateHelper.parseToDate(inputDTO.getBirthday(), DateHelper.FORMATS[0]));
			}
			visitor.setCardId(inputDTO.getCardId());
			visitor.setCensusAddr(inputDTO.getCensusAddr());
			visitor.setCreateTime(new Date());
			visitor.setHeadImgName(inputDTO.getHeadImgName());
			visitor.setIdenActiveFrom(inputDTO.getActiveFrom());
			visitor.setIdenActiveTo(inputDTO.getActiveTo());
			visitor.setIdenNumber(inputDTO.getIdenNumber());
			visitor.setPolice(inputDTO.getPolice());
			visitor.setRace(inputDTO.getRace());
			visitor.setSnapshotImgName(inputDTO.getSnapshotImgName());
			visitor.setTelephone(inputDTO.getTelephone());
			visitor.setVisitorName(inputDTO.getName());

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

			return vo;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("createVisitorMachineQrCode 生成访客机二维码异常=====>" + e.getMessage());
			return null;
		}
	}

	@Override
	public List<GetCompanyVO> getCompanyList(Integer orgId) {

		List<GetCompanyVO> list = new ArrayList<>();
		try {
			List<VirtualArchitecture> virtualArchitectureList = propertyManager.getVirtualArchitectureList(orgId);
			if (!CollectionUtils.isEmpty(virtualArchitectureList)) {
				for (VirtualArchitecture vir : virtualArchitectureList) {
					GetCompanyVO vo = new GetCompanyVO();
					vo.setFloorName(vir.getName());
					// 获取企业所在楼层;如果存在多楼层则取一个;如果无信息,默认1;
					String floorIds = vir.getFloorIds();
					if (StringUtils.isNotBlank(floorIds)) {
						if (floorIds.contains(","))
							floorIds = floorIds.replaceAll(",", ";");
						// 获取楼层
						if(floorInfoManager.exists(Integer.valueOf(floorIds.split(";")[0]))){
							FloorInfo floorInfo = floorInfoManager.get(Integer.valueOf(floorIds.split(";")[0]));
							vo.setOnFloor(floorInfo.getName());
						}
				
					} else {
						vo.setOnFloor("1");
					}
					list.add(vo);
				}
			}
		} catch (Exception e) {
			log.error("getCompanyList error:{}======>", e.getMessage());
		}
		return list;
	}
	
	
	@Override
	public List<GetNewCompanyVO> getNewCompanyList(Integer orgId) {

		List<GetNewCompanyVO> list = new ArrayList<>();
		try {
			List<VirtualArchitecture> virtualArchitectureList = propertyManager.getVirtualArchitectureList(orgId);
			if (!CollectionUtils.isEmpty(virtualArchitectureList)) {
				for (VirtualArchitecture vir : virtualArchitectureList) {
					GetNewCompanyVO vo = new GetNewCompanyVO();
					vo.setOrgId(String.valueOf(vir.getId()));
					vo.setOrgName(vir.getName());
					// 获取企业所在楼层;如果存在多楼层则取一个;如果无信息,默认1;
					String floorIds = vir.getFloorIds();
					if (StringUtils.isNotBlank(floorIds)) {
						if (floorIds.contains(","))
							floorIds = floorIds.replaceAll(",", ";");
						// 获取楼层
						if(floorInfoManager.exists(Integer.valueOf(floorIds.split(";")[0]))){
							FloorInfo floorInfo = floorInfoManager.get(Integer.valueOf(floorIds.split(";")[0]));
							vo.setFloor(floorInfo.getName());
						}
				
					} else {
						vo.setFloor("1");
					}
					list.add(vo);
				}
			}
		} catch (Exception e) {
			log.error("getCompanyList error:{}======>", e.getMessage());
		}
		return list;
	}
	
	@Override
	public void sendQRCode(String telephone, String codeId,int methedType,Integer orgId) throws Exception {
		// 根据二维码ID查询访客订单信息
		VisitorOrder visitorOrder =null;;
		if(1==methedType){
			visitorOrder = lingLingDao.getMachineVisitorInfo(codeId);//根据二维码id查询
			if(null==visitorOrder||null==visitorOrder.getVisitorOrderId()||null==visitorOrder.getUserId()){
				return;
			}
			// 访客机登录用户id,用于获取项目信息,发送短息
			Long                             userId = visitorOrder.getUserId();
			List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(userId);
			if(null==list||list.size()<=0){
				return;
			}
			orgId  = list.get(0).getOrgId();
		}else{
			visitorOrder = lingLingDao.getMachineVisitorByQr(codeId);//根据二维码字段查询
		}
		
		if(null==visitorOrder||null==visitorOrder.getVisitorOrderId()){
			return;
		}
		
		

		// 根据访客订单id查询访客信息
		List<VisitorInfo> visitorInfoList = visitorInFoManager.getVisitorInfoList(visitorOrder.getVisitorOrderId());
		byte[]            encryptResult   = AesUtils.encrypt("id=" + visitorInfoList.get(0).getVisitorId(), "palmnest");
		String            encryptStr      = AesUtils.parseByte2HexStr(encryptResult);
		String            serverUrl       = Constants.SERVER_ADDRESS + "/wechat/visitor/getVisitorInfo?" + encryptStr;

		// 定义短信内容
		String content = "点击获取访客二维码\n" + serverUrl;

		// 发送短信
		smsAuthCodeManager.smsSendByOrgId(orgId + "", content, telephone, null, CodeConstants.SMS_VISITOR_TYPE);
	}

	@Override
	public VisitorInfoVO getVisitorInfo(Integer visitorId) {

		VisitorInfoVO vo = new VisitorInfoVO();
		vo.setVisitorId(visitorId);

		// 获取访客信息
		VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfo(visitorId);
		// 获取访客订单信息
		VisitorOrder visitorOrder = visitorInFoManager.getVisitorOrder(visitorInfo.getVisitorOrderId());
		// 获取访客基本信息
		LingLingVisitorInfo lingLingVisitorInfo = lingLingDao.getVisitorInfoByTelephone(visitorInfo.getVisitorPhone());

		vo.setNodeStr(visitorInfo.getNodeStr());
		vo.setLeaveTime(visitorInfo.getLeaveTime());
		vo.setVisitorName(visitorInfo.getVisitorName());// 访客姓名
		vo.setVisitorCompany(visitorInfo.getVisitorCompanyName());// 来访人公司
		vo.setVisitorTelephone(visitorInfo.getVisitorPhone());// 来访人手机号码
		vo.setVisitCode(visitorInfo.getVisitorPassword());// 访客码
		vo.setVisitTime(DateHelper.formatDate(visitorInfo.getVisitorStartTime(), DateHelper.FORMATS[0]));// 来访时间
		if (visitorOrder.getVisitorUserId() != null) {
			vo.setInterviewee(appUserManager.get(visitorOrder.getVisitorUserId()).getUserName());// 受访人
		}
		vo.setVisitReason(visitorOrder.getVisitorReason());// 到访目的
		vo.setVisitFloor(visitorOrder.getVisitorToFloor());// 访问楼层
		vo.setVisitToCompany(visitorOrder.getVisitorToCompany());// 到访公司

		// 获取日期格式
		String dateStr = DateHelper.formatDate(visitorInfo.getVisitorStartTime(), DateHelper.FORMATS[5]);
		if ("4".equalsIgnoreCase(visitorOrder.getVisitorOrderType())) {
			vo.setVisitorImage(IMAGE_URL + "/" + LingLingUtil.SNAPIMG + "/" + dateStr + "/" + visitorInfo.getUserHeadUrl() + ".jpeg");// 访客照片;令令访客机;
		} else {
			// 获取图片对象
			List<UserImageInfo> userImageList = visitorInFoManager.getUserImageInfo(visitorInfo.getVisitorId(), "2");
			if (!CollectionUtils.isEmpty(userImageList)) {
				vo.setVisitorImage(userImageList.get(0).getImageFaceUrl());// 访客照片
			}
		}

		if (!Objects.isNull(lingLingVisitorInfo)) {
			vo.setIdenNumber(lingLingVisitorInfo.getIdenNumber());// 身份证号码
			vo.setCardId(lingLingVisitorInfo.getCardId());// 身份证卡号
			vo.setIdenActiveTo(lingLingVisitorInfo.getIdenActiveTo());//
			vo.setIdenActiveFrom(lingLingVisitorInfo.getIdenActiveFrom());
			vo.setCreateTime(DateHelper.formatDate(lingLingVisitorInfo.getCreateTime(), DateHelper.FORMATS[0]));
			vo.setPolice(lingLingVisitorInfo.getPolice());
			vo.setHeadImgName(IMAGE_URL + "/" + LingLingUtil.HEADIMG + "/" + dateStr + "/" + visitorInfo.getVisitorIdenHeadImg() + ".jpeg");// 身份证头像
			vo.setRace(lingLingVisitorInfo.getRace());
			vo.setCensusAddr(lingLingVisitorInfo.getCensusAddr());
		}
		log.info("visitorOrder-visitorOrder:{}",JsonUtils.toJson(visitorOrder));
		if(null != visitorOrder && null != visitorOrder.getVisitorOrderId() && StringUtils.isNotEmpty(visitorOrder.getVisitorQrCode())){
			List<VisitorPassRecordVo> passList = visitorInFoManager.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_QRCODE);
			if(CollectionUtils.isEmpty(passList) && StringUtils.isNotEmpty(visitorOrder.getLinglingId())){
				passList = visitorInFoManager.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_LINGLINGID);
			}
			vo.setPassList(passList);
		}else if(null != visitorOrder  && null != visitorOrder.getVisitorOrderId() && StringUtils.isNotEmpty(visitorOrder.getLinglingId())){
			List<VisitorPassRecordVo> passList = visitorInFoManager.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_LINGLINGID);
			if(CollectionUtils.isEmpty(passList) && StringUtils.isNotEmpty(visitorOrder.getVisitorQrCode())){
				passList = visitorInFoManager.getVisitorPassInfo(visitorOrder.getVisitorOrderId(),CodeConstants.PASS_QRCODE);
			}
			vo.setPassList(passList);
		}
		return vo;
	}

	@Override
	public DevicePermGroup getByUserInfo(Integer orgId) {
		return lingLingDao.getByUserInfo(orgId);
	}

	@Override
	public List<String> getDateInfoByOrgId(Integer orgId) {
		SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM-dd");
		Calendar         now   = Calendar.getInstance();
		String           year  = now.get(Calendar.YEAR) + "";
		String           month = (now.get(Calendar.MONTH) + 1) + "";
		String           today = sdf.format(new Date());
		String           type  = getType(orgId);
		int              m     = (Integer.parseInt(month) + 1);
		List<String>     list  = getDateInfo(today, year, m + "", type);
		return list;
	}

	private List<String> getDateInfo(String today, String year, String month, String type) {
		SimpleDateFormat   sdf      = new SimpleDateFormat("yyyy-MM-dd");
		List<String>       list     = new ArrayList<String>();
		List<DateTypeInfo> dateList = dateTypeInfoManager.getDateTypeList(year, month, type, today);
		if (null == dateList || dateList.size() <= 0) {
			return null;
		}
		for (DateTypeInfo dateInfo : dateList) {
			String date = sdf.format(dateInfo.getDate());
			if (StringUtils.isBlank(date)) {
				continue;
			}
			list.add(date);
		}
		return list;
	}

	private String getType(Integer orgId) {
		DevicePermGroup group    = getByUserInfo(orgId);
		StringBuilder   sb       = new StringBuilder("");
		List<Integer>   typeList = new ArrayList<Integer>();
		if (null != group && 1 == group.getIsUseLimit()) {
			if (1 == group.getIsHoliday()) {
				//节假日
				typeList.add(1);
			}
			if (1 == group.getIsWeek()) {
				//周末
				typeList.add(3);
			}
			if (1 == group.getIsWorkday()) {
				//工作日
				typeList.add(0);
				typeList.add(2);
			}
		}
		if (null != typeList && typeList.size() > 0) {
			for (int i = 0; i < typeList.size(); i++) {
				Integer type = typeList.get(i);
				sb.append(type);
				sb.append(",");
			}
		}
		String res = sb.toString();
		if (StringUtils.isNotBlank(res) && ",".equals(res.substring(res.length() - 1, res.length()))) {
			res = res.substring(0, res.length() - 1);
		}
		return res;
	}

	public static void main(String[] args) {
		String visitorInfoList = "11";
		System.out.println(Objects.isNull(visitorInfoList));
		System.out.println(Objects.nonNull(visitorInfoList));
	}

	@Override
	public void saveLingLingLog(LingLingLog log) {
		
		lingLingDao.save(log);
	}

	@Override
	public LingLingDevice getByDeviceCode(String deviceCode) {
		return lingLingDao.getByDeviceCode(deviceCode);
	}
	
//	public int getMethedType(String orgId){
//		int methedType=2;
//		String lingOrgs=LingLingUtil.lingOrgs;
//		if(StringUtils.isNotBlank(lingOrgs)){
//			String [] arr=lingOrgs.split(",");
//			if(null!=arr&&arr.length>0){
//				int index=Arrays.binarySearch(arr, orgId);
//				if(index>=0){
//					methedType=1;
//				}
//			}
//		}
//		return methedType;
//	}
	
	public int getMethedType(String orgId){
		int methedType=2;
		LingLingDeveloper developer=findByOrgId(Integer.parseInt(orgId));
		if(null==developer){
			return methedType;
		}
		if(null==developer.getIsNew()||1==developer.getIsNew().intValue()){
			return methedType;
		}else{
			return 1;
		}
	}

	@Override
	public String updateUserPermNextNew(String userIds,Integer addUserId) {
		int code=0;
		try {
			Integer groupId=null;
			List<Integer> groupIds=lingLingDao.getGroupIds(userIds);
			log.info("updateUserPermNextNew-groupIds:"+JsonUtils.toJson(groupIds));
			if(!CollectionUtils.isEmpty(groupIds)){
				for (Integer id : groupIds) {
					log.info("updateUserPermNextNew-addUserId:"+JsonUtils.toJson(addUserId));
					log.info("updateUserPermNextNew-groupId:"+JsonUtils.toJson(id));
					int count=lingLingDao.getGroupIdsByGroupAndUser(addUserId,id);
					log.info("updateUserPermNextNew-count:"+JsonUtils.toJson(count));
					if(count>0){
						lingLingDao.deleteUserGroup(addUserId, Long.parseLong(id.toString()));
					}
					groupId=id;
//					lingLingDao.saveUserGroup(addUserId, id+"");
				}
				if(null == groupId){
					code=4;//该用户已有分组
					return "该用户已有分组";
				}
				String userIdList=addUserId+"";
				List<AppUser> appUsers=appUserManager.getAppUserByIds(userIdList);
				log.info("updateUserPermNextNew-appUsers:"+JsonUtils.toJson(appUsers));
				if(CollectionUtils.isEmpty(appUsers)){
					code=2;//获取不到用户
					return "获取不到用户信息";
				}
				
				AppUser user=appUsers.get(0);
				int methedType=getMethedType(user.getOrganizationId()+"");
				log.info("updateUserPermNextNew-methedType:"+JsonUtils.toJson(methedType));
				//设置linglingId
				String lingLingIds =setUserLinglingId(methedType,appUsers);
				log.info("updateUserPermNextNew-lingLingIds:"+JsonUtils.toJson(lingLingIds));
				//设置权限，只有新的会需要调用
				if(2==methedType){
					String res=saveUserPerm(groupId,lingLingIds,user.getOrganizationId(),2);
					if(StringUtils.isBlank(res)){
						lingLingDao.saveUserGroup(addUserId, groupId+"");
						code=1;
					}
				}else if(1 == methedType){
					code=1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("updateUserPermNextNew error:{}=====>", e.getMessage());
			code=3;//系统异常
			return "系统异常，添加失败:"+e.getMessage();
		}
		return "";
		
	}

	@Override
	public LingLingDeveloper findByOrgId(Integer orgId) {
		LingLingDeveloper developer=new LingLingDeveloper();
		if(null==orgId){
			log.info("LingLingDeveloper-findByOrgId-1");
			//项目为空时代表获取默认的设置信息
			developer=findDefault();
			return developer;
		}
		String orgJson=baseRedisService.get(CodeConstants.LINGLING_DEVELPER+"_"+orgId);
		if(StringUtils.isNotBlank(orgJson)){
			log.info("LingLingDeveloper-findByOrgId-2");
			log.info("LingLingDeveloper-findByOrgId-orgJson:"+orgJson);
			developer=JSONObject.parseObject(orgJson, LingLingDeveloper.class);
			return developer;
		}
		if(checkHaveOrgId(orgId)){
			log.info("LingLingDeveloper-findByOrgId-3");
			//如果项目是在数据库中存在的，就拿配置的；如果不存在的话，直接拿DEF;
			developer=lingLingDao.findByOrgId(orgId);
			if(null==developer){
				log.info("LingLingDeveloper-findByOrgId-4");
				//没有拿到的情况下用默认的开发者信息(默认的为超级前台开发者信息)
				developer=findDefault();
				baseRedisService.set(CodeConstants.LINGLING_DEVELPER+"_"+orgId, JsonUtils.toJson(developer));
				return developer;
			}
			log.info("LingLingDeveloper-findByOrgId-5");
			baseRedisService.set(CodeConstants.LINGLING_DEVELPER+"_"+orgId, JsonUtils.toJson(developer));
			return developer;
		}
		log.info("LingLingDeveloper-findByOrgId-6");
		developer=findDefault();
		baseRedisService.set(CodeConstants.LINGLING_DEVELPER+"_"+orgId, JsonUtils.toJson(developer));
		return developer;
	}
	
	private LingLingDeveloper findDefault(){
		LingLingDeveloper developer=new LingLingDeveloper();
		String allJson=baseRedisService.get(CodeConstants.LINGLING_DEVELPER+"_DEF");
		if(StringUtils.isNotBlank(allJson)){
			log.info("LingLingDeveloper-findDefault-allJson:"+allJson);
			developer=JSONObject.parseObject(allJson, LingLingDeveloper.class);
			return developer;
		}
		developer=lingLingDao.findByOrgId(null);
		baseRedisService.set(CodeConstants.LINGLING_DEVELPER+"_DEF", JsonUtils.toJson(developer));
		return developer;
	}
	
	private boolean checkHaveOrgId(Integer orgId){
		List orgIds=new ArrayList();
		String orgIdsJson=baseRedisService.get(CodeConstants.LINGLING_DEVELPER+"_ORGIDS");
		if(StringUtils.isNotBlank(orgIdsJson)){
			log.info("LingLingDeveloper-checkHaveOrgId-orgIdsJson:"+orgIdsJson);
			orgIds=JSONArray.parseArray(orgIdsJson);
		}else{
			orgIds=lingLingDao.findOrgIds();
			baseRedisService.set(CodeConstants.LINGLING_DEVELPER+"_ORGIDS", JsonUtils.toJson(orgIds));
		}
		log.info("LingLingDeveloper-checkHaveOrgId-orgIds:"+JsonUtils.toJson(orgIds));
		log.info("LingLingDeveloper-checkHaveOrgId-orgId:"+orgId);
		log.info("LingLingDeveloper-checkHaveOrgId-contains:"+orgIds.contains(orgId));
		if(orgIds.contains(orgId)){
			return true;
		}
		return false;
	}

	@Override
	public String getLinglingIdsByGroupId(Long groupId) {
		return lingLingDao.getLinglingIdsByGroupId(groupId);
	}

	@Override
	public Map<String, Object> getUserGroupInfo(Integer userId) {
		return lingLingDao.getUserGroupInfo(userId);
	}

	@Override
	public String getDeviceNamesByGroupId(String groupId) {
		// TODO 自动生成的方法存根
		return lingLingDao.getDeviceNamesByGroupId(groupId);
	}

	@Override
	public void savePermGroupDevice(Long devicePermGroupId, Long deviceId) {
		lingLingDao.savePermGroupDevice(devicePermGroupId,deviceId);
		
	}

	@Override
	public DevicePermGroup getGroupByUserId(Integer userId) {
		return lingLingDao.getGroupByUserId(userId);
	}

	@Override
	public LingLingCard getCardByUserId(Integer userId) {
		// TODO Auto-generated method stub
		return lingLingDao.getCardByUserId(userId);
	}

	@Override
	public void saveUserPermAsync(DevicePermGroup group) {
//		int methedType=getMethedType(group.getOrgId().toString());
//		if(2==methedType){
//			Integer groupId=Integer.parseInt(group.getId().toString());
//			String lingLingIds=getLinglingIdsByGroupId(group.getId());
//			if(StringUtils.isBlank(lingLingIds)){
//				return;
//			}
//			List<String> list=StringUtil.indexStr(lingLingIds);
//			if(CollectionUtils.isEmpty(list)){
//				return;
//			}
//			long beginTime=System.currentTimeMillis();
//			for(int i=0;i<list.size();i++){
//				saveUserPerm(groupId, list.get(i),group.getOrgId());
//			}
//			long endTime=System.currentTimeMillis();
//			log.info("批量设置令令权限时间:"+(endTime-beginTime));
//			lingLingDao.updatePermGroupUser(group.getId(),"",0);
//		}
	}

	@Override
	public int updatePermGroupUser(Long groupId, String userIds, int type) {
		return lingLingDao.updatePermGroupUser(groupId, userIds, type);
	}

	@Override
	public String getDeviceIdsByGroupId(Integer groupId) {
		// TODO Auto-generated method stub
		return lingLingDao.getDeviceIdsByGroupId(groupId);
	}

	@Override
	public AppResultDto exportPassHistory(Map<String, String> params) {
		log.info("begin exportPassHistory/params:{}",JsonUtils.toJson(params));
		HSSFWorkbook wb = new HSSFWorkbook();
		List<Map<String,Object>> mapList=lingLingDao.getExPassHistory(params);
		log.info("begin exportPassHistory/mapList:{}",JsonUtils.toJson(mapList));
		
		if (!CollectionUtils.isEmpty(mapList)) {
			for (Map<String, Object> map : mapList) {
				StringBuilder str=new StringBuilder("");
				if(null!=map&&map.containsKey("deviceType")&&null!=map.get("deviceType")){
					String deviceType = map.get("deviceType").toString();
					//闸机、梯控、门禁
					if("1".equals(deviceType)){
						str.append("闸机").append("  ");
					}else if("2".equals(deviceType)){
						str.append("梯控").append("  ");
					}else if("3".equals(deviceType)){
						str.append("门禁").append("  ");
					}else{
						str.append(deviceType).append("  ");
					}
				}
				if(null!=map&&map.containsKey("deviceId")&&null!=map.get("deviceId")){
					String deviceId = map.get("deviceId").toString();
					str.append(deviceId).append("  ");
				}
				if(null!=map&&map.containsKey("deviceName")&&null!=map.get("deviceName")){
					String deviceName = map.get("deviceName").toString();
					str.append(deviceName).append("  ");
				}
				map.put("passInfo", str.toString());
				if(null!=map&&map.containsKey("type")&&null!=map.get("type")){
					Integer type = Integer.parseInt(map.get("type").toString());
					if(1 == type && 3 == type){
						map.put("typeStr", "员工");
					}else{
						map.put("typeStr", "访客");
					}
					
					if (type.equals(2) &&map.containsKey("userName") &&null == map.get("userName")) {
						// 通行记录为访客通行且手机号为空,说明是访客机访客,姓名与手机号需要另行去填充,根据通行二维码code
						if(map.containsKey("qrcodeKey")&&null!=map.get("qrcodeKey")){
							VisitorInfo visitorInfo = visitorInFoManager.getVisitorInfoByQrCode(map.get("qrcodeKey").toString());
							if (null != visitorInfo) {
								map.put("userName", visitorInfo.getVisitorName());
								map.put("mobile", visitorInfo.getVisitorPhone());
								map.put("userInfo", visitorInfo.getVisitorName() +" " + visitorInfo.getVisitorPhone());
							}
						}
					}
				}
				
				Date openTime = (Date) map.get("openTime");
				map.put("openTime", DateHelper.formatDate(openTime, DateHelper.DATE_TIME_STRING));
				
				if(null!=map&&map.containsKey("passType")&&null!=map.get("passType")){
					String passType = map.get("passType").toString();
					//2-令令开门;3-访客;4-考拉
					if("2".equals(passType)){
						map.put("passTypeStr", "令令开门");
					}else if("3".equals(passType)){
						map.put("passTypeStr", "访客");
					}else if("4".equals(passType)){
						map.put("passTypeStr", "考拉");
					}else{
						map.put("passTypeStr", passType);
					}
				}
			}
		}
		
		String path=setPath("upload/PassHistoryExcel.xls");
		log.info("begin exportPassHistory/path:"+path);
		try {
			if(mapList!=null&&mapList.size()>0){
				String sheetName="通行记录";
				File file =new File( new ExcelUtils().getPath(path));
				String[] titles={"项目","通行人(姓名、手机号)","通行设备（类型、ID、名称）","通行时间","通行方式","用户类型","卡号"};
				String [] fieldNames={"orgName","userInfo","passInfo","openTime","passTypeStr","typeStr","cardUid"};
				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;
	}

	/**
	 * 获取通行趋势报表
	 * @param orgId
	 * @param type
	 * @param model
	 * @param date
	 * @param orgName
	 * @return
	 */
	@Override
	public List<LinglingPassDto> getPassList(Integer orgId, Integer type, Integer model, String date, String orgName) {
		if(StringUtils.isEmpty(orgName)){
			TbOrganization org=organizationDao.getOrganizationById(orgId);
			if(null != org){
				orgName=org.getName();
			}
		}
		List<LinglingPassDto> list=new ArrayList<LinglingPassDto>();
		if(1 == model.intValue()){
			list=getDayPass(orgId, type, date, orgName);
		}else if(2 == model.intValue()){
			list=getMonthPass(orgId, type, date, orgName);
		}
		return list;
	}
	
	/**
	 * 获取日趋势报表数据
	 * @param orgId
	 * @param type
	 * @param date
	 * @param orgName
	 * @return
	 */
	private List<LinglingPassDto> getDayPass(Integer orgId, Integer type,String date, String orgName){
		List<LinglingPassDto> list=new ArrayList<LinglingPassDto>();
		List<String> timeList=DateUtils.getTimeMin(30);
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("orgId", orgId);
		params.put("type", type);
		params.put("date", date);
		List<Map<String, Object>> sqlList=lingLingDao.getPassDate(params);
		if(CollectionUtils.isEmpty(sqlList)){
			return list;
		}
		for(String s:timeList){
			LinglingPassDto dto=new LinglingPassDto();
			dto.setOrgName(orgName);
			dto.setTime(s);
			dto.setCount(0);
			for(int i=0;i<sqlList.size();i++){
				Map<String, Object> map=sqlList.get(i);
				if(null != map && map.containsKey("time") && s.equals(map.get("time"))){
					dto.setCount(Integer.parseInt(map.get("count").toString()));
				}
			}
			list.add(dto);
		}
		return list;
	}
	
	/**
	 * 获取月趋势报表数据
	 * @param orgId
	 * @param type
	 * @param date
	 * @param orgName
	 * @return
	 */
	private List<LinglingPassDto> getMonthPass(Integer orgId, Integer type,String date, String orgName){
		List<LinglingPassDto> list=new ArrayList<LinglingPassDto>();
		String [] sp=date.split("-");
		if(null == sp || sp.length <= 0){
			return list;
		}
		int year=Integer.parseInt(sp[0]);
		int month=Integer.parseInt(sp[1]);
		List<String> timeList=DateUtils.getMonthFullDay(year, month);
		Map<String,Object> params=new HashMap<String, Object>();
		params.put("orgId", orgId);
		params.put("type", type);
		params.put("date", date);
		List<Map<String, Object>> sqlList=lingLingDao.getPassMonth(params);
		if(CollectionUtils.isEmpty(sqlList)){
			return list;
		}
		for(String s:timeList){
			LinglingPassDto dto=new LinglingPassDto();
			dto.setOrgName(orgName);
			dto.setTime(s);
			dto.setCount(0);
			for(int i=0;i<sqlList.size();i++){
				Map<String, Object> map=sqlList.get(i);
				if(null != map && map.containsKey("time") && s.equals(map.get("time"))){
					dto.setCount(Integer.parseInt(map.get("count").toString()));
				}
			}
			list.add(dto);
		}
		return list;
	}
	/**
	 * 导出通行趋势报表
	 * @param orgId
	 * @param type
	 * @param model
	 * @param date
	 * @param orgName
	 * @return
	 */
	@Override
	public AppResultDto exportPassList(Integer orgId, Integer type, Integer model, String date, String orgName) {
		HSSFWorkbook wb = new HSSFWorkbook();
		List<LinglingPassDto> mapList=getPassList(orgId, type, model, date, orgName);
		log.info("begin exportPassList/mapList:{}",JsonUtils.toJson(mapList));
		String path=setPath("upload/PassModelExcel.xls");
		log.info("begin exportPassList/path:"+path);
		try {
			if(!CollectionUtils.isEmpty(mapList)){
				String sheetName="通行数据分析";
				File file =new File( new ExcelUtils().getPath(path));
				if(1 == model.intValue()){
					String[] titles={"项目","时段","通行人数"};
					String [] fieldNames={"orgName","time","count"};
					ExcelUtils.exportExcel(file,wb, sheetName, mapList, titles, fieldNames);
				}else if(2 == model.intValue()){
					String[] titles={"项目","日期","通行人数"};
					String [] fieldNames={"orgName","time","count"};
					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);
	}
	
}
