package xiaoqu.home.open.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.export.GridExportOutput;
import xiaoqu.home.open.controller.input.grid.GridBatchAddInput;
import xiaoqu.home.open.controller.input.grid.GridDeleteInput;
import xiaoqu.home.open.controller.input.grid.GridInsertInput;
import xiaoqu.home.open.controller.input.grid.GridPageInput;
import xiaoqu.home.open.controller.input.grid.GridReadFileModel;
import xiaoqu.home.open.controller.input.grid.GridUpdateInput;
import xiaoqu.home.open.controller.input.workgroup.WorkGroupToPrincipalInput;
import xiaoqu.home.open.controller.output.FileUploadOutput;
import xiaoqu.home.open.controller.output.grid.GridOutput;
import xiaoqu.home.open.model.db1.Building;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.Floor;
import xiaoqu.home.open.model.db1.GridToPrincipal;
import xiaoqu.home.open.model.db1.MultistageGrid;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.PublicService;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.BuildingService;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db1.FloorService;
import xiaoqu.home.open.service.db1.GridToPrincipalService;
import xiaoqu.home.open.service.db1.MultistageGridService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.task.bean.DeleteEntityNotice;
import xiaoqu.home.open.task.bean.NameModifyNotice;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.StringUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;
import xiaoqu.home.open.utils.poi.ExcelUtil;

@Controller
@RequestMapping(value = "/grid")
@Api(value = "网格服务", description = "网格服务")
@Slf4j(topic = "Controller")
public class GridController {
	@Autowired
	private UserService userService;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private GridToPrincipalService gridToPrincipalService;
	@Autowired
	private BuildingService buildingService;
	@Autowired
	private FloorService floorService;
	@Autowired
	private PublicService publicService;
	@Autowired
	private MultistageGridService multistageGridService;
	@Autowired
	private RedisService5 redisService5;
	@Autowired
	private RedisService4 redisService4;
	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;

	public static void main(String[] args) throws Exception {
		List<GridOutput> outList = new ArrayList<GridOutput>();
		GridOutput gridOutput = new GridOutput();
		gridOutput.setCreateTime(new Date());
		gridOutput.setId(1L);
		outList.add(gridOutput);
		TimeUnit.SECONDS.sleep(1);
		GridOutput gridOutput1 = new GridOutput();
		gridOutput1.setCreateTime(new Date());
		gridOutput1.setId(2L);
		outList.add(gridOutput1);
		Collections.sort(outList, new Comparator<GridOutput>() {

			@Override
			public int compare(GridOutput o1, GridOutput o2) {
				if (o1.getCreateTime().after(o2.getCreateTime())) {
					return -1;
				} else {
					return 1;
				}
			}
		});
		for (GridOutput gridOutput2 : outList) {
			System.out.println(gridOutput2.getId());
		}

	}

