package org.springblade.modules.grid.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.building.entity.Building;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.floor.entity.Floor;
import org.springblade.community.floor.service.IFloorService;
import org.springblade.community.houseuser.dto.HouseuserDTO;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.room.entity.Room;
import org.springblade.community.room.service.IRoomService;
import org.springblade.community.unit.entity.Unit;
import org.springblade.community.unit.service.IUnitService;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.jobs.devicejob.entity.DeviceJob;
import org.springblade.jobs.devicejob.service.IDeviceJobService;
import org.springblade.modules.grid.dto.GridDTO;
import org.springblade.modules.grid.entity.Grid;
import org.springblade.modules.grid.vo.AgencyPerson;
import org.springblade.modules.grid.vo.CommunityCount;
import org.springblade.modules.grid.vo.GridStaticVO;
import org.springblade.modules.grid.vo.SmartDeviceStatic;
import org.springblade.modules.system.entity.DictBiz;
import org.springblade.modules.system.service.IDictBizService;
import org.springblade.openinterface.dto.smartdevice.SmartDeviceDto;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springblade.utils.SerializableUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created By lidexi in 2021/3/23
 **/
@RestController
@AllArgsConstructor
@RequestMapping("grid-community")
@Api(tags = "网格物业接口")
public class SzsqController {

	private final IAgencyService agencyService;
	private final IResidentialService residentialService;
	private final IBuildingService buildingService;
	private final IUnitService unitService;
	private final IFloorService floorService;
	private final IRoomService roomService;
	private final IHouseuserService houseuserService;

	private final IDictBizService dictBizService;
	private final IDeviceJobService deviceJobService;
	private final ISmartDeviceService smartDeviceService;
	private final RedisTemplate<String, String> redisTemplate;

