package com.scpyun.platform.jilinsscgsdp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.DataSourceSwitcher;
import com.scpyun.base.core.utils.StringUtils;
import com.scpyun.base.core.utils.UnifyLogger;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.pojo.Point;
import com.scpyun.platform.jilinsscgsdp.utils.DisposeRedisStatisticsUtil;
import com.scpyun.platform.jilinsscgsdp.utils.GetUserRedisInfoUtil;
import com.scpyun.platform.jilinsscgsdp.utils.GridPointUtil;
import com.scpyun.platform.jilinsscgsdp.utils.Statistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 *
 * @Title:  SysOfficeLevelServiceImpl
 * @Package SysOfficeLevelServiceImpl.java
 * @Description: copy By scp-grid
 * @author:  guojiucoder
 * @date:   2024/7/31 14:09
 * @version V1.0.0
 *
 */
@Api("查询机构层级关系")
@Service("sysOfficeLevelService")
public class SysOfficeLevelServiceImpl {
	@Autowired
	private CommonService commonService;
	@Autowired
	SwitchServiceImpl switchService;
// 4 区  5街道  6 社区  7 网格  8 楼   9 单元  10 层  11 户
	private String namespace = "com.scpyun.platform.standard.jilinsscgsdp.sysOfficeinfo.";
	// 5 为社区     6画格
	@ApiOperation(value="添加下级（选择中心点）", desc="添加下级（选择中心点）")
	public String Coordinate(HttpServletRequest request,Map<String, Object> map){
		Map<String,Object> _userMap = (Map<String, Object>) map.get("_user");
		if(StringUtils.toInteger(map.get("grade"))<6) {
			DataSourceSwitcher.setMaster();
			DataSourceSwitcher.setSharding("sc");
			if(commonService.update(namespace+"updateOfficeCoordinate", map)!=1) {
				throw new CustomException("新增中心标记点失败！");
			}
			return "success";
		}else if(StringUtils.toInteger(map.get("grade"))==6) {
			if(!("5".equals(_userMap.get("company_grade")))){
				throw new CustomException("请登录社区帐号操作！");
			}
			if(StringUtils.isEmpty(map.get("csc_mapjson"))) {
				throw new CustomException("请为网格绘画区域！");
			}
			// 添加小区
			DataSourceSwitcher.setMaster();
			if(map.get("id") != null && !"".equals(map.get("id"))) {
				//修改
				this.disposeGridScope(map);// 判断所画网格是否与本社区其他网格有重合
				if(commonService.update(namespace+"updateGridGarden", map)!=1) {
					throw new CustomException("修改小区信息失败!");
				}
			}else {
				//新增
				String parent_ids=StringUtils.toString(map.get("parent_ids"));
				String x[]=parent_ids.split(",");
				map.put("area_id", x[x.length-2]);
				map.put("street_id", x[x.length-1]);
				map.put("parent_ids", parent_ids+StringUtils.toString(map.get("community_id"))+",");
				this.disposeGridScope(map);// 判断所画网格是否与本社区其他网格有重合
				String uuid = com.scpyun.base.utils.UUID.getUUID();
				map.put("uuid", uuid);
				if(commonService.insert(namespace+"insertGridGarden", map)!=1) {
					throw new CustomException("新增小区信息失败!");
				}
				GetUserRedisInfoUtil k = new GetUserRedisInfoUtil();
				k.getUserRedisInfo(request,uuid,StringUtils.toInteger(map.get("grade")));
			}		
			return "success";
		}else if(StringUtils.toInteger(map.get("grade"))==7){
			if(!("5".equals(_userMap.get("company_grade")))){
				throw new CustomException("请登录社区帐号操作！");
			}
			// 添加栋（楼）
			DataSourceSwitcher.setMaster();
			if(map.get("id") != null && !"".equals(map.get("id"))) {
				// 修改
				this.disposeBuildingScope(map); // 判断楼是否在网格内
				if(commonService.update(namespace+"updateGridBuilding", map)!=1) {
					throw new CustomException("修改楼信息失败！");
				}
			}else {
				switchService.changeSwitch();
				String garden_id=StringUtils.toString(map.get("garden_id"));
				Map<String, Object> resultMap=commonService.getObject(namespace+"getGridGardenById", map);
				if(resultMap==null) {
					throw new CustomException("新增楼信息失败，未查询到上级信息！");
				}
				map.put("area_id", resultMap.get("area_id"));
				map.put("street_id", resultMap.get("street_id"));
				map.put("community_id", resultMap.get("community_id"));
				map.put("parent_ids", resultMap.get("parent_ids")+garden_id+",");
				this.disposeBuildingScope(map); // 判断楼是否在网格内
				String uuid = com.scpyun.base.utils.UUID.getUUID();
				map.put("uuid", uuid);
				if(commonService.insert(namespace+"insertGridBuilding", map)!=1) {
					throw new CustomException("新增楼信息失败！");
				}
				GetUserRedisInfoUtil k = new GetUserRedisInfoUtil();
				k.getUserRedisInfo(request,uuid,StringUtils.toInteger(map.get("grade")));
			}
			return "success";
		}else {
			switchService.changeSwitch();
			// 添加单元(层和户走单独接口)
			DataSourceSwitcher.setMaster();
			if(map.get("id") != null && !"".equals(map.get("id"))) {
				// 修改
				if(commonService.update(namespace+"updateGridUnit", map)!=1) {
					throw new CustomException("修改楼信息失败！");
				}
			}else {
				String building_id=StringUtils.toString(map.get("building_id"));
				Map<String, Object> resultMap=commonService.getObject(namespace+"findBuildingById", map);
				if(resultMap==null) {
					throw new CustomException("新增单元信息失败，未查询到上级信息！");
				}
				map.put("area_id", resultMap.get("area_id"));
				map.put("street_id", resultMap.get("street_id"));
				map.put("community_id", resultMap.get("community_id"));
				map.put("garden_id", resultMap.get("garden_id"));
				map.put("parent_ids", resultMap.get("parent_ids")+building_id+",");
				if(commonService.insert(namespace+"insertGridUnit", map)!=1) {
					throw new CustomException("新增单元信息失败！");
				}
			}
			return "success";
		}
	}
	@ApiOperation(value="批量生成层和户", desc="批量生成层和户")
	public String createFloor(Map<String, Object> map) {
		switchService.changeSwitch();
		if (StringUtils.isEmpty(map.get("floorNum"))) {
    		throw new CustomException("缺少参数！");
    	}
		if (StringUtils.isEmpty(map.get("doorplateNum"))) {
    		throw new CustomException("缺少参数！");
    	}
		String unit_id=StringUtils.toString(map.get("unit_id"));
		int floorNum=0;
		int doorplateNum=0;
		try {
			floorNum=StringUtils.toInteger(map.get("floorNum"));
			doorplateNum=StringUtils.toInteger(map.get("doorplateNum"));
		} catch (Exception e) {
			throw new CustomException("请检查所填，层数，户数是否正确");
		}
		Map<String, Object> resultMap=commonService.getObject(namespace+"findUnitById", map);
		if(resultMap==null) {
			throw new CustomException("新增层信息失败，未查询到上级信息！");
		}
		map.put("area_id", resultMap.get("area_id"));
		map.put("street_id", resultMap.get("street_id"));
		map.put("community_id", resultMap.get("community_id"));
		map.put("garden_id", resultMap.get("garden_id"));
		map.put("building_id", resultMap.get("building_id"));
		map.put("company_code", resultMap.get("company_code"));
		for(int i=1;i<=floorNum;i++) {
			map.put("grade", "9");
			map.put("name", i);
			map.put("sort", i*100);
			map.put("uuid",UUID.randomUUID().toString());
			map.put("parent_ids", resultMap.get("parent_ids")+unit_id+",");
			commonService.insert(namespace+"insertGridFloor", map);
			for(int j=1;j<=doorplateNum;j++) {
				map.put("grade", "10");
				map.put("name", j);
				map.put("sort", j*100);
				map.put("floor_id", map.get("uuid"));
				map.put("parent_ids", resultMap.get("parent_ids")+unit_id+","+StringUtils.toString(map.get("floor_id"))+",");
				commonService.insert(namespace+"insertGridDoorplate", map);
//				System.out.println(map.get("parent_ids"));
			}
		}
		return "success";
	}
	@ApiOperation(value="单独生成层和户", desc="单独生成层和户")
	public String createFloorDoorplate(Map<String, Object> map){
		switchService.changeSwitch();
		if("floor".equals(map.get("type"))) {
			// 添加一层
			Map<String, Object> resultMap=commonService.getObject(namespace+"findUnitById", map);
			map.put("area_id", resultMap.get("area_id"));
			map.put("street_id", resultMap.get("street_id"));
			map.put("community_id", resultMap.get("community_id"));
			map.put("garden_id", resultMap.get("garden_id"));
			map.put("building_id", resultMap.get("building_id"));
			map.put("parent_ids", resultMap.get("parent_ids")+StringUtils.toString(map.get("unit_id"))+",");
			map.put("uuid",UUID.randomUUID().toString());
			map.put("company_code", resultMap.get("company_code"));
			if(commonService.insert(namespace+"insertGridFloor", map)!=1) {
				throw new CustomException("新增层失败！");
			}
		}else if("doorplate".equals(map.get("type"))){
			// 添加一户
			Map<String, Object> resultMap=commonService.getObject(namespace+"findFloorById", map);
			map.put("area_id", resultMap.get("area_id"));
			map.put("street_id", resultMap.get("street_id"));
			map.put("community_id", resultMap.get("community_id"));
			map.put("garden_id", resultMap.get("garden_id"));
			map.put("building_id", resultMap.get("building_id"));
			map.put("unit_id", resultMap.get("unit_id"));
			map.put("company_code", resultMap.get("company_code"));
			map.put("parent_ids", resultMap.get("parent_ids")+StringUtils.toString(map.get("floor_id"))+",");
			if(commonService.insert(namespace+"insertGridDoorplate", map)!=1) {
				throw new CustomException("新增户失败！");
			}
		}
		return "success";
	}
	@ApiOperation(value="删除层级下级户", desc="删除层级下级户")
	public String deleteFloor(Map<String, Object> map){
		if(commonService.update(namespace+"deleteFloor", map)==0) {
			throw new CustomException("删除层失败！");
		}
		commonService.update(namespace+"deleteDoorplatePl", map);
		return "success";
	}
	@ApiOperation(value="调整层顺序", desc="调整层顺序")
	public String updateFloorSort(Map<String, Object> map){
		String id1=StringUtils.toString(map.get("id1"));
		String id2=StringUtils.toString(map.get("id2"));
		map.put("floor_id", id1);
		Map<String, Object> map1=commonService.getObject(namespace+"findFloorById", map);
		if(map1==null) {
			throw new CustomException("未查询到数据");
		}
		map.put("floor_id", id2);
		Map<String, Object> map2=commonService.getObject(namespace+"findFloorById", map);
		if(map2==null) {
			throw new CustomException("未查询到数据");
		}
		int x=StringUtils.toInteger(map1.get("sort"));
		int y=StringUtils.toInteger(map2.get("sort"));
		map1.put("sort", y);
		if(commonService.update(namespace+"updateFloor", map1)!=1) {
			throw new CustomException("更新排序失败！");
		}
		map2.put("sort", x);
		if(commonService.update(namespace+"updateFloor", map2)!=1) {
			throw new CustomException("更新排序失败！");
		}
		return "success";
	}
	@ApiOperation(value="网格查询下级(列表展示数据)", desc="网格查询下级(列表展示数据)")
	public List<Map<String, Object>> findSubordinateList(Map<String, Object> map){
		if(StringUtils.toInteger(map.get("grade"))<5) {
			//查询office
			DataSourceSwitcher.setSharding("sc");
			DataSourceSwitcher.setSlave();
			return commonService.findList(namespace+"findSubordinateList", map);
		}else if(StringUtils.toInteger(map.get("grade"))==5){
			//社区层级，查询社区下级（小区）
			return commonService.findList(namespace+"findCommunityXJList", map);
		}else if(StringUtils.toInteger(map.get("grade"))==6){
			//小区层级，查询小区（栋）
			List<Map<String, Object>> list1=commonService.findList(namespace+"findGardenXJList", map);
//			List<Map<String, Object>> list2=commonService.findList(namespace+"findzdrqByGardenNewList", map);
//			UnifyLogger.parent("list2:"+list2,UnifyLogger.Level.INFO);
//			if(list2.size()!=0) {
//				for(Map<String, Object> map1:list1) {
//					for(Map<String, Object> map2:list2) {
//						if(map1.get("id").equals(map2.get("building_id"))) {
//							map1.put("zd", true);
//						}
//					}
//				}
//			}
			return list1;
		}else if(StringUtils.toInteger(map.get("grade"))==7){
			//栋层级，查询栋（单元）
			return commonService.findList(namespace+"findBuildingXJList", map);
		}else {
			//单元层级，查询单元下级（楼层，户）
			List<Map<String, Object>> list=commonService.findList(namespace+"findUnitXJList", map);
			// 查询本单元包含重点人群的户
//			List<Map<String, Object>> zdlist=commonService.findList(namespace+"findzdrqByUnitNewList", map);
//			UnifyLogger.parent("zdlist"+zdlist,UnifyLogger.Level.INFO);
			if(list.size()!=0) {
				for(Map<String, Object> aMap:list) {
					map.put("floor_id", aMap.get("id"));
					List<Map<String, Object>> levelList=commonService.findList(namespace+"findFloorXJList", map);
//					if(zdlist.size()!=0) {
//						for(Map<String, Object> map1:levelList) {
//							for(Map<String, Object> map2:zdlist) {
//								if(map1.get("id").equals(map2.get("doorplate_id"))) {
//									map1.put("zd", true);
//								}
//							}
//						}
//					}
					aMap.put("children", levelList);
				}
				return list;
			}else {
				return new ArrayList<Map<String,Object>>();
			}		
		}
	}
	@ApiOperation(value="异步加载树形图部分（查询csc）", desc="异步加载树形图部分（查询csc）")
	public List<Map<String, Object>> findTreeList(Map<String, Object> map){
		if(5==StringUtils.toInteger(map.get("grade"))) {
			List<Map<String,Object>> list=commonService.findList(namespace+"findCommunityXJList", map);
			if(list.size()!=0) {
				for(Map<String, Object> amap:list) {
					amap.put("children", new ArrayList<Map<String,Object>>());
					amap.put("loading", false);
					amap.put("hasChild", true);
					Map<String, Object> ppMap=new HashMap<String, Object>();
					ppMap.put("garden_id", amap.get("id"));
					Map<String, Object> pMap=commonService.getObject(namespace+"getBuildingNum", ppMap);
					amap.put("BuildingNum", pMap.get("buildingnum"));
				}
			}
			return list;
		}else if(6==StringUtils.toInteger(map.get("grade"))) {
			List<Map<String,Object>> list=commonService.findList(namespace+"findGardenXJList", map);
			if(list.size()!=0) {
				for(Map<String, Object> amap:list) {
					amap.put("children", new ArrayList<Map<String,Object>>());
					amap.put("loading", false);
					amap.put("hasChild", true);
					Map<String, Object> ppMap=new HashMap<String, Object>();
					ppMap.put("building_id", amap.get("id"));
					amap.put("num", commonService.getObject(namespace+"getDoorplateNum", ppMap));
				}
			}
			return list;
		}else if(7==StringUtils.toInteger(map.get("grade"))) {
			List<Map<String,Object>> list=commonService.findList(namespace+"findBuildingXJList", map);
			if(list.size()!=0) {
				for(Map<String, Object> amap:list) {
					amap.put("children", new ArrayList<Map<String,Object>>());
					amap.put("loading", false);
					amap.put("hasChild", false);
				}
			}
			return list;
		}else {
			return new ArrayList<Map<String,Object>>();
		}	
	}
	@ApiOperation(value="sys_office树形图（查询sc）", desc="sys_office树形图（查询sc）")
	public Map<String, Object> findOfficeLevelList(Map<String, Object> map){
		DataSourceSwitcher.setSharding("sc");
		DataSourceSwitcher.setSlave();
		Map<String, Object> resultMap=commonService.getObject(namespace+"getOfficeInfoByCompanyCode", map);
		List<Map<String, Object>> list=commonService.findList(namespace+"findOfficeInfoList", map);
		Map<String, Object> _userMap = (Map<String, Object>) map.get("_user");
		return this.officeList(list,resultMap,_userMap);
	}
	
