package com.palmnest.webapp.controller.lingling;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
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.WebPageResultDto;
import com.palmnest.application.dto.input.LingLingScanVisitorInfo;
import com.palmnest.application.dto.input.LingLingVisitorMachineInputDto;
import com.palmnest.application.dto.output.DevicePermGroupOutDto;
import com.palmnest.application.dto.output.VisitorInfoVO;
import com.palmnest.application.dto.output.lingling.LingLingDeviceOutDto;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.lingling.DevicePermGroup;
import com.palmnest.model.lingling.LingLingDeveloper;
import com.palmnest.model.lingling.LingLingDevice;
import com.palmnest.service.MeetingService;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.VisitorInFoManager;
import com.palmnest.service.estateserve.release.VisitorInFoService;
import com.palmnest.service.lingling.manager.LingLingManager;
import com.palmnest.service.lingling.service.LingLingService;
import com.palmnest.service.org.OrganizationService;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

import java.util.*;

/**
 * @Author 黄笑天
 * @Description 令令开门相关接口
 * @Date 2018/12/5 10:54
 **/
@Slf4j
@RequestMapping(value = "/lingling")
@Controller
public class LingLingController extends BaseFormController {

	@Autowired
	private LingLingService lingLingService;

	@Autowired
	private LingLingManager    lingLingManager;
	@Autowired
	private VisitorInFoManager visitorInFoManager;
	@Autowired
	private UserManager        userManager;
	@Autowired
	private VisitorInFoService visitorInFoService;
	@Autowired
	private MeetingService     meetingService;

	@Autowired
	OrganizationService organizationService;
	
	@Autowired
	private AppUserManager     appUserManager;