	/**
	 * 分页
	 */
	@GetMapping("/agency/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网格根据areaCOde获取社区列表", notes = "传入areaCode(区code)")
	public R<List<Agency>> list(@RequestParam("areaCode") String areaCode) {
		List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().eq(Agency::getRegionArea, areaCode));
		return R.data(agencies);
	}

	/**
	 * 分页
	 */
	@GetMapping("/agency/listByids")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网格根据社区ids获取社区列表", notes = "社区ids")
	public R<List<Agency>> listByAgencyId(@RequestParam("agencyIds") String agencyIds) {
		List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().in(Agency::getId, agencyIds.split(",")));
		return R.data(agencies);
	}

	/**
	 * 分页
	 */
	@GetMapping("/residential/listByIds")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网格根据小区ids获取小区列表", notes = "小区ids")
	public R<List<Residential>> listByResidentialId(@RequestParam("agencyIds") String residentialIds) {
		List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().in(Residential::getId, residentialIds.split(",")));
		return R.data(residentials);
	}

	/**
	 * 分页
	 */
	@PostMapping("/static")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网格系统统计面板", notes = "网格系统统计面板")
	public R<GridStaticVO> staticScreen(@RequestBody Grid grid) {

		//先查缓存
		String redisKey = "grid:static:" + grid.getId();
		String value = redisTemplate.opsForValue().get(redisKey);
		if (value != null) {
			GridStaticVO gridStaticVO = null;
			try {
				gridStaticVO = (GridStaticVO) SerializableUtil.deserializeToObject(value);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return R.data(gridStaticVO);
		}

		//缓存中没有
		GridStaticVO gridStaticVO = null;
		if ("system".equals(grid.getBoundsType())) {//系统生成的网格  省市区级网格
			gridStaticVO = getStaticScreenForSystem(grid);
		} else if (grid.getAgencyIds() != null) {//社区网格
			gridStaticVO = getStaticForAgency(grid);

		} else if (grid.getResidentialIds() != null) {//小区网格
			gridStaticVO = getStaticForResidential(grid);
		}


		//存入缓存
		try {
			redisTemplate.opsForValue().set(redisKey, SerializableUtil.serializeToString(gridStaticVO));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return R.data(gridStaticVO);
	}


	/**
	 * 分页 住户表
	 */
	@PostMapping("/houseuserlist")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入houseuser")
	public R<IPage<Houseuser>> list(@RequestBody Map<String, Object> houseuserDto) {
		Map<String, Object> queryMap = (Map) houseuserDto.get("query");
		Query query = new Query();
		query.setSize(Integer.valueOf(queryMap.get("size").toString()));
		query.setCurrent(Integer.valueOf(queryMap.get("current").toString()));
		Map<String, Object> houseuser = (Map) houseuserDto.get("houseuser");

		if(houseuserDto.get("codePath") != null){//系统级
			String codePath = houseuserDto.get("codePath").toString();
			String orgPosition = codePath.substring(1, codePath.length());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = Condition.getQueryWrapper(houseuser, Houseuser.class).lambda();
			houseuserLambdaQueryWrapper.likeRight(Houseuser::getOrgPosition, orgPosition);
			IPage<Houseuser> pages = houseuserService.page(Condition.getPage(query), houseuserLambdaQueryWrapper);
			return R.data(pages);
		}else if(houseuserDto.get("agencyIds") != null){//社区
			List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().in(Agency::getId, houseuserDto.get("agencyIds").toString().split(",")));
			List<String> agencyOrgPosition = agencies.stream().map(Agency::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = new QueryWrapper<>(new Houseuser()).lambda().likeRight(Houseuser::getOrgPosition, agencyOrgPosition.get(0));
			for (int i = 1; i < agencies.size(); i++) {
				houseuserLambdaQueryWrapper.or().likeRight(Houseuser::getOrgPosition, agencyOrgPosition.get(i));
				IPage<Houseuser> pages = houseuserService.page(Condition.getPage(query), houseuserLambdaQueryWrapper);
				return R.data(pages);
			}
		}else if(houseuserDto.get("residentialIds") != null){//小区
			List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().in(Residential::getId, houseuserDto.get("residentialIds").toString().split(",")));
			List<String> residentialOrgPosition = residentials.stream().map(Residential::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = new QueryWrapper<>(new Houseuser()).lambda().likeRight(Houseuser::getOrgPosition, residentialOrgPosition.get(0));
			for (int i = 1; i < residentials.size(); i++) {
				houseuserLambdaQueryWrapper.or().likeRight(Houseuser::getOrgPosition, residentialOrgPosition.get(i));
				IPage<Houseuser> pages = houseuserService.page(Condition.getPage(query), houseuserLambdaQueryWrapper);
				return R.data(pages);
			}
		}

		return R.data(null);
	}

	/**
	 * 分页 只能设备表
	 */
	@PostMapping("/smartDeviceList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入houseuser")
	public R<IPage<SmartDevice>> smartDevicelist(@RequestBody Map<String, Object> smartDeviceDto) {
		Map<String, Object> queryMap = (Map) smartDeviceDto.get("query");
		Query query = new Query();
		query.setSize(Integer.valueOf(queryMap.get("size").toString()));
		query.setCurrent(Integer.valueOf(queryMap.get("current").toString()));
		Map<String, Object> smartDevice = (Map) smartDeviceDto.get("smartDevice");

		if(smartDeviceDto.get("codePath") != null){//系统级
			String codePath = smartDeviceDto.get("codePath").toString();
			String orgPosition = codePath.substring(1, codePath.length());
			LambdaQueryWrapper<SmartDevice> smartDeviceLambdaQueryWrapper = Condition.getQueryWrapper(smartDevice, SmartDevice.class).lambda();
			smartDeviceLambdaQueryWrapper.likeRight(SmartDevice::getOrgPosition, orgPosition);
			IPage<SmartDevice> pages = smartDeviceService.page(Condition.getPage(query), smartDeviceLambdaQueryWrapper);
			return R.data(pages);
		}else if(smartDeviceDto.get("agencyIds") != null){//社区
			List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().in(Agency::getId, smartDeviceDto.get("agencyIds").toString().split(",")));
			List<String> agencyOrgPosition = agencies.stream().map(Agency::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<SmartDevice> smartDeviceLambdaQueryWrapper = new QueryWrapper<>(new SmartDevice()).lambda().likeRight(SmartDevice::getOrgPosition, agencyOrgPosition.get(0));
			for (int i = 1; i < agencies.size(); i++) {
				smartDeviceLambdaQueryWrapper.or().likeRight(SmartDevice::getOrgPosition, agencyOrgPosition.get(i));
				IPage<SmartDevice> pages = smartDeviceService.page(Condition.getPage(query), smartDeviceLambdaQueryWrapper);
				return R.data(pages);
			}
		}else if(smartDeviceDto.get("residentialIds") != null){//小区
			List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().in(Residential::getId, smartDeviceDto.get("residentialIds").toString().split(",")));
			List<String> residentialOrgPosition = residentials.stream().map(Residential::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<SmartDevice> smartDeviceLambdaQueryWrapper = new QueryWrapper<>(new SmartDevice()).lambda().likeRight(SmartDevice::getOrgPosition, residentialOrgPosition.get(0));
			for (int i = 1; i < residentials.size(); i++) {
				smartDeviceLambdaQueryWrapper.or().likeRight(SmartDevice::getOrgPosition, residentialOrgPosition.get(i));
				IPage<SmartDevice> pages = smartDeviceService.page(Condition.getPage(query), smartDeviceLambdaQueryWrapper);
				return R.data(pages);
			}
		}

		return R.data(null);

	}

	/**
	 * 分页
	 */
	@PostMapping("/getDeviceStaticByType")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网格系统统计面板", notes = "网格系统统计面板")
	public R<SmartDeviceStatic> getGridDeviceListByType(@RequestBody GridDTO gridDTO) {

		SmartDeviceStatic smartDeviceStatic = new SmartDeviceStatic();

		if ("system".equals(gridDTO.getBoundsType())) {//系统生成的网格  省市区级网格
			String orgPosition = gridDTO.getCodePath().substring(1, gridDTO.getCodePath().length());
			if (gridDTO.getDeviceType() != null) {
				smartDeviceStatic.setDeviceType(gridDTO.getDeviceType());
				List<SmartDevice> smartDevices = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getDeviceType, gridDTO.getDeviceType())
					.likeRight(SmartDevice::getOrgPosition, orgPosition));
				smartDeviceStatic.setCount(smartDevices.size());
				long normalCount = smartDevices.stream().filter(smartDevice -> smartDevice.getDeviceStatus() == 1).count();
				smartDeviceStatic.setNormalCount(Math.toIntExact(normalCount));
				smartDeviceStatic.setExceptionCount(smartDeviceStatic.getCount() - smartDeviceStatic.getNormalCount());
				return R.data(smartDeviceStatic);
			} else {
				smartDeviceStatic.setDeviceType(null);
				List<SmartDevice> smartDevices = smartDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new SmartDevice()).lambda()
					.likeRight(SmartDevice::getOrgPosition, orgPosition));
				smartDeviceStatic.setCount(smartDevices.size());
				long normalCount = smartDevices.stream().filter(smartDevice -> smartDevice.getDeviceStatus() == 1).count();
				smartDeviceStatic.setNormalCount(Math.toIntExact(normalCount));
				smartDeviceStatic.setExceptionCount(smartDeviceStatic.getCount() - smartDeviceStatic.getNormalCount());
				return R.data(smartDeviceStatic);
			}
		} else if (gridDTO.getAgencyIds() != null) {//社区网格
			String[] agencyIds = gridDTO.getAgencyIds().split(",");
			List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().in(Agency::getId, agencyIds));
			List<String> agencyOrgPosition = agencies.stream().map(Agency::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<SmartDevice> smartDeviceLambdaQueryWrapper = new QueryWrapper<>(new SmartDevice()).lambda().likeRight(SmartDevice::getOrgPosition, agencyOrgPosition.get(0));
			for (int i = 1; i < agencies.size(); i++) {
				smartDeviceLambdaQueryWrapper.or().likeRight(SmartDevice::getOrgPosition, agencyOrgPosition.get(i));
			}

			if(gridDTO.getDeviceType() != null){
				smartDeviceStatic.setDeviceType(gridDTO.getDeviceType());
				smartDeviceLambdaQueryWrapper.eq(SmartDevice::getDeviceType,gridDTO.getDeviceType());
			}
			List<SmartDevice> smartDevices = smartDeviceService.getBaseMapper().selectList(smartDeviceLambdaQueryWrapper);
			smartDeviceStatic.setCount(smartDevices.size());
			long normalCount = smartDevices.stream().filter(smartDevice -> smartDevice.getDeviceStatus() == 1).count();
			smartDeviceStatic.setNormalCount(Math.toIntExact(normalCount));
			smartDeviceStatic.setExceptionCount(smartDeviceStatic.getCount() - smartDeviceStatic.getNormalCount());
			return R.data(smartDeviceStatic);

		}else if (gridDTO.getResidentialIds() != null) {//小区网格
			String[] residentialIds = gridDTO.getResidentialIds().split(",");
			List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().in(Residential::getId, residentialIds));
			List<String> residentialOrgPosition = residentials.stream().map(Residential::getOrgPosition).collect(Collectors.toList());
			LambdaQueryWrapper<SmartDevice> smartDeviceLambdaQueryWrapper = new QueryWrapper<>(new SmartDevice()).lambda().likeRight(SmartDevice::getOrgPosition, residentialOrgPosition.get(0));
			for (int i = 1; i < residentials.size(); i++) {
				smartDeviceLambdaQueryWrapper.or().likeRight(SmartDevice::getOrgPosition, residentialOrgPosition.get(i));
			}

			if(gridDTO.getDeviceType() != null){
				smartDeviceStatic.setDeviceType(gridDTO.getDeviceType());
				smartDeviceLambdaQueryWrapper.eq(SmartDevice::getDeviceType,gridDTO.getDeviceType());
			}
			List<SmartDevice> smartDevices = smartDeviceService.getBaseMapper().selectList(smartDeviceLambdaQueryWrapper);
			smartDeviceStatic.setCount(smartDevices.size());
			long normalCount = smartDevices.stream().filter(smartDevice -> smartDevice.getDeviceStatus() == 1).count();
			smartDeviceStatic.setNormalCount(Math.toIntExact(normalCount));
			smartDeviceStatic.setExceptionCount(smartDeviceStatic.getCount() - smartDeviceStatic.getNormalCount());
			return R.data(smartDeviceStatic);

		}

		return R.data(null);
	}


	private GridStaticVO getStaticScreenForSystem(Grid grid) {
		GridStaticVO gridStaticVO = Objects.requireNonNull(BeanUtil.copy(grid, GridStaticVO.class));
		String orgPosition = grid.getCodePath().substring(1, grid.getCodePath().length());
		//社区总数
		LambdaQueryWrapper<Agency> agencyLambdaQueryWrapper = new QueryWrapper<>(new Agency()).lambda().likeRight(Agency::getOrgPosition, orgPosition);
		List<Agency> agencies = agencyService.getBaseMapper().selectList(agencyLambdaQueryWrapper);
		Integer agencyNum = agencies.size();
		CommunityCount agencyCount = new CommunityCount();
		agencyCount.setName("社区总数");
		agencyCount.setValue(agencyNum);

		//小区总数
		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapper<>(new Residential()).lambda().likeRight(Residential::getOrgPosition, orgPosition);
		Integer residentialNum = residentialService.getBaseMapper().selectCount(residentialLambdaQueryWrapper);
		CommunityCount residentialCount = new CommunityCount();
		residentialCount.setName("小区总数");
		residentialCount.setValue(residentialNum);
		//楼栋总数
		LambdaQueryWrapper<Building> buildingLambdaQueryWrapper = new QueryWrapper<>(new Building()).lambda().likeRight(Building::getOrgPosition, orgPosition);
		Integer buildingNum = buildingService.getBaseMapper().selectCount(buildingLambdaQueryWrapper);
		CommunityCount buildingCount = new CommunityCount();
		buildingCount.setName("楼栋总数");
		buildingCount.setValue(buildingNum);
		//单元总数
		LambdaQueryWrapper<Unit> unitLambdaQueryWrapper = new QueryWrapper<>(new Unit()).lambda().likeRight(Unit::getOrgPosition, orgPosition);
		Integer unitNum = unitService.getBaseMapper().selectCount(unitLambdaQueryWrapper);
		CommunityCount unitCount = new CommunityCount();
		unitCount.setName("单元总数");
		unitCount.setValue(unitNum);
		//楼层总数
		LambdaQueryWrapper<Floor> floorLambdaQueryWrapper = new QueryWrapper<>(new Floor()).lambda().likeRight(Floor::getOrgPosition, orgPosition);
		Integer floorNum = floorService.getBaseMapper().selectCount(floorLambdaQueryWrapper);
		CommunityCount floorCount = new CommunityCount();
		floorCount.setName("楼层总数");
		floorCount.setValue(floorNum);
		//房间总数
		LambdaQueryWrapper<Room> roomLambdaQueryWrapper = new QueryWrapper<>(new Room()).lambda().likeRight(Room::getOrgPosition, orgPosition);
		Integer roomNum = roomService.getBaseMapper().selectCount(roomLambdaQueryWrapper);
		CommunityCount roomCount = new CommunityCount();
		roomCount.setName("房间总数");
		roomCount.setValue(roomNum);


		gridStaticVO.getCommunityCounts().add(agencyCount);
		gridStaticVO.getCommunityCounts().add(residentialCount);
		gridStaticVO.getCommunityCounts().add(buildingCount);
		gridStaticVO.getCommunityCounts().add(unitCount);
		gridStaticVO.getCommunityCounts().add(floorCount);
		gridStaticVO.getCommunityCounts().add(roomCount);


		//物联网设备类型
		List<DictBiz> device_type = dictBizService.getList("device_type");
		gridStaticVO.setDeviceType(device_type);

		//设备工单
		LambdaQueryWrapper<DeviceJob> deviceJobLambdaQueryWrapper = new QueryWrapper<>(new DeviceJob()).lambda().likeRight(DeviceJob::getOrgPosition, orgPosition).last(" limit 10");
		List<DeviceJob> deviceJobs = deviceJobService.getBaseMapper().selectList(deviceJobLambdaQueryWrapper);

		gridStaticVO.setDeviceJobList(deviceJobs);


		//人口统计-按社区
		List<AgencyPerson> agencyPersons = new ArrayList<>();
		agencies.stream().forEach(agency -> {
			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName(agency.getAgencyName());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = new QueryWrapper<>(new Houseuser()).lambda().likeRight(Houseuser::getOrgPosition, agency.getOrgPosition());
			Integer houseNum = houseuserService.getBaseMapper().selectCount(houseuserLambdaQueryWrapper);
			agencyPerson.setPersonNum(houseNum);
			agencyPersons.add(agencyPerson);
		});

		List<AgencyPerson> agencyPersonList = agencyPersons.stream().sorted(Comparator.comparing(AgencyPerson::getPersonNum)).collect(Collectors.toList());
		Collections.reverse(agencyPersonList);
		if(agencyPersonList.size()>4){
			List<AgencyPerson> rankBefore = agencyPersonList.subList(0, 4);

			List<AgencyPerson> rankAfter = agencyPersonList.subList(4, agencyPersonList.size());

			Integer rankAfterTotal = rankAfter.stream().mapToInt(AgencyPerson::getPersonNum).sum();

			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName("其他");
			agencyPerson.setPersonNum(rankAfterTotal);

			rankBefore.add(agencyPerson);

			for (AgencyPerson agencyPerson1 : rankBefore) {
				gridStaticVO.getAgencyPerson().add(agencyPerson1);
			}
		}else{
			for (AgencyPerson agencyPerson1 : agencyPersonList) {
				gridStaticVO.getAgencyPerson().add(agencyPerson1);
			}
		}


		return gridStaticVO;
	}

	private GridStaticVO getStaticForAgency(Grid grid) {
		GridStaticVO gridStaticVO = Objects.requireNonNull(BeanUtil.copy(grid, GridStaticVO.class));
		String[] agencyIds = grid.getAgencyIds().split(",");
		CommunityCount agencyCount = new CommunityCount();
		agencyCount.setName("社区总数");
		agencyCount.setValue(agencyIds.length);

		//小区总数
		LambdaQueryWrapper<Residential> residentialLambdaQueryWrapper = new QueryWrapper<>(new Residential()).lambda().in(Residential::getAgencyId, agencyIds);
		Integer residentialNum = residentialService.getBaseMapper().selectCount(residentialLambdaQueryWrapper);
		CommunityCount residentialCount = new CommunityCount();
		residentialCount.setName("小区总数");
		residentialCount.setValue(residentialNum);
		//楼栋总数
		LambdaQueryWrapper<Building> buildingLambdaQueryWrapper = new QueryWrapper<>(new Building()).lambda().in(Building::getAgencyId, agencyIds);
		Integer buildingNum = buildingService.getBaseMapper().selectCount(buildingLambdaQueryWrapper);
		CommunityCount buildingCount = new CommunityCount();
		buildingCount.setName("楼栋总数");
		buildingCount.setValue(buildingNum);
		//单元总数
		LambdaQueryWrapper<Unit> unitLambdaQueryWrapper = new QueryWrapper<>(new Unit()).lambda().in(Unit::getAgencyId, agencyIds);
		Integer unitNum = unitService.getBaseMapper().selectCount(unitLambdaQueryWrapper);
		CommunityCount unitCount = new CommunityCount();
		unitCount.setName("单元总数");
		unitCount.setValue(unitNum);
		//楼层总数
		LambdaQueryWrapper<Floor> floorLambdaQueryWrapper = new QueryWrapper<>(new Floor()).lambda().in(Floor::getAgencyId, agencyIds);
		Integer floorNum = floorService.getBaseMapper().selectCount(floorLambdaQueryWrapper);
		CommunityCount floorCount = new CommunityCount();
		floorCount.setName("楼层总数");
		floorCount.setValue(floorNum);
		//房间总数
		LambdaQueryWrapper<Room> roomLambdaQueryWrapper = new QueryWrapper<>(new Room()).lambda().in(Room::getAgencyId, agencyIds);
		Integer roomNum = roomService.getBaseMapper().selectCount(roomLambdaQueryWrapper);
		CommunityCount roomCount = new CommunityCount();
		roomCount.setName("房间总数");
		roomCount.setValue(roomNum);


		gridStaticVO.getCommunityCounts().add(agencyCount);
		gridStaticVO.getCommunityCounts().add(residentialCount);
		gridStaticVO.getCommunityCounts().add(buildingCount);
		gridStaticVO.getCommunityCounts().add(unitCount);
		gridStaticVO.getCommunityCounts().add(floorCount);
		gridStaticVO.getCommunityCounts().add(roomCount);


		//物联网设备类型
		List<DictBiz> device_type = dictBizService.getList("device_type");
		gridStaticVO.setDeviceType(device_type);

		//设备工单
		List<Agency> agencies = agencyService.getBaseMapper().selectList(new QueryWrapper<>(new Agency()).lambda().in(Agency::getId, agencyIds));
		List<String> agencyOrgPositionList = agencies.stream().map(Agency::getOrgPosition).collect(Collectors.toList());
		LambdaQueryWrapper<DeviceJob> deviceJobLambdaQueryWrapper = new QueryWrapper<>(new DeviceJob()).lambda().likeRight(DeviceJob::getOrgPosition, agencyOrgPositionList.get(0));
		for (int i = 1; i < agencyOrgPositionList.size(); i++) {
			deviceJobLambdaQueryWrapper.or().likeRight(DeviceJob::getOrgPosition, agencyOrgPositionList.get(i));
		}
		deviceJobLambdaQueryWrapper.last("limit 10");
		List<DeviceJob> deviceJobs = deviceJobService.getBaseMapper().selectList(deviceJobLambdaQueryWrapper);

		gridStaticVO.setDeviceJobList(deviceJobs);


		//人口统计-按社区
		List<AgencyPerson> agencyPersons = new ArrayList<>();
		agencies.stream().forEach(agency -> {
			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName(agency.getAgencyName());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = new QueryWrapper<>(new Houseuser()).lambda().likeRight(Houseuser::getOrgPosition, agency.getOrgPosition());
			Integer houseNum = houseuserService.getBaseMapper().selectCount(houseuserLambdaQueryWrapper);
			agencyPerson.setPersonNum(houseNum);
			agencyPersons.add(agencyPerson);
		});

		List<AgencyPerson> agencyPersonList = agencyPersons.stream().sorted(Comparator.comparing(AgencyPerson::getPersonNum)).collect(Collectors.toList());
		Collections.reverse(agencyPersonList);
		if (agencyPersonList.size() > 5) {
			List<AgencyPerson> rankBefore = agencyPersonList.subList(0, 4);

			List<AgencyPerson> rankAfter = agencyPersonList.subList(4, agencyPersonList.size());

			Integer rankAfterTotal = rankAfter.stream().mapToInt(AgencyPerson::getPersonNum).sum();

			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName("其他");
			agencyPerson.setPersonNum(rankAfterTotal);

			rankBefore.add(agencyPerson);

			for (AgencyPerson agencyPerson1 : rankBefore) {
				gridStaticVO.getAgencyPerson().add(agencyPerson1);
			}
		} else {
			for (AgencyPerson agencyPerson1 : agencyPersonList) {
				gridStaticVO.getAgencyPerson().add(agencyPerson1);
			}
		}

		return gridStaticVO;
	}

	private GridStaticVO getStaticForResidential(Grid grid) {
		GridStaticVO gridStaticVO = Objects.requireNonNull(BeanUtil.copy(grid, GridStaticVO.class));
		String[] residentialIds = grid.getResidentialIds().split(",");

		//小区总数
		CommunityCount residentialCount = new CommunityCount();
		residentialCount.setName("小区总数");
		residentialCount.setValue(residentialIds.length);
		//楼栋总数
		LambdaQueryWrapper<Building> buildingLambdaQueryWrapper = new QueryWrapper<>(new Building()).lambda().in(Building::getResidentialId, residentialIds);
		Integer buildingNum = buildingService.getBaseMapper().selectCount(buildingLambdaQueryWrapper);
		CommunityCount buildingCount = new CommunityCount();
		buildingCount.setName("楼栋总数");
		buildingCount.setValue(buildingNum);
		//单元总数
		LambdaQueryWrapper<Unit> unitLambdaQueryWrapper = new QueryWrapper<>(new Unit()).lambda().in(Unit::getResidentialId, residentialIds);
		Integer unitNum = unitService.getBaseMapper().selectCount(unitLambdaQueryWrapper);
		CommunityCount unitCount = new CommunityCount();
		unitCount.setName("单元总数");
		unitCount.setValue(unitNum);
		//楼层总数
		LambdaQueryWrapper<Floor> floorLambdaQueryWrapper = new QueryWrapper<>(new Floor()).lambda().in(Floor::getResidentialId, residentialIds);
		Integer floorNum = floorService.getBaseMapper().selectCount(floorLambdaQueryWrapper);
		CommunityCount floorCount = new CommunityCount();
		floorCount.setName("楼层总数");
		floorCount.setValue(floorNum);
		//房间总数
		LambdaQueryWrapper<Room> roomLambdaQueryWrapper = new QueryWrapper<>(new Room()).lambda().in(Room::getResidentialId, residentialIds);
		Integer roomNum = roomService.getBaseMapper().selectCount(roomLambdaQueryWrapper);
		CommunityCount roomCount = new CommunityCount();
		roomCount.setName("房间总数");
		roomCount.setValue(roomNum);

		gridStaticVO.getCommunityCounts().add(residentialCount);
		gridStaticVO.getCommunityCounts().add(buildingCount);
		gridStaticVO.getCommunityCounts().add(unitCount);
		gridStaticVO.getCommunityCounts().add(floorCount);
		gridStaticVO.getCommunityCounts().add(roomCount);


		//物联网设备类型
		List<DictBiz> device_type = dictBizService.getList("device_type");
		gridStaticVO.setDeviceType(device_type);

		//设备工单
		List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().in(Residential::getId, residentialIds));
		List<String> residentialOrgPositionList = residentials.stream().map(Residential::getOrgPosition).collect(Collectors.toList());
		LambdaQueryWrapper<DeviceJob> deviceJobLambdaQueryWrapper = new QueryWrapper<>(new DeviceJob()).lambda().likeRight(DeviceJob::getOrgPosition, residentialOrgPositionList.get(0));

		for (int i = 1; i < residentialOrgPositionList.size(); i++) {
			deviceJobLambdaQueryWrapper.or().likeRight(DeviceJob::getOrgPosition, residentialOrgPositionList.get(i));
		}
		deviceJobLambdaQueryWrapper.last("limit 10");
		List<DeviceJob> deviceJobs = deviceJobService.getBaseMapper().selectList(deviceJobLambdaQueryWrapper);

		gridStaticVO.setDeviceJobList(deviceJobs);


		//人口统计-按小区
		List<AgencyPerson> residentialPersons = new ArrayList<>();
		residentials.stream().forEach(residential -> {
			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName(residential.getName());
			LambdaQueryWrapper<Houseuser> houseuserLambdaQueryWrapper = new QueryWrapper<>(new Houseuser()).lambda().likeRight(Houseuser::getOrgPosition, residential.getOrgPosition());
			Integer houseNum = houseuserService.getBaseMapper().selectCount(houseuserLambdaQueryWrapper);
			agencyPerson.setPersonNum(houseNum);
			residentialPersons.add(agencyPerson);
		});

		List<AgencyPerson> residentialPersonList = residentialPersons.stream().sorted(Comparator.comparing(AgencyPerson::getPersonNum)).collect(Collectors.toList());
		Collections.reverse(residentialPersonList);
		if (residentialPersonList.size() > 5) {
			List<AgencyPerson> rankBefore = residentialPersonList.subList(0, 4);

			List<AgencyPerson> rankAfter = residentialPersonList.subList(4, residentialPersonList.size());

			Integer rankAfterTotal = rankAfter.stream().mapToInt(AgencyPerson::getPersonNum).sum();

			AgencyPerson agencyPerson = new AgencyPerson();
			agencyPerson.setAgencyName("其他");
			agencyPerson.setPersonNum(rankAfterTotal);

			rankBefore.add(agencyPerson);

			for (AgencyPerson agencyPerson1 : rankBefore) {
				gridStaticVO.getAgencyPerson().add(agencyPerson1);
			}
		} else {
			for (AgencyPerson residentialPerson1 : residentialPersonList) {
				gridStaticVO.getAgencyPerson().add(residentialPerson1);
			}
		}

		return gridStaticVO;
	}
}