	@ApiOperation(value="arcgis地图通过copanycode获取fid", desc="arcgis地图通过copanycode获取fid")
	public Map<String, Object> getOfficeInfoByCompanyCode(Map<String, Object> map){
		DataSourceSwitcher.setSharding("sc");
		DataSourceSwitcher.setSlave();
		return commonService.getObject(namespace+"getOfficeInfoByCompanyCode", map);
	}
	
	public Map<String,Object> officeList(List<Map<String,Object>> list,Map<String, Object> map,Map<String, Object> userMap){
        List<Map<String,Object>> list1=new ArrayList<>();
        DataSourceSwitcher.setSharding("grid");
		DataSourceSwitcher.setSlave();
        List<Map<String, Object>> gradenList=new ArrayList<Map<String,Object>>();
        List<Map<String, Object>> buildingList=new ArrayList<Map<String,Object>>();
        if("2".equals(map.get("grade"))) {
        	gradenList=commonService.findList(namespace+"findGradenByAreaList", null);
            buildingList=commonService.findList(namespace+"findBuildingByAreaList", null);
        }
        if("3".equals(map.get("grade"))) { 
    		//此时查询街道部分统计
    		map.put("street_id", map.get("id"));
    		gradenList=commonService.findList(namespace+"findGradenByStreetList", map);
    		buildingList=commonService.findList(namespace+"findBuildingByStreetList", map);
    	}
    	if("4".equals(map.get("grade"))) { 
    		//此时查询社区部分统计
    		map.put("community_id", map.get("id"));
    		gradenList=commonService.findList(namespace+"findGradenBycommunityList", map);
    		buildingList=commonService.findList(namespace+"findBuildingBycommunityList", map);
    	}
        for (Map<String,Object> x : list) {
            Map<String,Object> mapArr = new LinkedHashMap<String, Object>();
            if(StringUtils.toString(map.get("id")).equals(x.get("parent_id"))){
            	mapArr.put("id", x.get("id"));
                mapArr.put("title", x.get("name"));
                mapArr.put("name", x.get("name"));
                mapArr.put("code", x.get("code"));
                mapArr.put("loading", false);        
                mapArr.put("grade", x.get("grade"));
                mapArr.put("csc_mapjson", x.get("csc_mapjson"));
                mapArr.put("parent_id", x.get("parent_id"));
                mapArr.put("parent_ids", x.get("parent_ids"));
                if("3".equals(x.get("grade"))) {
                	 if(gradenList!=null) {
                 		for(Map<String, Object> result:gradenList) {
                     		if(x.get("id").equals(result.get("area_id"))) {
                     			mapArr.put("gradenNum", result.get("num"));
                     		}
                     	}
                 	}
                     if(buildingList!=null) {
                 		for(Map<String, Object> result:buildingList) {
                     		if(x.get("id").equals(result.get("area_id"))) {
                     			mapArr.put("buildingNum", result.get("num"));
                     		}
                     	}
                 	}
                }
                if("4".equals(x.get("grade"))) {
               	 if(gradenList!=null) {
                		for(Map<String, Object> result:gradenList) {
                    		if(x.get("id").equals(result.get("street_id"))) {
                    			mapArr.put("gradenNum", result.get("num"));
                    		}
                    	}
                	}
                    if(buildingList!=null) {
                		for(Map<String, Object> result:buildingList) {
                    		if(x.get("id").equals(result.get("street_id"))) {
                    			mapArr.put("buildingNum", result.get("num"));
                    		}
                    	}
                	}
                }
                if("5".equals(x.get("grade"))) {
					mapArr.put("hasChild", true);
                  	 if(gradenList!=null) {
                   		for(Map<String, Object> result:gradenList) {
                       		if(x.get("id").equals(result.get("community_id"))) {
                       			mapArr.put("gradenNum", result.get("num"));
                       		}
                       	}
                   	}
                       if(buildingList!=null) {
                   		for(Map<String, Object> result:buildingList) {
                       		if(x.get("id").equals(result.get("community_id"))) {
                       			mapArr.put("buildingNum", result.get("num"));
                       		}
                       	}
                   	}
                   }
                mapArr.put("children", officeChild(x.get("id").toString(),x.get("grade").toString(),list));
                list1.add(mapArr);
            }
        }
        Map<String, Object> returnMap=map;
        returnMap.put("title", map.get("name"));
        Map<String, Object> sMap=new HashMap<String, Object>();
        Map<String, Object> tittleMap;
        if("2".equals(map.get("grade"))) {
            tittleMap=new HashMap<String, Object>();
        }else if("3".equals(map.get("grade"))) {
        	tittleMap=new HashMap<String, Object>();
        	tittleMap.put("area_id", map.get("id"));
        }else if("4".equals(map.get("grade"))) {
        	tittleMap=new HashMap<String, Object>();
        	tittleMap.put("street_id", map.get("id"));
        }else if("5".equals(map.get("grade"))) {
        	tittleMap=new HashMap<String, Object>();
        	tittleMap.put("community_id", map.get("id"));
        }else {
			throw new CustomException("级别错误！");
		}
        tittleMap.put("_user", userMap);
        sMap=commonService.getObject(namespace+"getGardenNumNew", tittleMap);
        returnMap.put("gradenNum",sMap.get("gardennum"));
        sMap=commonService.getObject(namespace+"getBuildingNumNew", tittleMap);
        returnMap.put("buildingNum",sMap.get("buildingnum"));
        returnMap.put("children", list1);
        return returnMap;
    }