	@ApiOperation(value = "网格查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<GridOutput>> pageList(HttpServletRequest request, @RequestBody GridPageInput input) {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点查询");
		}
		PageOutput<GridOutput> output = new PageOutput<GridOutput>();
		List<GridOutput> outList = new ArrayList<GridOutput>();

		if (input.getGridId() != null) {
			switch (input.getGridLevel()) {
			case 2:
				QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
				wrapperFloor.eq("district_id", input.getDistrictId());
				wrapperFloor.eq("building_id", input.getGridId());
				wrapperFloor.orderByDesc("create_time");
				Page<Floor> pageListFloor = new Page<Floor>(input.getPage(), input.getRows());
				List<Floor> listFloor = floorService.page(pageListFloor, wrapperFloor).getRecords();

				for (Floor floor : listFloor) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(floor, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", 2);
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListFloor.getCurrent());
				output.setRecords(pageListFloor.getTotal());
				output.setTotal(pageListFloor.getPages());
				output.setRows(outList);
				break;
			case 3:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid.eq("district_id", input.getDistrictId());
				wrapperMultistageGrid.eq("floor_id", input.getGridId());
				wrapperMultistageGrid.orderByDesc("create_time");
				Page<MultistageGrid> pageListMultistageGrid = new Page<MultistageGrid>(input.getPage(), input.getRows());
				List<MultistageGrid> listMultistageGrid = multistageGridService.page(pageListMultistageGrid, wrapperMultistageGrid).getRecords();

				for (MultistageGrid multistageGrid : listMultistageGrid) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", multistageGrid.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListMultistageGrid.getCurrent());
				output.setRecords(pageListMultistageGrid.getTotal());
				output.setTotal(pageListMultistageGrid.getPages());
				output.setRows(outList);
				break;
			case 4:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid2 = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid2.eq("district_id", input.getDistrictId());
				wrapperMultistageGrid2.eq("superior_id", input.getGridId());
				wrapperMultistageGrid2.orderByDesc("create_time");
				Page<MultistageGrid> pageListMultistageGrid2 = new Page<MultistageGrid>(input.getPage(), input.getRows());
				List<MultistageGrid> listMultistageGrid2 = multistageGridService.page(pageListMultistageGrid2, wrapperMultistageGrid2).getRecords();

				for (MultistageGrid multistageGrid : listMultistageGrid2) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", multistageGrid.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListMultistageGrid2.getCurrent());
				output.setRecords(pageListMultistageGrid2.getTotal());
				output.setTotal(pageListMultistageGrid2.getPages());
				output.setRows(outList);
				break;
			}
			return ResultResponseBeanUtil.success(output);
		}

		if (input.getUserId() != null) {// 负责人不为空就查中间表
			QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("user_id", input.getUserId());
			wrapper.eq("district_id", input.getDistrictId());
			if (input.getGridLevel() != null) {
				wrapper.eq("grid_level", input.getGridLevel());
			}
			if (input.getName() != null) {
				wrapper.like("name", input.getName());
			}
			wrapper.orderByDesc("create_time");
			Page<GridToPrincipal> pageList = new Page<GridToPrincipal>(input.getPage(), input.getRows());
			List<GridToPrincipal> gridToPrincipalList = gridToPrincipalService.page(pageList, wrapper).getRecords();
			for (GridToPrincipal gridToPrincipal : gridToPrincipalList) {
				GridOutput gridOutput = publicService.getGridByLevelAndId(gridToPrincipal.getGridLevel(), gridToPrincipal.getGridId());
				if (gridOutput==null) {
					gridToPrincipal.setSoftDelete(1);
					gridToPrincipalService.updateById(gridToPrincipal);
					continue;
				}
				outList.add(gridOutput);
			}
			Collections.sort(outList, new Comparator<GridOutput>() {
				@Override
				public int compare(GridOutput o1, GridOutput o2) {
					if (o1.getCreateTime().after(o2.getCreateTime())) {
						return -1;
					} else {
						return 1;
					}
				}
			});
			output.setPage(pageList.getCurrent());
			output.setRecords(pageList.getTotal());
			output.setTotal(pageList.getPages());
			output.setRows(outList);
			return ResultResponseBeanUtil.success(output);
		}

		if (input.getGridLevel() != null) {// 网格级别不为空就单查
			switch (input.getGridLevel()) {
			case 1:
				QueryWrapper<Building> wrapperBuilding = WrapperUtils.getWrapper(false);
				wrapperBuilding.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperBuilding.like("name", input.getName());
				}
				wrapperBuilding.orderByDesc("create_time");
				Page<Building> pageListBuilding = new Page<Building>(input.getPage(), input.getRows());
				List<Building> listBuilding = buildingService.page(pageListBuilding, wrapperBuilding).getRecords();

				for (Building building : listBuilding) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(building, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", 1);
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListBuilding.getCurrent());
				output.setRecords(pageListBuilding.getTotal());
				output.setTotal(pageListBuilding.getPages());
				output.setRows(outList);
				break;
			case 2:
				QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
				wrapperFloor.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperFloor.like("name", input.getName());
				}
				wrapperFloor.orderByDesc("create_time");
				Page<Floor> pageListFloor = new Page<Floor>(input.getPage(), input.getRows());
				List<Floor> listFloor = floorService.page(pageListFloor, wrapperFloor).getRecords();

				for (Floor floor : listFloor) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(floor, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", 2);
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListFloor.getCurrent());
				output.setRecords(pageListFloor.getTotal());
				output.setTotal(pageListFloor.getPages());
				output.setRows(outList);
				break;
			default:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperMultistageGrid.like("name", input.getName());
				}
				wrapperMultistageGrid.orderByDesc("create_time");
				Page<MultistageGrid> pageListMultistageGrid = new Page<MultistageGrid>(input.getPage(), input.getRows());
				List<MultistageGrid> listMultistageGrid = multistageGridService.page(pageListMultistageGrid, wrapperMultistageGrid).getRecords();

				for (MultistageGrid multistageGrid : listMultistageGrid) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", multistageGrid.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				output.setPage(pageListMultistageGrid.getCurrent());
				output.setRecords(pageListMultistageGrid.getTotal());
				output.setTotal(pageListMultistageGrid.getPages());
				output.setRows(outList);
				break;
			}
			return ResultResponseBeanUtil.success(output);
		} else {// 网格级别为空就一个一个的查 先查楼座 再查楼层，最后查多级网格
			QueryWrapper<Building> wrapperBuilding = WrapperUtils.getWrapper(false);
			wrapperBuilding.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperBuilding.like("name", input.getName());
			}
			input.setRows(1000);
			List<Building> listBuilding = buildingService.list(wrapperBuilding);

			for (Building building : listBuilding) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(building, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", 1);
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				if (StringUtil.isNotEmpty(list)) {
					List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
					for (GridToPrincipal gridToPrincipal : list) {
						WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
						User userTemp = userService.getById(gridToPrincipal.getUserId()); 
						workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
						workGroupToPrincipalInput.setMobile(userTemp.getMobile());
						workGroupToPrincipalInput.setName(userTemp.getName());
						userIds.add(workGroupToPrincipalInput);
					}
					gridOutput.setUserIds(userIds);
				}
				outList.add(gridOutput);
			}
			QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
			wrapperFloor.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperFloor.like("name", input.getName());
			}
			List<Floor> listFloor = floorService.list(wrapperFloor);

			for (Floor floor : listFloor) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(floor, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", 2);
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				if (StringUtil.isNotEmpty(list)) {
					List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
					for (GridToPrincipal gridToPrincipal : list) {
						WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
						User userTemp = userService.getById(gridToPrincipal.getUserId()); 
						workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
						workGroupToPrincipalInput.setMobile(userTemp.getMobile());
						workGroupToPrincipalInput.setName(userTemp.getName());
						userIds.add(workGroupToPrincipalInput);
					}
					gridOutput.setUserIds(userIds);
				}
				outList.add(gridOutput);
			}
			QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
			wrapperMultistageGrid.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperMultistageGrid.like("name", input.getName());
			}
			List<MultistageGrid> listMultistageGrid = multistageGridService.list(wrapperMultistageGrid);

			for (MultistageGrid multistageGrid : listMultistageGrid) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(multistageGrid, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", multistageGrid.getGridLevel());
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				if (StringUtil.isNotEmpty(list)) {
					List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
					for (GridToPrincipal gridToPrincipal : list) {
						WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
						User userTemp = userService.getById(gridToPrincipal.getUserId()); 
						workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
						workGroupToPrincipalInput.setMobile(userTemp.getMobile());
						workGroupToPrincipalInput.setName(userTemp.getName());
						userIds.add(workGroupToPrincipalInput);
					}
					gridOutput.setUserIds(userIds);
				}
				outList.add(gridOutput);
			}
			Collections.sort(outList, new Comparator<GridOutput>() {
				@Override
				public int compare(GridOutput o1, GridOutput o2) {
					if (o1.getCreateTime().after(o2.getCreateTime())) {
						return -1;
					} else {
						return 1;
					}
				}
			});
			output.setPage(1L);
			output.setRecords(Long.parseLong(outList.size() + ""));
			output.setTotal(1L);
			output.setRows(outList);
			return ResultResponseBeanUtil.success(output);
		}
	}

	@ApiOperation(value = "导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody GridPageInput input) throws IOException {
		List<GridOutput> outList = new ArrayList<GridOutput>();
		if (input.getGridId() != null) {
			switch (input.getGridLevel()) {
			case 2:
				QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
				wrapperFloor.eq("district_id", input.getDistrictId());
				wrapperFloor.eq("building_id", input.getGridId());
				wrapperFloor.orderByDesc("create_time");
				List<Floor> listFloor = floorService.list(wrapperFloor);
				for (Floor floor : listFloor) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(floor, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", 2);
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				break;
			case 3:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid.eq("district_id", input.getDistrictId());
				wrapperMultistageGrid.eq("floor_id", input.getGridId());
				wrapperMultistageGrid.orderByDesc("create_time");
				List<MultistageGrid> listMultistageGrid = multistageGridService.list(wrapperMultistageGrid);

				for (MultistageGrid multistageGrid : listMultistageGrid) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", multistageGrid.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				break;
			case 4:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid2 = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid2.eq("district_id", input.getDistrictId());
				wrapperMultistageGrid2.eq("superior_id", input.getGridId());
				wrapperMultistageGrid2.orderByDesc("create_time");
				List<MultistageGrid> listMultistageGrid2 = multistageGridService.list(wrapperMultistageGrid2);

				for (MultistageGrid multistageGrid : listMultistageGrid2) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", multistageGrid.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					if (StringUtil.isNotEmpty(list)) {
						List<WorkGroupToPrincipalInput> userIds = new ArrayList<WorkGroupToPrincipalInput>();
						for (GridToPrincipal gridToPrincipal : list) {
							WorkGroupToPrincipalInput workGroupToPrincipalInput = new WorkGroupToPrincipalInput();
							User userTemp = userService.getById(gridToPrincipal.getUserId()); 
							workGroupToPrincipalInput.setId(gridToPrincipal.getUserId());
							workGroupToPrincipalInput.setMobile(userTemp.getMobile());
							workGroupToPrincipalInput.setName(userTemp.getName());
							userIds.add(workGroupToPrincipalInput);
						}
						gridOutput.setUserIds(userIds);
					}
					outList.add(gridOutput);
				}
				break;
			}
		} else if (input.getUserId() != null) {// 负责人不为空就查中间表
			QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("user_id", input.getUserId());
			wrapper.eq("district_id", input.getDistrictId());
			if (input.getGridLevel() != null) {
				wrapper.eq("grid_level", input.getGridLevel());
			}
			if (input.getName() != null) {
				wrapper.like("name", input.getName());
			}
			List<GridToPrincipal> gridToPrincipalList = gridToPrincipalService.list(wrapper);
			for (GridToPrincipal gridToPrincipal : gridToPrincipalList) {
				GridOutput gridOutput = publicService.getGridByLevelAndId(gridToPrincipal.getGridLevel(), gridToPrincipal.getGridId());
				if (gridOutput==null) {
					gridToPrincipal.setSoftDelete(1);
					gridToPrincipalService.updateById(gridToPrincipal);
					continue;
				}
				outList.add(gridOutput);
			}
		} else if (input.getGridLevel() != null) {// 网格级别不为空就单查
			switch (input.getGridLevel()) {
			case 1:
				QueryWrapper<Building> wrapperBuilding = WrapperUtils.getWrapper(false);
				wrapperBuilding.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperBuilding.like("name", input.getName());
				}
				List<Building> listBuilding = buildingService.list(wrapperBuilding);

				for (Building building : listBuilding) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(building, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", gridOutput.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					outList.add(gridOutput);
				}
				break;
			case 2:
				QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
				wrapperFloor.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperFloor.like("name", input.getName());
				}
				List<Floor> listFloor = floorService.list(wrapperFloor);

				for (Floor floor : listFloor) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(floor, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", gridOutput.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					outList.add(gridOutput);
				}
				break;
			default:
				QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
				wrapperMultistageGrid.eq("district_id", input.getDistrictId());
				if (input.getName() != null) {
					wrapperMultistageGrid.like("name", input.getName());
				}
				List<MultistageGrid> listMultistageGrid = multistageGridService.list(wrapperMultistageGrid);

				for (MultistageGrid multistageGrid : listMultistageGrid) {
					GridOutput gridOutput = new GridOutput();
					BeanUtils.copyProperties(multistageGrid, gridOutput);
					QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("grid_id", gridOutput.getId());
					wrapper.eq("grid_level", gridOutput.getGridLevel());
					List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
					gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
					outList.add(gridOutput);
				}
				break;
			}
		} else {// 网格级别为空就一个一个的查 先查楼座 再查楼层，最后查多级网格
			QueryWrapper<Building> wrapperBuilding = WrapperUtils.getWrapper(false);
			wrapperBuilding.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperBuilding.like("name", input.getName());
			}
			List<Building> listBuilding = buildingService.list(wrapperBuilding);

			for (Building building : listBuilding) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(building, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", gridOutput.getGridLevel());
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				outList.add(gridOutput);
			}
			QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
			wrapperFloor.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperFloor.like("name", input.getName());
			}
			List<Floor> listFloor = floorService.list(wrapperFloor);

			for (Floor floor : listFloor) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(floor, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", gridOutput.getGridLevel());
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				outList.add(gridOutput);
			}
			QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
			wrapperMultistageGrid.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperMultistageGrid.like("name", input.getName());
			}
			List<MultistageGrid> listMultistageGrid = multistageGridService.list(wrapperMultistageGrid);

			for (MultistageGrid multistageGrid : listMultistageGrid) {
				GridOutput gridOutput = new GridOutput();
				BeanUtils.copyProperties(multistageGrid, gridOutput);
				QueryWrapper<GridToPrincipal> wrapper = WrapperUtils.getWrapper(false);
				wrapper.eq("grid_id", gridOutput.getId());
				wrapper.eq("grid_level", gridOutput.getGridLevel());
				List<GridToPrincipal> list = gridToPrincipalService.list(wrapper);
				gridOutput.setPrincipal(list.stream().map(gridToPrincipal -> gridToPrincipal.getUserName()).collect(Collectors.joining(",")));
				outList.add(gridOutput);
			}
		}
		User user = UserUtils.getUser(request);
		List<GridExportOutput> newList = new ArrayList<GridExportOutput>();
		for (GridOutput gridOutput : outList) {
			GridExportOutput gridExportOutput = new GridExportOutput();
			BeanUtils.copyProperties(gridOutput, gridExportOutput);
			newList.add(gridExportOutput);
		}
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<GridExportOutput> util = new ExcelUtil<GridExportOutput>(GridExportOutput.class);
		util.exportExcelByColumns(response, newList, "网格区域", exportColumns);
	}

	@ApiOperation(value = "删除网格")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public BaseOutput<String> delete(HttpServletRequest request, @RequestBody GridDeleteInput input) {
		User user = UserUtils.getUser(request);
		Long id = input.getId();
		Integer gridLevel = input.getGridLevel();
		if (id == null) {
			return ResultResponseBeanUtil.fail("请传递记录ID");
		}
		if (gridLevel == null) {
			return ResultResponseBeanUtil.fail("请传递网格级别");
		}
		if (gridLevel == 1) {
			return ResultResponseBeanUtil.fail("一级网格无法删除");
		}
		DeleteEntityNotice deleteEntityNotice = new DeleteEntityNotice();
		switch (gridLevel) {
		case 1:
			Building building = buildingService.getById(id);
			if (building == null) {
				return ResultResponseBeanUtil.fail("网格不存在");
			}
			if (building.getSoftDelete() == 1) {
				return ResultResponseBeanUtil.fail("网格是已删除状态");
			}
			QueryWrapper<Floor> wrapperFloor = WrapperUtils.getWrapper(false);
			wrapperFloor.eq("building_id", building.getId());
			int count99 = floorService.count(wrapperFloor);
			if (count99 > 0) {
				return ResultResponseBeanUtil.fail("网格存在下级，不能删除");
			}
			building.setModifyName(user.getName());
			building.setModifyId(user.getId());
			building.setModifyTime(new Date());
			building.setSoftDelete(1);
			buildingService.updateById(building);
			deleteEntityNotice.setId(building.getId());
			deleteEntityNotice.setLevel(1);
			deleteEntityNotice.setType(0);
			redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
			break;
		case 2:
			Floor floor = floorService.getById(id);
			if (floor == null) {
				return ResultResponseBeanUtil.fail("网格不存在");
			}
			if (floor.getSoftDelete() == 1) {
				return ResultResponseBeanUtil.fail("网格是已删除状态");
			}
			QueryWrapper<MultistageGrid> wrapperMultistageGrid = WrapperUtils.getWrapper(false);
			wrapperMultistageGrid.eq("superior_id", floor.getId());
			int count = multistageGridService.count(wrapperMultistageGrid);
			if (count > 0) {
				return ResultResponseBeanUtil.fail("网格存在下级，不能删除");
			}
			floor.setModifyName(user.getName());
			floor.setModifyId(user.getId());
			floor.setModifyTime(new Date());
			floor.setSoftDelete(1);
			floorService.updateById(floor);
			deleteEntityNotice.setId(floor.getId());
			deleteEntityNotice.setLevel(2);
			deleteEntityNotice.setType(0);
			redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
			break;
		default:
			MultistageGrid multistageGrid = multistageGridService.getById(id);
			if (multistageGrid == null) {
				return ResultResponseBeanUtil.fail("网格不存在");
			}
			if (multistageGrid.getSoftDelete() == 1) {
				return ResultResponseBeanUtil.fail("网格是已删除状态");
			}
			QueryWrapper<MultistageGrid> wrapperMultistageGrid1 = WrapperUtils.getWrapper(false);
			wrapperMultistageGrid1.eq("superior_id", multistageGrid.getId());
			int count1 = multistageGridService.count(wrapperMultistageGrid1);
			if (count1 > 0) {
				return ResultResponseBeanUtil.fail("网格存在下级，不能删除");
			}
			multistageGrid.setModifyName(user.getName());
			multistageGrid.setModifyId(user.getId());
			multistageGrid.setModifyTime(new Date());
			multistageGrid.setSoftDelete(1);
			multistageGridService.updateById(multistageGrid);
			deleteEntityNotice.setId(multistageGrid.getId());
			deleteEntityNotice.setLevel(multistageGrid.getGridLevel());
			deleteEntityNotice.setType(0);
			redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
			break;
		}
		return ResultResponseBeanUtil.success("删除成功");

	}

	@ApiOperation(value = "新增网格")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public BaseOutput<String> add(HttpServletRequest request, @RequestBody GridInsertInput input) {
		log.info("新增网格" + JSON.toJSONString(input));
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		if (input.getGridLevel() == null) {
			return ResultResponseBeanUtil.fail("请传递网格级别");
		}
		Integer gridLevel = input.getGridLevel();
		User user = UserUtils.getUser(request);
		String agentName = redisService5.get("name:Agent:" + district.getAgentId());
		String propertyName = redisService5.get("name:Properyt:" + district.getPropertyId());
		Long recordId = 0L;
		boolean flag1 = false;
		switch (gridLevel) {
		case 1:
			flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, null, null, input.getName());
			if (flag1) {
				return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
			}
			Building building = new Building();
			BeanUtils.copyProperties(input, building);
			building.setAgentId(district.getAgentId());
			building.setPropertyId(district.getPropertyId());
			building.setDistrictId(district.getId());
			building.setAgentName(agentName);
			building.setPropertyName(propertyName);
			building.setDistrictName(district.getDistrictName());
			building.setCreateName(user.getName());
			building.setCreateId(user.getId());
			building.setCreateTime(new Date());
			buildingService.save(building);
			recordId = building.getId();
			break;
		case 2:
			Floor floor = new Floor();
			BeanUtils.copyProperties(input, floor);
			floor.setAgentId(district.getAgentId());
			floor.setPropertyId(district.getPropertyId());
			floor.setDistrictId(district.getId());
			floor.setAgentName(agentName);
			floor.setPropertyName(propertyName);
			floor.setDistrictName(district.getDistrictName());
			floor.setCreateName(user.getName());
			floor.setCreateId(user.getId());
			floor.setCreateTime(new Date());
			Building building2 = buildingService.getById(input.getSuperiorId());
			if (building2 == null) {
				return ResultResponseBeanUtil.fail("上级网格不存在");
			}
			flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, building2.getId(), null, input.getName());
			if (flag1) {
				return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
			}
			floor.setSuperiorName(building2.getName());
			floor.setBuildingId(building2.getId());
			floorService.save(floor);
			recordId = floor.getId();
			break;
		default:
			MultistageGrid multistageGrid = new MultistageGrid();
			BeanUtils.copyProperties(input, multistageGrid);
			multistageGrid.setAgentId(district.getAgentId());
			multistageGrid.setPropertyId(district.getPropertyId());
			multistageGrid.setDistrictId(district.getId());
			multistageGrid.setAgentName(agentName);
			multistageGrid.setPropertyName(propertyName);
			multistageGrid.setDistrictName(district.getDistrictName());
			multistageGrid.setCreateName(user.getName());
			multistageGrid.setCreateId(user.getId());
			multistageGrid.setCreateTime(new Date());
			if (gridLevel == 3) {
				Floor floorT = floorService.getById(input.getSuperiorId());
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, floorT.getBuildingId(), floorT.getId(), input.getName());
				if (flag1) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				multistageGrid.setSuperiorName(floorT.getSuperiorName() + "->" + floorT.getName());
				multistageGrid.setBuildingId(floorT.getBuildingId());
				multistageGrid.setBuildingName(floorT.getSuperiorName());
				multistageGrid.setFloorId(floorT.getId());
				multistageGrid.setFloor(floorT.getName());
			} else {
				MultistageGrid multistageGridT = multistageGridService.getById(input.getSuperiorId());
				if (multistageGridT == null) {
					return ResultResponseBeanUtil.fail("上级网格不存在");
				}
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, multistageGridT.getBuildingId(), multistageGridT.getFloorId(), input.getName());
				if (flag1) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				multistageGrid.setSuperiorName(multistageGridT.getSuperiorName() + "->" + multistageGridT.getName());
				multistageGrid.setBuildingId(multistageGridT.getBuildingId());
				multistageGrid.setBuildingName(multistageGridT.getSuperiorName());
				multistageGrid.setFloorId(multistageGridT.getFloorId());
				multistageGrid.setFloor(multistageGridT.getFloor());
			}
			multistageGridService.save(multistageGrid);
			recordId = multistageGrid.getId();
			break;
		}
		// 建立负责人表
		List<WorkGroupToPrincipalInput> userIds = input.getUserIds();
		if (userIds != null) {
			if (userIds.size() > 0) {
				for (WorkGroupToPrincipalInput workGroupToPrincipalInput : userIds) {
					GridToPrincipal gridToPrincipal = new GridToPrincipal();
					BeanUtils.copyProperties(input, gridToPrincipal);
					gridToPrincipal.setGridId(recordId);
					gridToPrincipal.setUserId(workGroupToPrincipalInput.getId());
					gridToPrincipal.setUserName(userService.getById(workGroupToPrincipalInput.getId()).getName());
					gridToPrincipal.setAgentId(district.getAgentId());
					gridToPrincipal.setPropertyId(district.getPropertyId());
					gridToPrincipal.setDistrictId(district.getId());
					gridToPrincipal.setAgentName(agentName);
					gridToPrincipal.setPropertyName(propertyName);
					gridToPrincipal.setDistrictName(district.getDistrictName());
					gridToPrincipalService.save(gridToPrincipal);
				}
			}
		}
		return ResultResponseBeanUtil.success("添加成功");
	}

	@ApiOperation(value = "编辑网格")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public BaseOutput<String> update(HttpServletRequest request, @RequestBody GridUpdateInput input) {
		Long recordId = input.getId();
		Long districtId = input.getDistrictId();
		Integer gridLevel = input.getGridLevel();
		if (recordId == null || recordId == 0) {
			return ResultResponseBeanUtil.fail("选择的记录不存在");
		}
		if (gridLevel == null || gridLevel == 0) {
			return ResultResponseBeanUtil.fail("网格级别是必传参数");
		}
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		User user = UserUtils.getUser(request);
		String agentName = redisService5.get("name:Agent:" + district.getAgentId());
		String propertyName = redisService5.get("name:Properyt:" + district.getPropertyId());
		boolean flag1 = false;
		switch (gridLevel) {
		case 1:
			Building building = buildingService.getById(recordId);
			if (building == null) {
				return ResultResponseBeanUtil.fail("记录不存在,请确认");
			}
			if (!building.getName().equals(input.getName())) {
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, null, null, input.getName());
				if (flag1) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				// 更新名称
				NameModifyNotice nameModifyNotice = new NameModifyNotice();
				nameModifyNotice.setId(building.getId());
				nameModifyNotice.setLevel(1);
				nameModifyNotice.setNewName(input.getName());
				nameModifyNotice.setOldName(building.getName());
				nameModifyNotice.setType(0);
				redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
			}
			BeanUtils.copyProperties(input, building);
			building.setModifyName(user.getName());
			building.setModifyId(user.getId());
			building.setModifyTime(new Date());
			buildingService.updateById(building);
			break;
		case 2:
			Floor floor = floorService.getById(recordId);
			if (floor == null) {
				return ResultResponseBeanUtil.fail("记录不存在,请确认");
			}
			if (!floor.getName().equals(input.getName())) {
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, floor.getBuildingId(), null, input.getName());
				if (flag1) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				// 更新名称
				NameModifyNotice nameModifyNotice = new NameModifyNotice();
				nameModifyNotice.setId(floor.getId());
				nameModifyNotice.setLevel(2);
				nameModifyNotice.setNewName(input.getName());
				nameModifyNotice.setOldName(floor.getName());
				nameModifyNotice.setType(0);
				redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
			}
			BeanUtils.copyProperties(input, floor);
			floor.setModifyName(user.getName());
			floor.setModifyId(user.getId());
			floor.setModifyTime(new Date());
			floorService.updateById(floor);
			break;
		default:
			MultistageGrid multistageGrid = multistageGridService.getById(recordId);
			if (multistageGrid == null) {
				return ResultResponseBeanUtil.fail("记录不存在,请确认");
			}
			if (!multistageGrid.getName().equals(input.getName())) {
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, multistageGrid.getBuildingId(), multistageGrid.getFloorId(), input.getName());
				if (flag1) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				// 更新名称
				NameModifyNotice nameModifyNotice = new NameModifyNotice();
				nameModifyNotice.setId(multistageGrid.getId());
				nameModifyNotice.setLevel(multistageGrid.getGridLevel());
				nameModifyNotice.setNewName(input.getName());
				nameModifyNotice.setOldName(multistageGrid.getName());
				nameModifyNotice.setType(0);
				redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
			}
			BeanUtils.copyProperties(input, multistageGrid);
			multistageGrid.setModifyName(user.getName());
			multistageGrid.setModifyId(user.getId());
			multistageGrid.setModifyTime(new Date());
			multistageGridService.updateById(multistageGrid);
			break;
		}