	/**
	 * 处理令令接口返回参数信息
	 *
	 * @param result 待处理的结果字符串
	 * @return 处理后的结果
	 */
	public AppResultDto handleResult(String result) {

		Object              responseResult = "fail";
		Map<String, Object> obj;
		try {
			obj = JSONObject.parseObject(result, Map.class);
			String statusCode = (String) obj.get("statusCode");
			responseResult = obj.get("responseResult");

			if ("1".equalsIgnoreCase(statusCode)) {
				return AppResultUtil.createSuccesDto(responseResult);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("LingLingController handleResult 参数处理异常========>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", responseResult.toString());
	}

	/**
	 * 添加令令设备
	 *
	 * @param request
	 */
	@RequestMapping(value = "/addDevice")
	@ResponseBody
	public AppResultDto addDevice(HttpServletRequest request) {

		String deviceName = request.getParameter("deviceName");
		String deviceCode = request.getParameter("deviceCode");
		String orgId      = request.getParameter("orgId");
		String deviceType = request.getParameter("deviceType");
		String address    = request.getParameter("address");

		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户

		if (StringUtils.isAnyBlank(deviceCode, deviceName, orgId, deviceType, address)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}
		
		LingLingDevice deviceNo=lingLingManager.getByDeviceCode(deviceCode);

		if(null!=deviceNo){
			return AppResultUtil.createErrorDto("100", "设备码已存在，无法新增");
		}

		log.info("LingLingController addDevice:deviceName{},deviceCode{}", deviceName, deviceCode);
		int methedType=lingLingManager.getMethedType(orgId);
		String url ="";
		
//		if(1==methedType){
//			url = LingLingUtil.preUrl + "/device/addDevice/" + LingLingUtil.openToken;
//		}else{
//			url = LingLingUtil.newPreUrl+"/device/addDevice/" + LingLingUtil.newOpenToken;
//		}
		//拿项目对应的开发者信息
		LingLingDeveloper developer=lingLingManager.findByOrgId(Integer.parseInt(orgId));
		if(null==developer){
			return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
		}
		
		url=developer.getUrl()+ "/device/addDevice/" + developer.getOpenToken();
		
		LingLingDevice device = new LingLingDevice();
		device.setDeviceCode(deviceCode);
		device.setDeviceName(deviceName);
		device.setCreator(user.getId());
		device.setOrgId(Integer.parseInt(orgId));
		device.setDeviceType(Integer.parseInt(deviceType));
		device.setAddress(address);
		device.setMethedType(methedType);
		device.setInOutType(1);
		return lingLingManager.saveDevice(device, url,developer);
	}


	/**
	 * 本地数据库 修改 令令设备信息
	 *
	 * @param request
	 */
	@RequestMapping(value = "/updateLocalDevice")
	@ResponseBody
	public AppResultDto updateLocalDevice(@ModelAttribute("lingLingDevice") LingLingDevice device, HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("UserCache");
		if (null == device.getDeviceId() || null == device.getDeviceType() || StringUtils.isBlank(device.getAddress())
				|| null == device.getOrgId() || StringUtils.isBlank(device.getDeviceName())) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		LingLingDevice byDeviceId = lingLingManager.getByDeviceId(device.getDeviceId(),device.getOrgId());
		if (byDeviceId == null) {
			return AppResultUtil.createErrorDto("100", "没有该设备");
		}
		byDeviceId.setModify(user.getId());
		byDeviceId.setModifyTime(new Date());
		byDeviceId.setAddress(device.getAddress());
		byDeviceId.setRemark(device.getRemark());
		byDeviceId.setDeviceType(device.getDeviceType());
		byDeviceId.setDeviceName(device.getDeviceName());
		
		if(1==byDeviceId.getMethedType().intValue()&&StringUtils.isBlank(byDeviceId.getSdkKey())){
			lingLingManager.saveDeviceSdk(device);
		}

		try {
			lingLingManager.updateModel(byDeviceId);
			return AppResultUtil.createSuccesDto("修改成功");
		} catch (Exception e) {
			log.error("LingLingController updateLocalDevice============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "修改失败");
	}

	/**
	 * 删除设备
	 *
	 * @param request
	 */
	@RequestMapping(value = "/delDevice")
	@ResponseBody
	public AppResultDto delDevice(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		String deviceId = request.getParameter("deviceId");
		String orgId      = request.getParameter("orgId");
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		if (StringUtils.isBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目Id不能为空");
		}
		String [] arr=orgId.split(",");
		if (arr.length > 1) {
			return AppResultUtil.createErrorDto("100", "请指定项目");
		}
		
		if (StringUtils.isBlank(deviceId)) {
			return AppResultUtil.createErrorDto("100", "设备id号为空");
		}
		log.info("LingLingController delDevice:deviceId{}", deviceId);
		String url ="";
		return lingLingManager.delDevice(Integer.parseInt(deviceId), url,Integer.parseInt(orgId));
	}

	/**
	 * 获取设备信息
	 *
	 * @param request
	 */
	@RequestMapping(value = "/getDeviceInfo")
	@ResponseBody
	public AppResultDto getDeviceInfo(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		String deviceId = request.getParameter("deviceId");
		String orgId = request.getParameter("orgId");// 项目id
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		if (StringUtils.isBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目Id不能为空");
		}
		String [] arr=orgId.split(",");
		if (arr.length > 1) {
			return AppResultUtil.createErrorDto("100", "请指定项目");
		}
		if (StringUtils.isBlank(deviceId)) {
			return AppResultUtil.createErrorDto("100", "设备id号为空");
		}
		LingLingDevice       byDeviceId   = lingLingManager.getByDeviceId(Integer.parseInt(deviceId),Integer.parseInt(orgId));
		LingLingDeviceOutDto deviceOutDto = lingLingManager.convertDeviceDto(byDeviceId);
		return AppResultUtil.createSuccesDto(deviceOutDto);
	}


	/**
	 * 更新设备
	 *
	 * @param request
	 */
	@RequestMapping(value = "/updateDevice")
	@ResponseBody
	public AppResultDto updateDevice(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		String deviceId = request.getParameter("deviceId");// 设备id
		String orgId = request.getParameter("orgId");// 项目id
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		if (StringUtils.isBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目Id不能为空");
		}
		String [] arr=orgId.split(",");
		if (arr.length > 1) {
			return AppResultUtil.createErrorDto("100", "请指定项目");
		}
		if (StringUtils.isBlank(deviceId)) {
			return AppResultUtil.createErrorDto("100", "设备id号为空");
		}
		String newDeviceName = request.getParameter("newDeviceName");// 新设备名称
		String newDeviceCode = request.getParameter("newDeviceCode");// 新设备的SN码

		log.info("LingLingController updateDevice:deviceId{}", deviceId);
		
		
		LingLingDevice byDeviceId = lingLingManager.getByDeviceId(Integer.parseInt(deviceId),Integer.parseInt(orgId));
		
		LingLingDevice device=lingLingManager.getByDeviceCode(newDeviceCode);

		if(null!=device){
			return AppResultUtil.createErrorDto("100", "设备码已存在，无法修改");
		}
		
		int methedType=lingLingManager.getMethedType(byDeviceId.getOrgId()+"");
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("deviceId", deviceId);
		map.put("newDeviceName", newDeviceName);
		map.put("newDeviceCode", newDeviceCode);
		
		String oldCode=byDeviceId.getDeviceCode();
//		if(1==methedType){
//			//新的旧的都是A开头
//			String url = LingLingUtil.preUrl + "/device/updateDevice/" + LingLingUtil.openToken;
//			String params = LingLingUtil.linglingParam(map,methedType);
//			if (StringUtils.isBlank(params)) {
//				return AppResultUtil.createErrorDto("100", "全局参数异常");
//			}
//			return lingLingManager.updateDevice(map, url);
//		}else{
//			//新的旧的都是M开头
//			map.put("strKey",LingLingUtil.NEWSTRKEY);
//			String params = LingLingUtil.linglingParam(map,methedType);
//			if (StringUtils.isBlank(params)) {
//				return AppResultUtil.createErrorDto("100", "全局参数异常");
//			}
//			String url = LingLingUtil.newPreUrl + "/device/updateDevice/" + LingLingUtil.newOpenToken;
//			return lingLingManager.updateDevice(map, url);
//		}
		
		
		//拿项目对应的开发者信息
			LingLingDeveloper developer=lingLingManager.findByOrgId(byDeviceId.getOrgId());
			if(null==developer){
				return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
			}
			
			String url =developer.getUrl()+ "/device/updateDevice/" + developer.getOpenToken();
			if(1==methedType){
			}else{
				//新的旧的都是M开头
				map.put("strKey",developer.getStrKey());
			}
			String params = LingLingUtil.linglingParam(map,developer.getSignature(),developer.getToken(),developer.getOpenToken());
			if (StringUtils.isBlank(params)) {
				return AppResultUtil.createErrorDto("100", "全局参数异常");
			}
			return lingLingManager.updateDevice(map, url,developer,Integer.parseInt(orgId));
	}

	/**
	 * 根据条件获取设备列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDeviceList")
	@ResponseBody
	public WebPageResultDto getDeviceList(HttpServletRequest request) {
		String pageSize     = request.getParameter("pageSize");
		String pageNo       = request.getParameter("pageNo");
		String deviceType   = request.getParameter("deviceType");
		String deviceStatus = request.getParameter("deviceStatus");
		String deviceId     = request.getParameter("deviceId");
		String deviceCode   = request.getParameter("deviceCode");
		String createTime   = request.getParameter("createTime");
		String orgId        = request.getParameter("orgId");

		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}

		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		map.put("deviceType", deviceType);
		map.put("deviceStatus", deviceStatus);
		if (NumberUtils.isNumeric(deviceId)) {
			map.put("deviceId", deviceId);
		}
		map.put("deviceCode", deviceCode);
		map.put("createTime", createTime);
		map.put("orgId", orgId);

		Page deviceList = lingLingManager.getDeviceList(map);

		WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", deviceList.getItems());
		dto.setCount(deviceList.getTotalCount());
		return dto;
	}

	/**
	 * 令令端查询设备列表
	 */
	@RequestMapping(value = "/queryDeviceList")
	@ResponseBody
	public AppResultDto queryDeviceList() {

		String url = LingLingUtil.preUrl + "/device/queryDeviceList/" + LingLingUtil.openToken;

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 生成开门密钥
	 */
	@RequestMapping(value = "/makeSdkKey")
	@ResponseBody
	public AppResultDto makeSdkKey(HttpServletRequest request) {

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

		if (StringUtils.isBlank(deviceIds)) {
			return AppResultUtil.createErrorDto("100", "设备id为空");
		}

		log.info("LingLingController makeSdkKey:deviceIds{}", deviceIds);

		String[] ids = deviceIds.split(",");

		String url = LingLingUtil.preUrl + "/key/makeSdkKey/" + LingLingUtil.openToken;

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 获取令令id
	 */
	@RequestMapping(value = "/getLingLingId")
	@ResponseBody
	public AppResultDto getLingLingId() {

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 批量获取令令id
	 */
	@RequestMapping(value = "/getLingLingIds")
	@ResponseBody
	public AppResultDto getLingLingIds(HttpServletRequest request) {

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

		if (StringUtils.isBlank(count)) {
			count = "1";
		}

		log.info("LingLingController getLingLingIds:count{}", count);

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

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 生成业主二维码
	 */
	@RequestMapping(value = "/addOwnerQrCode")
	@ResponseBody
	public AppResultDto addOwnerQrCode(HttpServletRequest request) {

		String lingLingId = request.getParameter("lingLingId");
		String sdkKeys    = request.getParameter("sdkKeys");
		String endTime    = request.getParameter("endTime");
		String strKey     = request.getParameter("strKey");

		if (StringUtils.isAnyBlank(lingLingId, sdkKeys, endTime, strKey)) {
			return AppResultUtil.createErrorDto("100", "非空字段为空");
		}

		log.info("LingLingController addOwnerQrCode:lingLingId{},sdkKeys{},endTime{},strKey{}", lingLingId, sdkKeys, endTime, strKey);

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

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lingLingId", lingLingId);
		map.put("sdkKeys", sdkKeys.split(","));
		map.put("endTime", Integer.parseInt(endTime));
		map.put("strKey", strKey);
		map.put("effecNumber", LingLingUtil.EFFEC_NUMBER_1);

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 添加门禁访客
	 */
	@RequestMapping(value = "/addVisitorQrCode")
	@ResponseBody
	public AppResultDto addVisitorQrCode(HttpServletRequest request) {

		String lingLingId  = request.getParameter("lingLingId");
		String sdkKeys     = request.getParameter("sdkKeys");
		String startTime   = request.getParameter("startTime");
		String endTime     = request.getParameter("endTime");
		String effecNumber = request.getParameter("effecNumber");
		String strKey      = request.getParameter("strKey");

		if (StringUtils.isAnyBlank(lingLingId, sdkKeys, startTime, endTime, strKey)) {
			return AppResultUtil.createErrorDto("100", "非空字段为空");
		}

		if (StringUtils.isAnyBlank(effecNumber)) {
			effecNumber = "1";
		}

		log.info("LingLingController addVisitorQrCode:lingLingId{},sdkKeys{},startTime{},endTime{},effecNumber{},strKey{}",
				lingLingId, sdkKeys, startTime, endTime, effecNumber, strKey);

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

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lingLingId", lingLingId);
		map.put("sdkKeys", sdkKeys.split(","));
		map.put("endTime", Integer.parseInt(endTime));
		map.put("strKey", strKey);
		map.put("effecNumber", effecNumber);
		map.put("startTime", Long.parseLong(startTime));

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 删除访客二维码
	 */
	@RequestMapping(value = "/delVisitorQrCode")
	@ResponseBody
	public AppResultDto delVisitorQrCode(HttpServletRequest request) {

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

		if (StringUtils.isBlank(codeId)) {
			return AppResultUtil.createErrorDto("100", "二维码id为空");
		}

		log.info("LingLingController delVisitorQrCode:codeId{}", codeId);

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

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 开门日志查询
	 */
	@RequestMapping(value = "/selectOpenDoorLog")
	@ResponseBody
	public AppResultDto selectOpenDoorLog(HttpServletRequest request) {

		String page       = request.getParameter("page");
		String rows       = request.getParameter("rows");
		String deviceId   = request.getParameter("deviceId");
		String startTime  = request.getParameter("startTime");
		String endTime    = request.getParameter("endTime");
		String lingLingId = request.getParameter("lingLingId");

		log.info("LingLingController selectOpenDoorLog:page{},rows{},deviceId{},startTime{},endTime{},lingLingId{}",
				page, rows, deviceId, startTime, endTime, lingLingId);

		String url = LingLingUtil.preUrl + "/openDoorLog/selectOpenDoorLog/" + LingLingUtil.openToken;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("page", page);
		map.put("rows", rows);
		map.put("deviceId", deviceId);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		map.put("lingLingId", lingLingId);

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 添加门禁卡
	 */
	@RequestMapping(value = "/addOpenDoorCard")
	@ResponseBody
	public AppResultDto addOpenDoorCard(HttpServletRequest request) {

		String cardUids  = request.getParameter("cardUids");
		String deviceIds = request.getParameter("deviceIds");
		String endTime   = request.getParameter("endTime");

		if (StringUtils.isAnyBlank(cardUids, deviceIds, endTime)) {
			return AppResultUtil.createErrorDto("100", "非空字段为空");
		}

		log.info("LingLingController selectOpenDoorLog:cardUids{},deviceIds{},endTime{}", cardUids, deviceIds, endTime);

		String url = LingLingUtil.preUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.openToken;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cardUids", cardUids.split(","));
		map.put("deviceIds", deviceIds.split(","));
		map.put("endTime", Integer.parseInt(endTime));

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}


	/**
	 * 删除门禁卡
	 */
	@RequestMapping(value = "/delOpenDoorCard")
	@ResponseBody
	public AppResultDto delOpenDoorCard(HttpServletRequest request) {

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

		if (StringUtils.isBlank(cardUids)) {
			return AppResultUtil.createErrorDto("100", "门禁卡id为空");
		}

		log.info("LingLingController delOpenDoorCard:cardUids{}", cardUids);

		String url = LingLingUtil.preUrl + "/openDoorCard/delOpenDoorCard/" + LingLingUtil.openToken;

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 更新门禁卡
	 */
	@RequestMapping(value = "/updateOpenDoorCard")
	@ResponseBody
	public AppResultDto updateOpenDoorCard(HttpServletRequest request) {

		String cardUids     = request.getParameter("cardUids");
		String newDeviceIds = request.getParameter("newDeviceIds");
		String newEndTime   = request.getParameter("newEndTime");

		if (StringUtils.isAnyBlank(cardUids, newDeviceIds, newEndTime)) {
			return AppResultUtil.createErrorDto("100", "非空字段为空");
		}

		log.info("LingLingController updateOpenDoorCard:cardUids{},newDeviceIds{},newEndTime{}", cardUids, newDeviceIds, newEndTime);

		String url = LingLingUtil.preUrl + "/openDoorCard/updateOpenDoorCard/" + LingLingUtil.openToken;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cardUids", cardUids.split(","));
		map.put("newDeviceIds", newDeviceIds.split(","));
		map.put("newEndTime", Integer.parseInt(newEndTime));

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 查询门禁卡
	 */
	@RequestMapping(value = "/queryOpenDoorCard")
	@ResponseBody
	public AppResultDto queryOpenDoorCard(HttpServletRequest request) {

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

		if (StringUtils.isBlank(cardUids)) {
			return AppResultUtil.createErrorDto("100", "门禁卡id为空");
		}

		log.info("LingLingController queryOpenDoorCard:cardUids{}", cardUids);

		String url = LingLingUtil.preUrl + "/openDoorCard/queryOpenDoorCard/" + LingLingUtil.openToken;

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 远程开门
	 */
	@RequestMapping(value = "/remoteOpenDoor")
	@ResponseBody
	public AppResultDto remoteOpenDoor(HttpServletRequest request) {

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

		if (StringUtils.isBlank(sdkKey)) {
			return AppResultUtil.createErrorDto("100", "开门密匙为空");
		}

		log.info("LingLingController remoteOpenDoor:sdkKey{}", sdkKey);

		String url = LingLingUtil.preUrl + "/key/remoteOpenDoor/" + LingLingUtil.openToken;

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

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

		if (StringUtils.isBlank(params)) {
			return AppResultUtil.createErrorDto("100", "全局参数异常");
		}

		String result = HttpKit.HttpPost(params, url);

		return handleResult(result);
	}

	/**
	 * 添加设备权限
	 *
	 * @param group
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addUpdateDeviceGroup")
	@ResponseBody
	public AppResultDto addUpdateDeviceGroup(@ModelAttribute("devicePermGroup") DevicePermGroup group, HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		
		String isChange = request.getParameter("isChange");
		try {
			if (group.getId() == null) {
				// 新增
				group.setCreateTime(new Date());
				group.setCreator(user.getId());
				// 如果新增的是访客权限组,则需校验当前项目下是否已经存在访客权限组
				if (group.getGroupType() == 2) {
					List<DevicePermGroup> groups = lingLingManager.getDevicePermGroupByOrgId(group.getOrgId(), 2);
					if (groups != null && groups.size() > 0) {// 如果存在,则不能新增
						return AppResultUtil.createErrorDto("100", "当前项目下已存在访客权限组");
					}
				}
				lingLingManager.saveModel(group);
				Set<LingLingDevice>  setLingLingDevice=  getDeviceSet(request);
				for(LingLingDevice d:setLingLingDevice){
					lingLingManager.savePermGroupDevice(group.getId(),d.getId());
				}

			} else {
				DevicePermGroup groupById = lingLingManager.getDeviceGroupById(group.getId());
				groupById.setRemark(group.getRemark());
				groupById.setModify(user.getId());
				groupById.setModifyTime(new Date());
				groupById.setBeginTime(group.getBeginTime());
				groupById.setEndTime(group.getEndTime());
				groupById.setIsHoliday(group.getIsHoliday());
				groupById.setIsUseLimit(group.getIsUseLimit());
				groupById.setIsWeek(group.getIsWeek());
				groupById.setIsWorkday(group.getIsWorkday());
				
				Set<LingLingDevice>  setLingLingDevice=  getDeviceSet(request);
				lingLingManager.updateDeviceGroup(groupById,setLingLingDevice);
				
			}
			if(StringUtils.isEmpty(isChange) || "1".equals(isChange)){
				lingLingService.updateUserPerm(group);
			}
			
		} catch (Exception e) {
			log.error("LingLingController addUpdateDeviceGroup ==========>" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作失败");
		}
		return AppResultUtil.createSuccesDto();
	}
	
	/**
	 * 获取权限组列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDeviceGroupList")
	@ResponseBody
	public WebPageResultDto getDeviceGroupList(HttpServletRequest request) {
		String pageSize  = request.getParameter("pageSize");
		String pageNo    = request.getParameter("pageNo");
		String groupName = request.getParameter("groupName");
		String groupType = request.getParameter("groupType");
		String deviceId  = request.getParameter("deviceId");
		String orgId     = request.getParameter("orgId");

		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		map.put("groupName", groupName);
		map.put("groupType", groupType);
		map.put("deviceId", deviceId);
		map.put("orgId", orgId);

		Page deviceList = lingLingManager.getDeviceGroupList(map);

		WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", deviceList.getItems());
		dto.setCount(deviceList.getTotalCount());
		return dto;
	}

	/**
	 * 获取员工权限组列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getEmployeeGroupList")
	@ResponseBody
	public AppResultDto getEmployeeGroupList(HttpServletRequest request) {
		String orgId = request.getParameter("orgId");

		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}

		List<DevicePermGroup>       groups = lingLingManager.getDevicePermGroupByOrgId(Integer.parseInt(orgId), 1);
		List<DevicePermGroupOutDto> list   = new ArrayList<DevicePermGroupOutDto>();
		if (groups != null && groups.size() > 0) {
			for (DevicePermGroup group : groups) {
				DevicePermGroupOutDto dto = new DevicePermGroupOutDto();
				dto.setId(group.getId());
				dto.setGroupName(group.getGroupName());
				list.add(dto);
			}
		}
		return AppResultUtil.createSuccesDto(list);
	}


	/**
	 * 获取权限组详情
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDeviceGroupInfo")
	@ResponseBody
	public AppResultDto getDeviceGroupInfo(HttpServletRequest request) {
		String                groupId = request.getParameter("id");
		DevicePermGroup       group   = lingLingManager.getDeviceGroupById(Long.parseLong(groupId));
		DevicePermGroupOutDto dto     = new DevicePermGroupOutDto();
		if (group != null) {
			//String deviceNames = LingLingUtil.getDeviceNames(group.getDevices());
			String deviceNames = lingLingManager.getDeviceNamesByGroupId(groupId);
			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());
			dto.setOrgId(group.getOrgId());
			dto.setIsHoliday(group.getIsHoliday());
			dto.setIsUseLimit(group.getIsUseLimit());
			dto.setIsWeek(group.getIsWeek());
			dto.setIsWorkday(group.getIsWorkday());
			dto.setBeginTime(group.getBeginTime());
			dto.setEndTime(group.getEndTime());
		}

		return AppResultUtil.createSuccesDto(dto);
	}

	/**
	 * 删除权限组
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delDeviceGroup")
	@ResponseBody
	public AppResultDto delDeviceGroup(HttpServletRequest request) {
		String groupId = request.getParameter("id");

		if (StringUtils.isBlank(groupId)) {
			return AppResultUtil.createErrorDto("100", "id为空");
		}
		String flag = lingLingManager.delDeviceGroup(groupId);

		if (Constants.SUCCESS_FLAG.equals(flag)) {
			return AppResultUtil.createSuccesDto("删除成功");
		}
		return AppResultUtil.createErrorDto("100", "删除失败");
	}

	/**
	 * 获取设备列表,及指定的权限组关联设备情况
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDeviceTree")
	@ResponseBody
	public AppResultDto getDeviceTree(HttpServletRequest request) {
		List<Map<String, Object>> list    = new ArrayList<Map<String, Object>>();
		String                    groupId = request.getParameter("groupId");
		String                    orgId   = request.getParameter("orgId");

		if (StringUtils.isBlank(orgId)) {
			return AppResultUtil.createErrorDto("100", "项目id为空");
		}
		// 首先获取所有可用的设备列表
		List<LingLingDevice> deviceList = lingLingManager.getDeviceList(1, Integer.parseInt(orgId));
		// 然后获取当前组关联的设备列表
		Set<LingLingDevice> devices = new HashSet<LingLingDevice>() ;
		if (StringUtils.isNotBlank(groupId)) {
			DevicePermGroup devicePermGroup = lingLingManager.getDeviceGroupById(Long.parseLong(groupId));
			
			//devices = devicePermGroup.getDevices();			
			List<LingLingDevice> devicesList = lingLingManager.getDevicesByGroup(devicePermGroup.getId(), 1);
			for(LingLingDevice d: devicesList){
				devices.add(d);
			}
		}


		if (deviceList != null && deviceList.size() > 0) {
			for (LingLingDevice device : deviceList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", device.getId());
				map.put("deviceId", device.getDeviceId());
				map.put("deviceName", device.getDeviceName());
				map.put("isChecked", false);
				if (devices != null && devices.size() > 0) {
					for (LingLingDevice device1 : devices) {
						if (device.getId() == device1.getId()) {
							map.put("isChecked", true);
							continue;
						}
					}
				}
				list.add(map);
			}
		}
		return AppResultUtil.createSuccesDto(list);
	}

	/**
	 * 发卡操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/provideCard")
	@ResponseBody
	public AppResultDto provideCard(HttpServletRequest request) {
		String cardCode = request.getParameter("cardCode");
		String userId   = request.getParameter("userId");

		if (StringUtils.isAnyBlank(cardCode, userId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}
		
		if(!StringUtil.isContainChinese(cardCode)){
			return AppResultUtil.createErrorDto("100", "不能输入非16进制字符");
		}
		return lingLingManager.provideCard(cardCode, userId);
	}

	/**
	 * 收卡操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/recycleCard")
	@ResponseBody
	public AppResultDto recycleCard(HttpServletRequest request) {
		String cardId   = request.getParameter("id");
		String cardCode = request.getParameter("cardCode");
		String userId   = request.getParameter("userId");

		if (StringUtils.isAnyBlank(cardId, cardCode)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		AppUser appUser = appUserManager.get(Integer.parseInt(userId));
		int methedType=lingLingManager.getMethedType(appUser.getOrganizationId()+"");
		//拿项目对应的开发者信息
		LingLingDeveloper developer=lingLingManager.findByOrgId(appUser.getOrganizationId());
		if(null==developer){
			return AppResultUtil.createErrorDto("100", "未获取到开发者信息，请联系管理员");
		}
		return lingLingManager.recycleCard(cardId, cardCode,methedType,developer);
	}

	/** 
	 * 批量设置用户通行权限
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/setUserPerm")
	@ResponseBody
	public AppResultDto setUserPerm(HttpServletRequest request) {

		String groupId = request.getParameter("groupId");
		String userIds = request.getParameter("userIds");

		if (StringUtils.isAnyBlank(groupId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
//            DevicePermGroup groupById= lingLingManager.getDeviceGroupById(Long.parseLong(groupId));
//            groupById.setUsers(getUserSet(request));
			lingLingManager.updateUserPerm(groupId, userIds);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("LingLingController setUserPerm===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "设置失败");
	}


	/**
	 * 批量新增设置用户通行权限
	 * 指定权限组
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/addUserPerm")
	@ResponseBody
	public AppResultDto addUserPerm(HttpServletRequest request) {

		String groupId = request.getParameter("groupId");
		String userIds = request.getParameter("userIds");

		if (StringUtils.isAnyBlank(groupId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
			//只有单项目才有权限分配功能
			Integer orgId=null;
			User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
			String orgIds = getUserManageOrgIds(user);
			if(StringUtils.isNotBlank(orgIds)){
				orgId=Integer.parseInt(orgIds);
			}
			int methedType=lingLingManager.getMethedType(orgId+"");
			lingLingManager.updateUserPermNew(groupId, userIds, true,methedType,orgId);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("LingLingController setUserPerm===============>" + e.getMessage());
			e.printStackTrace();
		}

		return AppResultUtil.createErrorDto("100", "设置失败");
	}

	/**
	 * 批量删除设置用户通行权限
	 * 指定权限组
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteUserPerm")
	@ResponseBody
	public AppResultDto deleteUserPerm(HttpServletRequest request) {

		String groupId = request.getParameter("groupId");
		String userIds = request.getParameter("userIds");

		if (StringUtils.isAnyBlank(groupId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
//            DevicePermGroup groupById= lingLingManager.getDeviceGroupById(Long.parseLong(groupId));
//            groupById.setUsers(getUserSet(request));
			lingLingManager.updateUserPermNew(groupId, userIds, false,2,null);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("LingLingController setUserPerm===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "设置失败");
	}


	/**
	 * 批量删除用户通行权限
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delUserPerm")
	@ResponseBody
	public AppResultDto delUserPerm(HttpServletRequest request) {
		String userIds = request.getParameter("userIds");

		if (StringUtils.isAnyBlank(userIds)) {
			return AppResultUtil.createErrorDto("100", "请选择用户");
		}

		try {
			// 对数组进行去重
			String[] ids = LingLingUtil.distinct(userIds.split(";"));
			userIds = StringUtils.join(ids, ",");
			lingLingManager.deleteUserGroupByUserIds(userIds);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("LingLingController delUserPerm===============>" + e.getMessage());
		}

		return AppResultUtil.createErrorDto("100", "操作失败");
	}


	/**
	 * 获取指定权限组下的用户列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGroupUser")
	@ResponseBody
	public AppResultDto getGroupUser(HttpServletRequest request) {

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

		if (StringUtils.isAnyBlank(groupId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
			List<Map<String, Object>> groupUser = lingLingManager.getGroupUser(groupId);
			return AppResultUtil.createSuccesDto(groupUser);
		} catch (Exception e) {
			log.error("LingLingController getGroupUser===============>" + e.getMessage());
		}
		return AppResultUtil.createErrorDto("100", "获取失败");
	}

	/**
	 * 获取通行记录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getPassHistory")
	@ResponseBody
	public WebPageResultDto getPassHistory(HttpServletRequest request) {		
		
		String deviceType = request.getParameter("deviceType");// 设备类型
		String deviceId   = request.getParameter("deviceId");// 设备id
		String mobile     = request.getParameter("mobile");// 手机号码
		String userType   = request.getParameter("userType");// 用户类型 1 员工；2 访客
		String cardCode   = request.getParameter("cardCode");// 实体卡号
		String startTime  = request.getParameter("startTime");// 起始时间
		String endTime    = request.getParameter("endTime");// 结束时间
		String pageNo     = request.getParameter("pageNo");// 当前页
		String pageSize   = request.getParameter("pageSize");// 每页显示数
		String orgId      = request.getParameter("orgId");// 项目id
		String passType   = request.getParameter("passType"); 
		
		
		String passPersonInfo      = request.getParameter("passPersonInfo");// 通行人信息 姓名、手机号、企业
		String passEqInfo      = request.getParameter("passEqInfo");// 通行设备信息 设备类型、ID、名称 
		
		if (StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("deviceType", deviceType);
		params.put("deviceId", deviceId);
		params.put("mobile", mobile);
		params.put("userType", userType);
		params.put("cardCode", cardCode);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
		params.put("pageNo", pageNo);
		params.put("pageSize", pageSize);
		params.put("orgId", orgId);
		params.put("passType", passType);
		params.put("passPersonInfo", passPersonInfo);
		params.put("passEqInfo", passEqInfo);

		try {
			Page             list = lingLingManager.getPassHistory(params);
			WebPageResultDto dto  = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", list.getItems());
			dto.setCount(list.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("LingLingController getPassHistory===============>" + e.getMessage());
			e.printStackTrace();
		}

		return new WebPageResultDto("500","",null);
	}
	
	
	/**
	 * 导出订餐统计报表
	 *
	 * @param orgId
	 * @param dateType
	 * @param date
	 * @param endDate
	 * @return
	 */
	@RequestMapping(value = "exportPassHistory")
	@ResponseBody
	public AppResultDto exportPassHistory(HttpServletRequest request) {
		
		String deviceType = request.getParameter("deviceType");// 设备类型
		String deviceId   = request.getParameter("deviceId");// 设备id
		String mobile     = request.getParameter("mobile");// 手机号码
		String userType   = request.getParameter("userType");// 用户类型 1 员工；2 访客
		String cardCode   = request.getParameter("cardCode");// 实体卡号
		String startTime  = request.getParameter("startTime");// 起始时间
		String endTime    = request.getParameter("endTime");// 结束时间
//		String pageNo     = request.getParameter("pageNo");// 当前页
//		String pageSize   = request.getParameter("pageSize");// 每页显示数
		String orgId      = request.getParameter("orgId");// 项目id
		String passType   = request.getParameter("passType"); 
		String passPersonInfo      = request.getParameter("passPersonInfo");// 通行人信息 姓名、手机号、企业
		String passEqInfo      = request.getParameter("passEqInfo");// 通行设备信息 设备类型、ID、名称 
		User user = (User) request.getSession().getAttribute("UserCache");// 获取当前用户
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("deviceType", deviceType);
		params.put("deviceId", deviceId);
		params.put("mobile", mobile);
		params.put("userType", userType);
		params.put("cardCode", cardCode);
		params.put("startTime", startTime);
		params.put("endTime", endTime);
//		params.put("pageNo", pageNo);
//		params.put("pageSize", pageSize);
		params.put("orgId", orgId);
		params.put("passType", passType);
		params.put("passPersonInfo", passPersonInfo);
		params.put("passEqInfo", passEqInfo);
		return lingLingManager.exportPassHistory(params);
	}


	/**
	 * 获取设备集合
	 *
	 * @param request
	 * @return
	 */
	public Set<LingLingDevice> getDeviceSet(HttpServletRequest request) {
		String              deviceIds = request.getParameter("deviceIds");
		Set<LingLingDevice> deviceSet = new HashSet<LingLingDevice>();
		if (StringUtils.isNotEmpty(deviceIds)) {
			String[] ids = deviceIds.split(";");
			for (String id : ids) {
				deviceSet.add(lingLingManager.getById(Long.parseLong(id)));
			}
		}
		return deviceSet;
	}

	/**
	 * 获取用户集合
	 * @param request
	 * @return
	 */
//    public Set<AppUser> getUserSet(HttpServletRequest request) {
//        String userIds = request.getParameter("userIds");
//        Set<AppUser> userSet = new HashSet<AppUser>();
//        if (StringUtils.isNotEmpty(userIds)) {
//            // 对数组进行去重
//            String[] ids = LingLingUtil.distinct(userIds.split(";"));
//            if (ids == null){
//                return null;
//            }
//            for (String id : ids) {
//                AppUser user = new AppUser();
//                user.setId(Integer.parseInt(id));
//                userSet.add(user);
//            }
//        }
//        return userSet;
//    }


	/**
	 * 配置/修改访客机设置
	 *
	 * @return
	 */
	@RequestMapping(value = "/addUpdateVisitorMachine")
	@ResponseBody
	public AppResultDto addUpdateVisitorMachine(@ModelAttribute LingLingVisitorMachineInputDto visitorMachine,
												HttpServletRequest request) {

		// 获取当前登录用户
		User    user   = userManager.getUserByUsername2(request.getRemoteUser());
		boolean result = lingLingManager.addUpdateVisitorMachine(visitorMachine, user);

		if (result) {
			return AppResultUtil.createSuccesDto();
		}
		return AppResultUtil.createErrorDto(AppConstants.ERROR_CODE, "操作失败");
	}

	/**
	 * 获取访客机配置信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/visitorMachineInfo")
	@ResponseBody
	public AppResultDto visitorMachineInfo(@RequestParam Integer orgId) {
		LingLingVisitorMachineInputDto dto = lingLingManager.getVisitorMachine(orgId);
		return AppResultUtil.createSuccesDto(dto);
	}

	/**
	 * 获取访客详情
	 *
	 * @return
	 */
	@RequestMapping(value = "/visitorInfo")
	@ResponseBody
	public AppResultDto visitorInfo(@RequestParam Integer visitorId) {

		VisitorInfoVO visitorInfoVO = lingLingManager.getVisitorInfo(visitorId);
		return AppResultUtil.createSuccesDto(visitorInfoVO);
	}

	/**
	 * 保存访客登记信息
	 * 之前只有微信的 增加PC的接口
	 * 抽的共用的接口 visitorInFoService.saveVisitorUserInfo
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveVisitorUserInfo")
	@ResponseBody
	public AppResultDto saveVisitorUserInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {


		Map<String, Object> returnMap = visitorInFoService.saveVisitorUserInfo(request, response);
		return AppResultUtil.createSuccesDto(returnMap);


	}

	/**
	 * 保存扫描打印编辑内容
	 */
	@RequestMapping(value = "scanUpdateVisitorInfo")
	@ResponseBody
	public AppResultDto scanUpdateVisitorInfo(@ModelAttribute LingLingScanVisitorInfo scanVisitorInfo,
											  HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = visitorInFoManager.scanUpdateVisitorInfo(scanVisitorInfo, request);

		return AppResultUtil.createSuccesDto(returnMap);

	}


	/**
	 * 获取指定权限组下的用户列表new
	 *
	 * @param orgId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getVirtDeptUser")
	@ResponseBody
	public AppResultDto getVirtDeptUser(HttpServletRequest request) throws Exception {


		String groupId = request.getParameter("groupId");
		String orgId   = request.getParameter("orgId");
		String name    = request.getParameter("name");
		String type    = request.getParameter("type");//1-指定权限组下的已分配的用户 2-指定权限组下的未分配的用户
		if (StringUtils.isEmpty(type)) {
			return AppResultUtil.createErrorDto("100", "type不能为空");
		}

		if (StringUtils.isAnyBlank(groupId, orgId)) {
			return AppResultUtil.createErrorDto("100", "参数为空");
		}

		try {
			Map<Integer, Object> map = meetingService.getGroupUser(Integer.valueOf(groupId), Integer.valueOf(orgId), name, type);
			return AppResultUtil.createSuccesDto(map);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "返回信息：" + e.getMessage());
		}
	}
	
	/**
	 * 获取通行趋势报表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPassList")
	@ResponseBody
	public AppResultDto getPassList(Integer orgId,Integer type,Integer model,String date,String orgName) throws Exception {


		if (null == orgId) {
			return AppResultUtil.createErrorDto("100", "项目不能为空");
		}

		if (null == model) {
			return AppResultUtil.createErrorDto("100", "视图模式不能为空");
		}
		
		if(StringUtils.isEmpty(date)){
			return AppResultUtil.createErrorDto("100", "时间不能为空");
		}

		try {
			List<LinglingPassDto> list = lingLingManager.getPassList(orgId,type,model,date,orgName);
			return AppResultUtil.createSuccesDto(list);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取失败:" + e.getMessage());
		}
	}

	
	/**
	 * 导出通行趋势报表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/exportPassList")
	@ResponseBody
	public AppResultDto exportPassList(Integer orgId,Integer type,Integer model,String date,String orgName) throws Exception {


		if (null == orgId) {
			return AppResultUtil.createErrorDto("100", "项目不能为空");
		}

		if (null == model) {
			return AppResultUtil.createErrorDto("100", "视图模式不能为空");
		}
		
		if(StringUtils.isEmpty(date)){
			return AppResultUtil.createErrorDto("100", "时间不能为空");
		}
		try {
			return lingLingManager.exportPassList(orgId, type, model, date, orgName);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "导出失败:" + e.getMessage());
		}
	}

}