    public List<Map<String,Object>> officeChild(String id,String grade,List<Map<String,Object>> list){
    	Map<String, Object> map =new HashMap<String, Object>();
    	List<Map<String, Object>> gradenList=new ArrayList<Map<String,Object>>();
    	List<Map<String, Object>> buildingList = new ArrayList<Map<String,Object>>(); 
    	if("3".equals(grade)) { 
    		//此时查询街道部分统计
    		map.put("street_id", id);
    		gradenList=commonService.findList(namespace+"findGradenByStreetList", map);
    		buildingList=commonService.findList(namespace+"findBuildingByStreetList", map);
    	}
    	if("4".equals(grade)) { 
    		//此时查询社区部分统计
    		map.put("community_id", id);
    		gradenList=commonService.findList(namespace+"findGradenBycommunityList", map);
    		buildingList=commonService.findList(namespace+"findBuildingBycommunityList", map);
    	}
        List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
        for(Map<String,Object> a:list){
            Map<String,Object> childArray = new LinkedHashMap<String, Object>();
            if(id.equals(a.get("parent_id"))){
            	childArray.put("id", a.get("id"));
            	childArray.put("title", a.get("name"));
            	childArray.put("name", a.get("name"));
            	childArray.put("code", a.get("code"));
            	childArray.put("loading", false);
            	childArray.put("grade", a.get("grade"));
            	childArray.put("csc_mapjson", a.get("csc_mapjson"));
            	childArray.put("parent_id", a.get("parent_id"));
            	childArray.put("parent_ids", a.get("parent_ids"));
            	System.out.println(childArray.get("name"));
            	System.out.println(childArray.get("grade"));
            	if("4".equals(a.get("grade"))) {
            		if(gradenList!=null) {
                		for(Map<String, Object> result:gradenList) {
                    		if(a.get("id").equals(result.get("street_id"))) {
                    			childArray.put("gradenNum", result.get("num"));
                    		}
                    	}
                	}
                    if(buildingList!=null) {
                		for(Map<String, Object> result:buildingList) {
                    		if(a.get("id").equals(result.get("street_id"))) {
                    			childArray.put("buildingNum", result.get("num"));
                    		}
                    	}
                	}
            	}
            	if("5".equals(a.get("grade"))) {
            		childArray.put("hasChild", true);
            		if(gradenList!=null) {
                		for(Map<String, Object> result:gradenList) {
                    		if(a.get("id").equals(result.get("community_id"))) {
                    			childArray.put("gradenNum", result.get("num"));
                    		}
                    	}
                	}
                    if(buildingList!=null) {
                		for(Map<String, Object> result:buildingList) {
                    		if(a.get("id").equals(result.get("community_id"))) {
                    			childArray.put("buildingNum", result.get("num"));
                    		}
                    	}
                	}
            	}
            	childArray.put("children", officeChild(a.get("id").toString(),a.get("grade").toString(),list));
                lists.add(childArray);
            }
        }
        return lists;
    }
    @ApiOperation(value="统计", desc="统计")
    public Map<String, Object> getStatistics(Map<String, Object> map){
    	DisposeRedisStatisticsUtil tj=new DisposeRedisStatisticsUtil();
    	Map<String, Object> resultMap=new HashMap<String, Object>();
    	if("2".equals(map.get("grade"))) {
    		// LM
    		
    		DataSourceSwitcher.setSharding("sc");
    		DataSourceSwitcher.setSlave();

    		// 查询区数
    		resultMap.putAll(commonService.getObject(namespace+"getAreaNum", map));
    		// 查询街道数
    		resultMap.putAll(commonService.getObject(namespace+"getStreetNum", map));

    		// 查询社区数
    		resultMap.putAll(commonService.getObject(namespace+"getCommunityNum", map));
    		
    		DataSourceSwitcher.setSharding("grid");
    		DataSourceSwitcher.setSlave();

    		// 查询网格数
    		resultMap.putAll(commonService.getObject(namespace+"getGardenNum", map));
    		// 查询楼数
			resultMap.putAll(commonService.getObject(namespace+"getBuildingNum", map));

			// 统计查询户数
			Map<String, String> doorplateMap=new HashMap<String, String>();
			try {
				doorplateMap=tj.getStatisticsInfo(StringUtils.toString(map.get("id")), Statistics.doorplateNum);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(doorplateMap==null) {			
				Map<String, Object> rMap=commonService.getObject(namespace+"getDoorplateNum", map);
				resultMap.putAll(rMap);
				Map<String, String> sMap=new HashMap<String, String>();
				sMap.put("doorplatenum", rMap.get("doorplatenum").toString());
				sMap.put("time", this.getTime());
				tj.setRedisInfo("doorplateNum", StringUtils.toString(map.get("id")), sMap);
			}else {
				resultMap.put("doorplatenum", doorplateMap.get("doorplatenum"));
				resultMap.put("doorplatenum_time", doorplateMap.get("time"));
			}

			// 查询人数
			resultMap.putAll(commonService.getObject(namespace+"getUserNumByLm", map));

    	}else if("3".equals(map.get("grade"))){
			// 区
    		
    		DataSourceSwitcher.setSharding("sc");
    		DataSourceSwitcher.setSlave();
    		
    		// 查询街道数
    		resultMap.putAll(commonService.getObject(namespace+"getStreetNum", map));
    		// 查询社区数
    		resultMap.putAll(commonService.getObject(namespace+"getCommunityNum", map));
    		
    		DataSourceSwitcher.setSharding("grid");
    		DataSourceSwitcher.setSlave();
    		
    		// 查询网格数
    		resultMap.putAll(commonService.getObject(namespace+"getGardenNum", map));
    		// 查询楼数
			resultMap.putAll(commonService.getObject(namespace+"getBuildingNum", map));

			// 统计查询户数
			Map<String, String> doorplateMap=new HashMap<String, String>();
			try {
				doorplateMap=tj.getStatisticsInfo(StringUtils.toString(map.get("id")), Statistics.doorplateNum);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(doorplateMap==null) {			
				Map<String, Object> rMap=commonService.getObject(namespace+"getDoorplateNum", map);
				resultMap.putAll(rMap);
				Map<String, String> sMap=new HashMap<String, String>();
				sMap.put("doorplatenum", rMap.get("doorplatenum").toString());
				sMap.put("time", this.getTime());
				tj.setRedisInfo("doorplateNum", StringUtils.toString(map.get("id")), sMap);
			}else {
				resultMap.put("doorplatenum", doorplateMap.get("doorplatenum"));
				resultMap.put("doorplatenum_time", doorplateMap.get("time"));
			}
			
			// 统计查询人数
			Map<String, String> peopleMap=new HashMap<String, String>();
			try {
				peopleMap=tj.getStatisticsInfo(StringUtils.toString(map.get("area_id")), Statistics.peopleNum);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(peopleMap==null) {			
				Map<String, Object> rMap=commonService.getObject(namespace+"getUserNum", map);
				resultMap.putAll(rMap);
				Map<String, String> sMap=new HashMap<String, String>();
				sMap.put("num", rMap.get("usernum").toString());
				sMap.put("time", this.getTime());
				tj.setRedisInfo("peopleNum", StringUtils.toString(map.get("area_id")), sMap);
			}else {
				resultMap.put("usernum", peopleMap.get("num"));
				resultMap.put("usernum_time", peopleMap.get("time"));
			}
			
		}else if("4".equals(map.get("grade"))){
			// 街道
			
			DataSourceSwitcher.setSharding("sc");
    		DataSourceSwitcher.setSlave();
    		
    		resultMap.putAll(commonService.getObject(namespace+"getCommunityNum", map));
    		
			DataSourceSwitcher.setSharding("grid");
    		DataSourceSwitcher.setSlave();
    		
			resultMap.putAll(commonService.getObject(namespace+"getGardenNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getBuildingNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getDoorplateNum", map));
			
			// 查询人数
			Map<String, String> peopleMap=new HashMap<String, String>();
			try {
				peopleMap=tj.getStatisticsInfo(StringUtils.toString(map.get("street_id")), Statistics.peopleNum);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(peopleMap==null) {
				Map<String, Object> rMap=commonService.getObject(namespace+"getUserNum", map);
				resultMap.putAll(rMap);
				Map<String, String> sMap=new HashMap<String, String>();
				sMap.put("num", rMap.get("usernum").toString());
				sMap.put("time", this.getTime());
				tj.setRedisInfo("peopleNum", StringUtils.toString(map.get("street_id")), sMap);
			}else {
				resultMap.put("usernum", peopleMap.get("num"));
				resultMap.put("usernum_time", peopleMap.get("time"));
			}
			
		}else if("5".equals(map.get("grade"))) {
			// 社区
			resultMap.putAll(commonService.getObject(namespace+"getGardenNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getBuildingNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getDoorplateNum", map));
			
			// 查询人数
			Map<String, String> peopleMap=new HashMap<String, String>();
			try {
				peopleMap=tj.getStatisticsInfo(StringUtils.toString(map.get("community_id")), Statistics.peopleNum);
			} catch (Exception e) {
				// TODO: handle exception
			}
			if(peopleMap==null) {
				Map<String, Object> rMap=commonService.getObject(namespace+"getUserNum", map);
				resultMap.putAll(rMap);
				Map<String, String> sMap=new HashMap<String, String>();
				sMap.put("num", rMap.get("usernum").toString());
				sMap.put("time", this.getTime());
				tj.setRedisInfo("peopleNum", StringUtils.toString(map.get("community_id")), sMap);
			}else {
				resultMap.put("usernum", peopleMap.get("num"));
				resultMap.put("usernum_time", peopleMap.get("time"));
			}
			
		}else if("6".equals(map.get("grade"))) {
			
			// 小区
			resultMap.putAll(commonService.getObject(namespace+"getBuildingNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getDoorplateNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getUserNum", map));
			
		}else if("7".equals(map.get("grade"))) {
			
			// 楼
			resultMap.putAll(commonService.getObject(namespace+"getDoorplateNum", map));
			resultMap.putAll(commonService.getObject(namespace+"getUserNum", map));
			
		}else {
			throw new CustomException("未查询到改级别信息");
		}
    	return resultMap;
    }
    @ApiOperation(value="新增用户网格数据", desc="新增用户网格数据")
    public String createGridUserInfo(Map<String, Object> map){
    	if(map.get("id") != null && !"".equals(map.get("id"))) {
    		// 
    		if(commonService.update(namespace+"updateGridUserInfo", map)!=1) {
    			throw new CustomException("修改网格数据失败！");
    		}
    	}
    	Map<String, Object> resultMap=commonService.getObject(namespace+"getDoorplateById", map);
    	if(resultMap==null) {
    		throw new CustomException("未查询到数据！");
    	}
    	resultMap.put("doorplate_id", map.get("doorplate_id"));
    	resultMap.put("name", map.get("name"));
    	resultMap.put("cardno", map.get("cardno"));
    	resultMap.put("_user", map.get("_user"));
    	UnifyLogger.parent("入参map：---------"+resultMap);
    	if(commonService.insert(namespace+"creatGridUser", resultMap)!=1) {
    		throw new CustomException("保存网格信息失败！");
    	}
    	return "success";
    }
    @ApiOperation(value="点击网格查询数据", desc="点击网格查询数据")
    public Map<String, Object> getGridByGardenId(Map<String, Object> map){
    	if(StringUtils.isEmpty(map.get("csc_mapjson"))) {
    		throw new CustomException("缺少参数！");
    	}
    	Map<String, Object> aMap=new HashMap<String, Object>();
    	
    	
    	switch (StringUtils.toInteger(map.get("grade"))) {
		case 6:
			aMap=commonService.getObject(namespace+"getGardenByCoordinates", map);
			break;
		case 7:
			aMap=commonService.getObject(namespace+"getBuildingByCoordinates", map);
			break;
		}
    	if(aMap==null) {
    		throw new CustomException("未查询到信息！");
    	}
    	Map<String, Object> tMap=new HashMap<String, Object>();
    	switch (StringUtils.toInteger(map.get("grade"))) {
		case 6:
			tMap.put("garden_id", aMap.get("id"));
			break;
		case 7:
			tMap.put("building_id", aMap.get("id"));
			break;
		}
    	tMap.put("grade", aMap.get("grade"));
    	Map<String, Object> returnMap=new HashMap<String, Object>();
    	returnMap.put("info", aMap);
//    	returnMap.put("statistics", this.getStatistics(tMap));
    	return returnMap;
    }
    @ApiOperation(value="根据company_code查询坐标", desc="根据company_code查询坐标")
    public Map<String, Object> getMapJsonByCompanyCode(Map<String, Object> map){
    	DataSourceSwitcher.setSlave();
    	DataSourceSwitcher.setSharding("sc");
    	Map<String, Object> resultMap=commonService.getObject(namespace+"getOfficeInfoByCompanyCode", map);
    	if(resultMap == null) {
    		throw new CustomException("未查询到数据！");
    	}
    	return resultMap;
    }
    public String getTime() {
    	Date day=new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeString=df.format(day);
		return timeString;
    }
    @ApiOperation(desc = "查询楼根据社区",value = "查询楼根据社区")
    public List<Map<String, Object>> findBuildingListByCommunity(Map<String, Object> map){
    	List<Map<String, Object>> list1=commonService.findList(namespace+"findBuildByCommunityList", map);
//    	List<Map<String, Object>> list2=commonService.findList(namespace+"findzdrqByCommunityNewList", map);
//    	if(list2.size()!=0) {
//    		for(Map<String, Object> map1:list1) {
//				for(Map<String, Object> map2:list2) {
//					if(map1.get("id").equals(map2.get("building_id"))) {
//						map1.put("zd", true);
//					}
//				}
//			}
//    	}
    		return list1;
    }
    
    @ApiOperation(desc = "地图画格校验",value = "地图画格校验")
    public Map<String, Object> disposeGridScope(Map<String, Object> map){
    	// 查询当前社区所画网格
    	List<Map<String, Object>> list = commonService.findList(namespace+"findGridGardenList", map);
    	if(list.size() > 0) {
    		for(Map<String, Object> aMap : list) {
    			GridPointUtil gridPointUtil = new GridPointUtil();
    			Boolean result = gridPointUtil.disposeMapJson(StringUtils.toString(map.get("csc_mapjson")), StringUtils.toString(aMap.get("csc_mapjson")));
    			if(result) {
    				throw new CustomException("当前所画网格，已经与本社区====="+aMap.get("name")+"=====所重合！请重新绘画网格！");
    			}
    		}
    	}
    	return map;
    }
    public Map<String, Object> disposeBuildingScope(Map<String, Object> map){
    	List<Map<String, Object>> list = commonService.findList(namespace+"findBuildingByCscMapjsonList", map);
    	if(list.size() > 0) {
    		throw new CustomException("当前楼坐标点与"+list.get(0).get("graden_name")+"---"+list.get(0).get("building_name")+"坐标点重复！");
    	}
    	Map<String, Object> resultMap=commonService.getObject(namespace+"getGridGardenById", map);
		if(resultMap==null) {
			throw new CustomException("新增楼信息失败，未查询到上级信息！");
		}
		JSONArray oldJsonArray=JSONArray.parseArray(StringUtils.toString(resultMap.get("csc_mapjson")));
		Point[] ps = new Point[oldJsonArray.size()];
		for(int i=0;i<oldJsonArray.size();i++) {
			String x = StringUtils.toString(oldJsonArray.get(i));
			JSONArray oldJsonArray1 = JSONArray.parseArray(x);
			ps[i] = new Point(StringUtils.toDouble(oldJsonArray1.get(0)), StringUtils.toDouble(oldJsonArray1.get(1)));
		}
		String csc_mapjson = StringUtils.toString(map.get("csc_mapjson"));
		if(!GridPointUtil.isPtInPoly(StringUtils.toDouble(csc_mapjson.split(",")[0]), StringUtils.toDouble(csc_mapjson.split(",")[1]), ps)) {
			throw new CustomException("当前楼坐标超出所规划的网格范围！");
		}
    	return map;
    }
    @ApiOperation(desc = "查询村统计",value = "查询村统计")
    public Map<String, Object> getCunNum(Map<String, Object> map){
    	Map<String, Object> cunMap = commonService.getObject(namespace+"getCunNum", map);
    	Map<String, Object> paintGridNum = commonService.getObject(namespace+"getCunPaintGridNum", map);
    	Map<String, Object> returnMap = new HashMap<String, Object>();
    	returnMap.put("cunNum", cunMap);
    	returnMap.put("cunPaintGridNum", paintGridNum);
    	return returnMap;
    }
}
