package com.yeejoin.amos.supervision.business.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.yeejoin.amos.supervision.business.dao.mapper.CheckMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.PointMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.RouteMapper;
import com.yeejoin.amos.supervision.business.dao.mapper.TaskMapper;
import com.yeejoin.amos.supervision.business.feign.Business;
import com.yeejoin.amos.supervision.business.service.intfc.ISafety3DDataSendService;
import com.yeejoin.amos.supervision.business.util.CommonResponse;
import com.yeejoin.amos.supervision.common.remote.RemoteServer;
import com.yeejoin.amos.supervision.feign.RemoteSecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.google.common.base.Joiner;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.supervision.core.common.response.CheckInputResponse;
import com.yeejoin.amos.supervision.core.common.response.PatrolUserRespone;
import com.yeejoin.amos.supervision.core.common.response.PointCheckInfoBusinessRespone;
import com.yeejoin.amos.supervision.core.common.response.PointCheckInfoRespone;
import com.yeejoin.amos.supervision.core.common.response.PointInfoSyn3DRespone;
import com.yeejoin.amos.supervision.core.common.response.PointPositionInfoSyn3DRespone;
import com.yeejoin.amos.supervision.core.common.response.PointUserSyn3DRespone;
import com.yeejoin.amos.supervision.core.common.response.RouteResponse;
import com.yeejoin.amos.supervision.core.common.response.TaskInfoBusinessRespone;
import com.yeejoin.amos.supervision.core.common.response.TaskInfoRespone;
import com.yeejoin.amos.safety.common.cache.PointStatusCache;
@Service("safety3DDataSend")
public class Safety3DDataSendServiceImpl implements ISafety3DDataSendService {

	private static final Logger logger = LoggerFactory.getLogger(Safety3DDataSendServiceImpl.class);
	
	@Autowired
	private CheckMapper checkMapper;
	
	@Resource
    TaskMapper taskMapper;
	
   
	@Autowired
    RemoteServer remoteServer;
	
	@Autowired
    private Business business;
	
	
	
	
	@Resource
	private PointMapper pointMapper;
	@Autowired
	private RemoteSecurityService remoteSecurityService;

	@Resource
	private RouteMapper routeMapper;
	
   /* @Value("${params.remoteP.enable}")
    private boolean enable;*/

	@Override
	public PointCheckInfoRespone pointCheckInfoPush(String toke,String product,String appKey,Long checkId) {
		 PointStatusCache pointStatusCache = PointStatusCache.getInstance();
		 List<PointCheckInfoRespone> pointCheckInfoList = checkMapper.getCheckInfoById(checkId);
		 PointCheckInfoRespone pointCheckInfo = new PointCheckInfoRespone();
		 if(!pointCheckInfoList.isEmpty()){
			 pointCheckInfo = pointCheckInfoList.get(0);
			 AgencyUserModel userModel = remoteSecurityService.getUserById( toke, product, appKey,String.valueOf(pointCheckInfo.getUserID()));
	            if(userModel != null){
	            	pointCheckInfo.setUserName(userModel.getUserName());
	            	pointCheckInfo.setTelephone(userModel.getMobile());
	            }
			 List<CheckInputResponse> checkInputList = new ArrayList<CheckInputResponse>();
			 pointCheckInfoList.forEach(action->{
				 CheckInputResponse checkInputBo = new CheckInputResponse();
				 checkInputBo.setInputItemName(action.getInputName());
				 checkInputBo.setInputValue(action.getInputValue());
				 checkInputBo.setIsOK(action.getInputStatus());
				 checkInputBo.setInputLevel(action.getInputLevel());
				 checkInputList.add(checkInputBo);
			 });
			 pointCheckInfo.setCheckInput(checkInputList);
			 String pointStatus = pointStatusCache.getPointStatus(pointCheckInfo.getPointID());
			 if(!ObjectUtils.isEmpty(pointStatus)){
				 if(!pointStatus.equals(pointCheckInfo.getStatus())){
					 pointStatusCache.putPointStatus(pointCheckInfo.getPointID(), pointCheckInfo.getStatus());
					 pointCheckInfo.setIsChangeStatus(true);
				 }
			 }else{
				 pointStatusCache.putPointStatus(pointCheckInfo.getPointID(), pointCheckInfo.getStatus());
				 pointCheckInfo.setIsChangeStatus(true);
			 }
			 logger.debug("推送数据============"+pointCheckInfo);
			 
			 List<PointCheckInfoRespone> pointCheckInfolist=new ArrayList<>();
			 pointCheckInfolist.add(pointCheckInfo);
			 
			 
			 
//		CommonResponse commonResponse = remote3DServer.checkStatusPush( toke, product, appKey,pointCheckInfolist);

		 }
		return pointCheckInfo;
	}