//		删除旧的 建立新的
		UpdateWrapper<GridToPrincipal> updateWrapperDet = Wrappers.update();
		updateWrapperDet.eq("grid_id", recordId);
		updateWrapperDet.eq("grid_level", gridLevel);
		updateWrapperDet.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		gridToPrincipalService.update(updateWrapperDet);
		// 建立负责人表
		List<WorkGroupToPrincipalInput> userIds = input.getUserIds();
		if (userIds != null) {
			if (userIds.size() > 0) {
				for (WorkGroupToPrincipalInput workGroupToPrincipalInput : userIds) {
					GridToPrincipal gridToPrincipal = new GridToPrincipal();
					BeanUtils.copyProperties(input, gridToPrincipal);
					gridToPrincipal.setGridId(recordId);
					gridToPrincipal.setUserId(workGroupToPrincipalInput.getId());
					gridToPrincipal.setUserName(workGroupToPrincipalInput.getName());
					gridToPrincipal.setAgentId(district.getAgentId());
					gridToPrincipal.setPropertyId(district.getPropertyId());
					gridToPrincipal.setDistrictId(district.getId());
					gridToPrincipal.setAgentName(agentName);
					gridToPrincipal.setPropertyName(propertyName);
					gridToPrincipal.setDistrictName(district.getDistrictName());
					gridToPrincipalService.save(gridToPrincipal);
				}
			}
		}
		return ResultResponseBeanUtil.success("更新成功");
	}

	@ApiOperation(value = "上传文件", notes = "上传硬件文件")
	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public BaseOutput<FileUploadOutput> uploadFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws Exception {
		// 将读取的文件内容放到redis里 提交的时候再读出来
		FileUploadOutput fileUploadOutput = new FileUploadOutput();
		String districtId = request.getParameter("districtId");
		if (districtId == null) {
			return ResultResponseBeanUtil.fail("请上传站点ID");
		}
		String originalFilename = file.getOriginalFilename();
		if (originalFilename.indexOf("xlsx") > 0 || originalFilename.indexOf("xls") > 0 || originalFilename.indexOf("XLSX") > 0 || originalFilename.indexOf("XLS") > 0) {
			Long redisKey = System.currentTimeMillis();
			InputStream inputStream = file.getInputStream();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);// 从第三行读取
			List<GridReadFileModel> entities = ExcelImportUtil.importExcel(inputStream, GridReadFileModel.class, params);
			if (entities.size() > 0) {
				for (GridReadFileModel gridBatchInsertInput : entities) {
					redisService4.lPush("GridFile:" + districtId + "_" + redisKey, com.alibaba.fastjson.JSON.toJSONString(gridBatchInsertInput));
				}
				fileUploadOutput.setFileId(redisKey);
				fileUploadOutput.setInfo("上传成功");
			} else {
				return ResultResponseBeanUtil.fail("上传的文件为空");
			}
		} else {
			return ResultResponseBeanUtil.fail("请上传excel文件，文件已.xlsx或.xls结尾");
		}
		return ResultResponseBeanUtil.success(fileUploadOutput);
	}

	@ApiOperation(value = "批量新增网格")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/batchAdd", method = RequestMethod.POST)
	public BaseOutput<String> batchAdd(HttpServletRequest request, @RequestBody GridBatchAddInput input) {
		Long fileId = input.getFileId();
		if (fileId == null) {
			return ResultResponseBeanUtil.fail("文件不存在或未上传成功");
		}
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		if (!redisService4.exists("GridFile:" + districtId + "_" + fileId)) {
			return ResultResponseBeanUtil.fail("文件不存在或未上传成功");
		}
		District district = districtService.getById(districtId);
		List<String> gridString = redisService4.lRangeAll("GridFile:" + districtId + "_" + fileId);
		List<String> memoList = new ArrayList<String>();
		User user = UserUtils.getUser(request);
		String agentName = redisService5.get("name:Agent:" + district.getAgentId());
		String propertyName = redisService5.get("name:Properyt:" + district.getPropertyId());
//		3条 错误记录，网格名称1,网格名称2,网格名称3
		for (String gridJson : gridString) {
			GridReadFileModel gridReadFileModel = JSON.parseObject(gridJson, GridReadFileModel.class);
//			网格名称（必填）	网格级别（必选）	上级网格（非必填）	备注
//			A座					1级							没事
//			F1					2级				A座			没事
			if (gridReadFileModel.getName() == null) {
				continue;
			}
			// 级别
			String gridLevelString = gridReadFileModel.getGridLevel();
			if (gridLevelString == null) {
				memoList.add(gridReadFileModel.getName() + "->没有选择网格级别");
				continue;
			}
			if (!gridLevelString.endsWith("级")) {
				memoList.add(gridReadFileModel.getName() + "->网格级别填写有误");
				continue;
			}
			Integer gridLevel = Integer.parseInt(gridLevelString.split("级")[0]);
			if (gridLevel > 4) {// 不要大于4级
				memoList.add(gridReadFileModel.getName() + "->网格级别填写有误");
				continue;
			}
			String superiorName = gridReadFileModel.getSuperiorName();
			if (gridLevel == 1) {
				if (superiorName != null) {
					memoList.add(gridReadFileModel.getName() + "->一级网格不能有上级网格");
					continue;
				}
			}
			if (gridLevel == 2) {
				if (superiorName == null) {
					memoList.add(gridReadFileModel.getName() + "->请填写上级网格");
					continue;
				}
				if (superiorName.contains("->")) {
					memoList.add(gridReadFileModel.getName() + "->上级网格填写错误");
					continue;
				}
			}
			if (gridLevel == 3) {
				if (superiorName == null) {
					memoList.add(gridReadFileModel.getName() + "->请填写上级网格");
					continue;
				}
				if (!superiorName.contains("->")) {
					memoList.add(gridReadFileModel.getName() + "->上级网格填写错误,请参考说明");
					continue;
				}
			}

			boolean flag1 = false;

			switch (gridLevel) {
			case 1:
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, null, null, gridReadFileModel.getName());
				if (flag1) {
					continue;
				}
				Building building = new Building();
				building.setAgentId(district.getAgentId());
				building.setPropertyId(district.getPropertyId());
				building.setDistrictId(district.getId());
				building.setAgentName(agentName);
				building.setPropertyName(propertyName);
				building.setDistrictName(district.getDistrictName());
				building.setCreateName(user.getName());
				building.setCreateId(user.getId());
				building.setCreateTime(new Date());
				building.setNote(gridReadFileModel.getNote());
				building.setName(gridReadFileModel.getName());
				building.setGridLevel(gridLevel);
				buildingService.save(building);
				break;
			case 2:
				Floor floor = new Floor();
				floor.setAgentId(district.getAgentId());
				floor.setPropertyId(district.getPropertyId());
				floor.setDistrictId(district.getId());
				floor.setAgentName(agentName);
				floor.setPropertyName(propertyName);
				floor.setDistrictName(district.getDistrictName());
				floor.setCreateName(user.getName());
				floor.setCreateId(user.getId());
				floor.setCreateTime(new Date());
				floor.setNote(gridReadFileModel.getNote());
				floor.setName(gridReadFileModel.getName());
				floor.setGridLevel(gridLevel);
				QueryWrapper<Building> buildWrapper = WrapperUtils.getWrapper(false);
				buildWrapper.eq("name", gridReadFileModel.getSuperiorName()).eq("district_id", districtId).last(" limit 1");
				Building building2 = buildingService.getOne(buildWrapper);
				if (building2 == null) {
					memoList.add(gridReadFileModel.getName() + "->上级网格不存在");
					continue;
				}
				flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, building2.getId(), null, gridReadFileModel.getName());
				if (flag1) {
					continue;
				}
				floor.setBuildingId(building2.getId());
				floor.setSuperiorName(building2.getName());
				floorService.save(floor);
				break;
			case 3:
				MultistageGrid multistageGrid = new MultistageGrid();
				multistageGrid.setAgentId(district.getAgentId());
				multistageGrid.setPropertyId(district.getPropertyId());
				multistageGrid.setDistrictId(district.getId());
				multistageGrid.setAgentName(agentName);
				multistageGrid.setPropertyName(propertyName);
				multistageGrid.setDistrictName(district.getDistrictName());
				multistageGrid.setCreateName(user.getName());
				multistageGrid.setCreateId(user.getId());
				multistageGrid.setCreateTime(new Date());
				multistageGrid.setNote(gridReadFileModel.getNote());
				multistageGrid.setName(gridReadFileModel.getName());
				multistageGrid.setGridLevel(gridLevel);
				if (gridLevel == 3) {
//					A座->F2
					String[] b_f = gridReadFileModel.getSuperiorName().split("->");
					QueryWrapper<Building> buildWrapper3 = WrapperUtils.getWrapper(false);
					buildWrapper3.eq("name", b_f[0])
					.eq("district_id", districtId).last(" limit 1");
					Building building3 = buildingService.getOne(buildWrapper3);
					if (building3 == null) {
						memoList.add(gridReadFileModel.getName() + "->上级网格不存在");
						continue;
					}
					QueryWrapper<Floor> floorWrapper = WrapperUtils.getWrapper(false);
					floorWrapper.eq("name", b_f[1])
					.eq("district_id", districtId)
					.eq("building_id", building3.getId())
					.last(" limit 1");
					Floor floorT = floorService.getOne(floorWrapper);
					if (floorT == null) {
						memoList.add(gridReadFileModel.getName() + "->上级网格不存在");
						continue;
					}
					flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, floorT.getBuildingId(), floorT.getId(), gridReadFileModel.getName());
					if (flag1) {
						continue;
					}
					multistageGrid.setSuperiorName(floorT.getSuperiorName() + "->" + floorT.getName());
					multistageGrid.setBuildingId(floorT.getBuildingId());
					multistageGrid.setBuildingName(floorT.getSuperiorName());
					multistageGrid.setFloorId(floorT.getId());
					multistageGrid.setFloor(floorT.getName());
					multistageGrid.setSuperiorId(floorT.getId());
				} 