	@Override
	public TaskInfoRespone taskDetailInfoPush(String toke,String product,String appKey,Long taskId) {
		List<TaskInfoRespone> taskInfoResponeList = taskMapper.getTaskDetailInfoByTaskId(taskId);
		TaskInfoRespone taskInfoRespone = new TaskInfoRespone();
		if(!taskInfoResponeList.isEmpty()){
			taskInfoRespone = taskInfoResponeList.get(0);
			List<CheckInputResponse> checkInputList = new ArrayList<CheckInputResponse>();
			taskInfoResponeList.forEach(action->{
				CheckInputResponse checkInputResponse = new CheckInputResponse();
				checkInputResponse.setInputItemName(action.getInputItemName());
				checkInputResponse.setInputValue(action.getInputValue());
				checkInputResponse.setIsOK(action.getInputStatus());
				checkInputList.add(checkInputResponse);
			});
			taskInfoRespone.setCheckInputs(checkInputList);
			//remoteServer.errorTaskPush(taskInfoRespone);
			
			//修改推送
				TaskInfoBusinessRespone tb = new TaskInfoBusinessRespone();
				tb.setContent(taskInfoRespone.getContent());
				tb.setPointName(taskInfoRespone.getPointName());
				tb.setPointNo(taskInfoRespone.getPointID() + "");
				tb.setTaskID(taskInfoRespone.getTaskID());
				tb.setTaskName(taskInfoRespone.getTaskName());
				tb.setTaskState(Integer.valueOf(taskInfoRespone.getStatus()));
				CommonResponse commonResponse =business.errorTaskPushToB(tb);
				 List<TaskInfoRespone> taskInfoResponelist=new ArrayList<>();
				 taskInfoResponelist.add(taskInfoRespone);
//				CommonResponse commonResponse1 = remote3DServer.errorTaskPushTo3D(toke, product, appKey,taskInfoResponelist);

			
		}
		return taskInfoRespone;
		
	}
	
	
	@Override
	public List<PointInfoSyn3DRespone> pushPointTo3D(String toke,String product,String appKey,List<Long> pointIds) {
		List<PointInfoSyn3DRespone> list = new ArrayList<>();
		if(!pointIds.isEmpty()){
			pointIds.forEach(pointId->{
				List<Map<String,Object>> result = pointMapper.getPointInfoById(pointId);
				
				
				//安全处理
				
				
				//获取用户信息
	        	List<String> userIds = new ArrayList<>();
	        	List<String> depIds = new ArrayList<>();
	        	if( result != null  ) {
	        	result.forEach(item ->{
	               
	                if(!userIds.contains(item.get("userName"))&& !ObjectUtils.isEmpty(item.get("userName"))) {
	    				userIds.add((String) item.get("userName"));
	    			}
	    			if(!depIds.contains(item.get("groupName"))&& !ObjectUtils.isEmpty(item.get("groupName"))){
	        			depIds.add(item.get("groupName").toString());
	        		}
	        	});	
	        	
	        	
	        	
	        	
	        	result.forEach(item ->{
	        			if(userIds!=null&&userIds.size()>0){
	                		//设置执行人员和执行部门
	                    	List<AgencyUserModel> listUsers = remoteSecurityService.listUserByUserIds(toke, product, appKey,
	                    			Joiner.on(",").join(userIds));
	                    	if( listUsers != null && listUsers.size() > 0){
	                			List<AgencyUserModel> filterUser = listUsers.stream().filter(user -> user.getUserId().contains((String) item.get("userName"))).collect(Collectors.toList());
	                			if(filterUser != null && filterUser.size() == 1) {
	                				AgencyUserModel agencyUserModel = filterUser.get(0);      				
	                				item.put("userName",agencyUserModel.getRealName());        				
	                			}
	            				
	            			}
	                	}
	        			if(depIds!=null&&depIds.size()>0){
	                    	List<LinkedHashMap> listDepartments = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey,Joiner.on(",").join(depIds));
	                    	if(  listDepartments != null && listDepartments.size() ==1) {
	                    		List<LinkedHashMap> filterDep = listDepartments.stream().filter(d -> d.get("sequenceNbr").toString().equals(item.get("groupName"))).collect(Collectors.toList());
	                			
	                			if(filterDep != null && filterDep.size() > 0){
	                				LinkedHashMap dep = filterDep.get(0);
	                                item.put("groupName",dep.get("departmentName"));
	                            }
	                    	}
	                	}
	                	
	        			
	        		});       		
	        	}
				
				
				
				List<PointUserSyn3DRespone> users = new ArrayList<PointUserSyn3DRespone>();
				Map<String,PointUserSyn3DRespone> map = new HashMap<String, PointUserSyn3DRespone>();
				PointInfoSyn3DRespone pointInfoResponse = new PointInfoSyn3DRespone();
				if(!result.isEmpty()){
					result.forEach(action->{
						pointInfoResponse.setPointId(getValue(action.get("pointId")));
						pointInfoResponse.setPointName(getValue(action.get("pointName")));
						pointInfoResponse.setPointLevel(getValue(action.get("pointLevel")));
						pointInfoResponse.setStatus(getValue(action.get("status")));
						pointInfoResponse.setCoordinates(getValue(action.get("coordinates")));
						pointInfoResponse.setOrgCode(getValue(action.get("defaultOrgCode")));
						if(action.get("floor") != null){
							PointPositionInfoSyn3DRespone config = new PointPositionInfoSyn3DRespone();
							config.setBelongObjModel("floor_"+getValue(action.get("floor")));
							config.setIsIndoor(Boolean.valueOf(action.get("isIndoor").toString()));
							pointInfoResponse.setNodeConfigDTO(config);
						}
						pointInfoResponse.setAddress(getValue(action.get("address")));
						if(action.get("userId") != null && !map.containsKey(action.get("userId").toString())){
							PointUserSyn3DRespone pointUserSyn3DRespone = new PointUserSyn3DRespone();
							pointUserSyn3DRespone.setUserId(getValue(action.get("userId")));
							pointUserSyn3DRespone.setUserName(getValue(action.get("userName")));
							pointUserSyn3DRespone.setOrgCode(getValue(action.get("orgCode")));
							pointUserSyn3DRespone.setGroupName(getValue(action.get("groupName")));
							map.put(action.get("userId").toString(), pointUserSyn3DRespone);
							users.add(pointUserSyn3DRespone);
						}
						pointInfoResponse.setIsDelete(getValue(action.get("is_delete")).equals("false") ? false : true);
					});
					pointInfoResponse.setUsers(users);
				}
				list.add(pointInfoResponse);
			});
//		     CommonResponse commonResponse = remote3DServer.pointInfoPush(toke, product, appKey,list);

		}
		return list;
	}
	
	private String getValue(Object value){
		if(value == null){
			return "";
		}
		return value.toString();
	}

	@Override
	public RouteResponse pushRouteInfoTo3D(String toke,String product,String appKey,List<Long> routeIds) {
		// TODO Auto-generated method stub
		RouteResponse routeResponse = new RouteResponse();
		Map<String,PatrolUserRespone> map = new HashMap<String, PatrolUserRespone>();
		List<RouteResponse> routeResponseList = new ArrayList<>();
		for (Long routeId : routeIds) {
			List<Map<String, Object>> routeList = routeMapper.getRouteInfoList(routeId);
			
			//安全获取用户名称，部门名称
			
			
			//安全处理
			
			
			//获取用户信息
        	List<String> userIds = new ArrayList<>();
        	List<String> depIds = new ArrayList<>();
        	if( routeList != null  ) {
        		routeList.forEach(item ->{
               
                if(!userIds.contains(item.get("userName"))&& !"".equals(item.get("userName")+"")) {
    				userIds.add((String) item.get("userName"));
    			}
                if(!userIds.contains(item.get("boss"))&& !"".equals(item.get("boss")+"")) {
    				userIds.add((String) item.get("boss"));
    			}
                
                
    			if(!depIds.contains(item.get("groupName"))&& !"".equals(item.get("groupName")+"")){
        			depIds.add(item.get("groupName").toString());
        		}
        	});	
        	
        	
        	
        	
        		routeList.forEach(item ->{
        			if(userIds!=null&&userIds.size()>0){
                		//设置执行人员和执行部门
                    	List<AgencyUserModel> listUsers = remoteSecurityService.listUserByUserIds(toke, product, appKey,
                    			Joiner.on(",").join(userIds));
                    	if( listUsers != null && listUsers.size() > 0){
                			List<AgencyUserModel> filterUser = listUsers.stream().filter(user -> user.getUserId().contains((String) item.get("userName"))).collect(Collectors.toList());
                			if(filterUser != null && filterUser.size() ==1) {
                				AgencyUserModel agencyUserModel = filterUser.get(0);      				
                				item.put("userName",agencyUserModel.getRealName()); 
                				
                			}
            				
                			List<AgencyUserModel> filterUser1 = listUsers.stream().filter(user -> user.getUserId().contains((String) item.get("boss"))).collect(Collectors.toList());
                			if(filterUser1 != null && filterUser1.size() ==1) {
                				AgencyUserModel agencyUserModel1 = filterUser1.get(0);      				
                				item.put("boss",agencyUserModel1.getRealName()); 
                				
                			}
            			}
                	}
        			if(depIds!=null&&depIds.size()>0){
                    	List<LinkedHashMap> listDepartments = remoteSecurityService.listDepartmentByDeptIds(toke, product, appKey,Joiner.on(",").join(depIds));
                    	if(  listDepartments != null && listDepartments.size() > 0) {
                    		List<LinkedHashMap> filterDep = listDepartments.stream().filter(d -> d.get("sequenceNbr").toString().equals(item.get("groupName"))).collect(Collectors.toList());
                			
                			if(filterDep != null && filterDep.size() > 0){
                				LinkedHashMap dep = filterDep.get(0);
                                item.put("groupName",dep.get("departmentName"));
                            }
                    	}
                	}
                	
        			
        		});       		
        	}
			
			
			RouteResponse routeInfo = new RouteResponse();
			if (!routeList.isEmpty()) {
				List<PatrolUserRespone> exeUserList = new ArrayList<>();
				routeList.forEach(item -> {
					routeInfo.setBoss(getValue(item.get("boss")));
					routeInfo.setIsDelete(getValue(item.get("isDelete")).equals("false") ? false : true);
					routeInfo.setRouteId(Integer.valueOf(getValue(item.get("routeId"))));
					routeInfo.setRouteName(getValue(item.get("routeName")));
					routeInfo.setTel(getValue(item.get("tel")));
					routeInfo.setOrgCode(getValue(item.get("defaultOrgCode")));
					if(item.get("userId")!=null && !map.containsKey(item.get("userId").toString())){
						PatrolUserRespone exeUser = new PatrolUserRespone();
						exeUser.setGroupName(getValue(item.get("groupName")));
						exeUser.setOrgCode(getValue(item.get("orgCode")));
						exeUser.setUserName(getValue(item.get("userName")));
						exeUser.setUserId(getValue(item.get("userId")));
						exeUserList.add(exeUser);
						map.put(item.get("userId").toString(), exeUser);
					}
					routeInfo.setPatrolUsers(exeUserList);
				});
				routeResponseList.add(routeInfo);
			}
		}
		//remoteServer.routeInfoPush(routeResponseList);
//		   CommonResponse commonResponse = remote3DServer.routeInfoPush(toke, product, appKey,routeResponseList);

		return routeResponse;
	}

	/**
	 * 推送巡检记录到业务
	 * 
	 */
	@Override
	public PointCheckInfoBusinessRespone pointCheckInfoPushToB(Long checkId) {
		PointStatusCache pointStatusCache = PointStatusCache.getInstance();
		//获取推送内容
		PointCheckInfoBusinessRespone pb = checkMapper.getCheckInfoBusinessById(checkId);

		if(ObjectUtils.isEmpty(pb)){
			return pb;
		}
		//获取到推送点的状态
		String pointStatus = pointStatusCache.getPointStatus(pb.getId());
		if (pointStatus != null) {
			if (!pointStatus.equals(pb.getNodeState())) {
				pointStatusCache.putPointStatus(pb.getId(), pb.getNodeState());
			}
		} else {
			pointStatusCache.putPointStatus(pb.getId(), pb.getNodeState());
		}
		CommonResponse commonResponse = business.checkStatusPushToB(pb);
		return pb;
	}


	
}