//				else {
//					MultistageGrid multistageGridT = multistageGridService.getOne(new QueryWrapper<MultistageGrid>().eq("name", gridReadFileModel.getSuperiorName()).last(" limit 1"));
//					if (multistageGridT == null) {
//						memoList.add(gridReadFileModel.getName() + "->上级网格不存在");
//						continue;
//					}
//					flag1 = publicService.isExistGridByLevelAndName(gridLevel, districtId, multistageGridT.getBuildingId(), multistageGridT.getFloorId(), gridReadFileModel.getName());
//					if (flag1) {
//						continue;
//					}
//					multistageGrid.setSuperiorName(multistageGridT.getSuperiorName() + "->" + multistageGridT.getName());
//					multistageGrid.setBuildingId(multistageGridT.getBuildingId());
//					multistageGrid.setBuildingName(multistageGridT.getSuperiorName());
//					multistageGrid.setFloorId(multistageGridT.getFloorId());
//					multistageGrid.setFloor(multistageGridT.getFloor());
//				}
				multistageGridService.save(multistageGrid);
				break;
			}
		}
		if (memoList.size() > 0) {
			String memo = memoList.stream().map(me -> me).collect(Collectors.joining(";"));
			return ResultResponseBeanUtil.fail(memo);
		} else {
			return ResultResponseBeanUtil.success("添加成功");
		}

	}
}