package xiaoqu.home.open.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
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.ResponseBody;

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

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
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.scenes.BuildingUnionInfoOutput;
import xiaoqu.home.open.controller.export.scenes.DistrictUnionInfoOutput;
import xiaoqu.home.open.controller.export.scenes.FloorUnionOutout;
import xiaoqu.home.open.controller.export.scenes.MultistageGridOutput;
import xiaoqu.home.open.controller.export.scenes.ScenesUnionOutput;
import xiaoqu.home.open.controller.export.scenes.SuperiorScenesUnionOutput;
import xiaoqu.home.open.controller.input.DistrictIdInput;
import xiaoqu.home.open.controller.input.grid.GridSelectInput;
import xiaoqu.home.open.controller.input.scenes.ScenesBatchInsertInput;
import xiaoqu.home.open.controller.input.scenes.ScenesDeleteInput;
import xiaoqu.home.open.controller.input.scenes.ScenesInsertInput;
import xiaoqu.home.open.controller.input.scenes.ScenesPageInput;
import xiaoqu.home.open.controller.input.scenes.ScenesUpdateInput;
import xiaoqu.home.open.controller.output.scenes.ScenesOutput;
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.MultistageGrid;
import xiaoqu.home.open.model.db1.Positions;
import xiaoqu.home.open.model.db1.Toilet;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.UserToServiceArea;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
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.MultistageGridService;
import xiaoqu.home.open.service.db1.PositionsService;
import xiaoqu.home.open.service.db1.ToiletService;
import xiaoqu.home.open.service.db2.UserToServiceAreaService;
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;

@Controller
@RequestMapping(value = "/scenes")
@Api(value = "场景服务", description = "场景服务")
@Slf4j(topic = "Controller")
public class ScenesController {
	@Autowired
	private DistrictService districtService;
	@Autowired
	private FloorService floorService;
	@Autowired
	private BuildingService buildingService;
	@Autowired
	private MultistageGridService multistageGridService;
	@Autowired
	private ToiletService toiletService;

	@Autowired
	private PositionsService positionsService;

	@ApiOperation(value = "场景查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<ScenesOutput>> pageList(HttpServletRequest request, @RequestBody ScenesPageInput input) {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点查询");
		}
		PageOutput<ScenesOutput> output = new PageOutput<ScenesOutput>();
		List<ScenesOutput> outList = new ArrayList<ScenesOutput>();
		if (input.getScenesLevel() == null) {// 级别不为空
			return ResultResponseBeanUtil.fail("请选择场景级别");
		}
		switch (input.getScenesLevel()) {
		case 1:
			QueryWrapper<Toilet> wrapperToilet = WrapperUtils.getWrapper(false);
			wrapperToilet.eq("district_id", input.getDistrictId());
			wrapperToilet.ne("agent_id", 0);
			if (input.getName() != null) {
				wrapperToilet.like("name", input.getName());
			}
//		    @ApiModelProperty(value = "场景环境品质等级 0:A级;1:B级....")
//			private Integer qualityLevel;
			if (input.getQualityLevel() != null) {
				wrapperToilet.eq("quality_level", input.getQualityLevel());
			}
//		    @ApiModelProperty(value = "区域名称")
//			private String superiorGridName;
			if (input.getSuperiorGridName() != null) {
				wrapperToilet.like("superior_grid_name", input.getSuperiorGridName());
			}
//		    @ApiModelProperty(value = "启用状态(0:启用;1:停用)")
//			private Integer enableStatus;
			if (input.getEnableStatus() != null) {
				wrapperToilet.eq("enable_status", input.getEnableStatus());
			}
//		    @ApiModelProperty(value = "网格ID  树节点的时候查询用")
//		    private Long gridId;
//			@ApiModelProperty(value = "网格级别1,2,3.... 树节点的时候查询用")
//		    private Integer gridLevel;
			if (input.getGridLevel() != null) {
				switch (input.getGridLevel()) {
				case 1:
					wrapperToilet.eq("building_id", input.getGridId());
					break;
				case 2:
					wrapperToilet.eq("floor_id", input.getGridId());
					break;
				default:
					wrapperToilet.eq("multistage_grid_id", input.getGridId());
					break;
				}
			}
			if (input.getScenesType()!=null) {
				wrapperToilet.eq("scenes_type", input.getScenesType());
			}
			wrapperToilet.orderByDesc("create_time");
			Page<Toilet> pageListToilet = new Page<Toilet>(input.getPage(), input.getRows());
			List<Toilet> listToilet = toiletService.page(pageListToilet, wrapperToilet).getRecords();

			for (Toilet toilet : listToilet) {
				ScenesOutput scenesOutput = new ScenesOutput();
				BeanUtils.copyProperties(toilet, scenesOutput);
				outList.add(scenesOutput);
			}
			output.setPage(pageListToilet.getCurrent());
			output.setRecords(pageListToilet.getTotal());
			output.setTotal(pageListToilet.getPages());
			output.setRows(outList);
			break;
		case 2:
			QueryWrapper<Positions> wrapperPositions = WrapperUtils.getWrapper(false);
			wrapperPositions.eq("district_id", input.getDistrictId());
			if (input.getName() != null) {
				wrapperPositions.like("name", input.getName());
			}
//			 @ApiModelProperty(value = "场景环境品质等级 0:A级;1:B级....")
//				private Integer qualityLevel;
			if (input.getQualityLevel() != null) {
				wrapperPositions.eq("quality_level", input.getQualityLevel());
			}
//			    @ApiModelProperty(value = "区域名称")
//				private String superiorGridName;
			if (input.getSuperiorGridName() != null) {
				wrapperPositions.like("superior_grid_name", input.getSuperiorGridName());
			}
//			    @ApiModelProperty(value = "启用状态(0:启用;1:停用)")
//				private Integer enableStatus;
			if (input.getEnableStatus() != null) {
				wrapperPositions.eq("enable_status", input.getEnableStatus());
			}
//			    @ApiModelProperty(value = "网格ID  树节点的时候查询用")
//			    private Long gridId;
//				@ApiModelProperty(value = "网格级别1,2,3.... 树节点的时候查询用")
//			    private Integer gridLevel;
			if (input.getGridLevel() != null) {
				switch (input.getGridLevel()) {
				case 1:
					wrapperPositions.eq("building_id", input.getGridId());
					break;
				case 2:
					wrapperPositions.eq("floor_id", input.getGridId());
					break;
				default:
					wrapperPositions.eq("multistage_grid_id", input.getGridId());
					break;
				}
			}
			if (input.getScenesType()!=null) {
				wrapperPositions.eq("scenes_type", input.getScenesType());
			}
			wrapperPositions.orderByDesc("create_time");
			Page<Positions> pageListPositions = new Page<Positions>(input.getPage(), input.getRows());
			List<Positions> listPositions = positionsService.page(pageListPositions, wrapperPositions).getRecords();
			for (Positions positions : listPositions) {
				ScenesOutput scenesOutput = new ScenesOutput();
				BeanUtils.copyProperties(positions, scenesOutput);
				outList.add(scenesOutput);
			}
			output.setPage(pageListPositions.getCurrent());
			output.setRecords(pageListPositions.getTotal());
			output.setTotal(pageListPositions.getPages());
			output.setRows(outList);
			break;
		}
		return ResultResponseBeanUtil.success(output);

	}

	@ApiOperation(value = "删除场景")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public BaseOutput<String> delete(HttpServletRequest request, @RequestBody ScenesDeleteInput input) {
		User user = UserUtils.getUser(request);
		Long id = input.getId();
		Integer senesLevel = input.getScenesLevel();
		if (id == null) {
			return ResultResponseBeanUtil.fail("请传递记录ID");
		}
		if (senesLevel == null) {
			return ResultResponseBeanUtil.fail("请传递场景级别");
		}
		DeleteEntityNotice deleteEntityNotice = new DeleteEntityNotice();
		switch (senesLevel) {
		case 1:
			Toilet toilet = toiletService.getById(id);
			if (toilet == null) {
				return ResultResponseBeanUtil.fail("场景不存在");
			}
			if (toilet.getSoftDelete() == 1) {
				return ResultResponseBeanUtil.fail("场景是已删除状态");
			}
			QueryWrapper<Positions> wrapperPositions = WrapperUtils.getWrapper(false);
			wrapperPositions.eq("toilet_id", toilet.getId());
			int count99 = positionsService.count(wrapperPositions);
			if (count99 > 0) {
				return ResultResponseBeanUtil.fail("场景存在下级，不能删除");
			}
			toilet.setModifyName(user.getName());
			toilet.setModifyId(user.getId());
			toilet.setModifyTime(new Date());
			toilet.setSoftDelete(1);
			toiletService.updateById(toilet);
			deleteEntityNotice.setId(toilet.getId());
			deleteEntityNotice.setLevel(2);
			deleteEntityNotice.setType(1);
			redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
			break;
		case 2:
			Positions positions = positionsService.getById(id);
			if (positions == null) {
				return ResultResponseBeanUtil.fail("场景不存在");
			}
			if (positions.getSoftDelete() == 1) {
				return ResultResponseBeanUtil.fail("场景是已删除状态");
			}
			positions.setModifyName(user.getName());
			positions.setModifyId(user.getId());
			positions.setModifyTime(new Date());
			positions.setSoftDelete(1);
			positionsService.updateById(positions);
			deleteEntityNotice.setId(positions.getId());
			deleteEntityNotice.setLevel(positions.getScenesLevel());
			deleteEntityNotice.setType(1);
			redisService4.lPush("DeleteEntityNotice", JSON.toJSONString(deleteEntityNotice));
			break;
		}
		return ResultResponseBeanUtil.success("删除成功");

	}

	@Autowired
	private UserToServiceAreaService userToServiceAreaService;

	@ApiOperation(value = "新增场景")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public BaseOutput<String> add(HttpServletRequest request, @RequestBody ScenesBatchInsertInput 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("选择的站点不存在");
		}
		User user = UserUtils.getUser(request);
		List<GridSelectInput> gridSelect = input.getGridSelect();
		if (gridSelect == null || gridSelect.size() == 0) {
			return ResultResponseBeanUtil.fail("请选择区域网格");
		}
		List<ScenesInsertInput> scenes = input.getScenes();
		if (scenes == null || scenes.size() == 0) {
			return ResultResponseBeanUtil.fail("请填写场景信息");
		}
		Set<String> nameSet = new HashSet<String>();
		for (ScenesInsertInput scenesInsertInput : scenes) {
			nameSet.add(scenesInsertInput.getName());
		}
		if (nameSet.size() != scenes.size()) {
			return ResultResponseBeanUtil.fail("名称重复,请重新修改提交");
		}

		for (ScenesInsertInput scenesInsertInput : scenes) {
			switch (scenesInsertInput.getScenesLevel()) {
			case 1:
				for (GridSelectInput gridSelectInput : gridSelect) {
					QueryWrapper<Toilet> wrapperB = WrapperUtils.getWrapper(false);
					int countB = 0;
					switch (gridSelectInput.getGridLevel()) {
					case 2:
						wrapperB.eq("name", scenesInsertInput.getName());
						wrapperB.eq("district_id", districtId);
						wrapperB.eq("floor_id", gridSelectInput.getGridId());
						countB = toiletService.count(wrapperB);
						if (countB > 0) {
							return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
						}
						break;
					case 3:
						wrapperB.eq("name", scenesInsertInput.getName());
						wrapperB.eq("district_id", districtId);
						wrapperB.eq("multistage_grid_id", gridSelectInput.getGridId());
						countB = toiletService.count(wrapperB);
						if (countB > 0) {
							return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
						}
						break;

					}
				}
				break;

			default:
				for (GridSelectInput gridSelectInput : gridSelect) {
					QueryWrapper<Positions> wrapperP = WrapperUtils.getWrapper(false);
					int countP = 0;
					switch (gridSelectInput.getGridLevel()) {
					case 2:
						wrapperP.eq("name", scenesInsertInput.getName());
						wrapperP.eq("district_id", districtId);
						wrapperP.eq("floor_id", gridSelectInput.getGridId());
						countP = positionsService.count(wrapperP);
						if (countP > 0) {
							return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
						}
					case 3:
						wrapperP.eq("name", scenesInsertInput.getName());
						wrapperP.eq("district_id", districtId);
						wrapperP.eq("multistage_grid_id", gridSelectInput.getGridId());
						countP = positionsService.count(wrapperP);
						if (countP > 0) {
							return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
						}
					}
				}

				break;
			}
		}

		for (ScenesInsertInput scenesInsertInput : scenes) {
			Integer scenesLevel = scenesInsertInput.getScenesLevel();
			switch (scenesLevel) {
			case 1:
				for (GridSelectInput gridSelectInput : gridSelect) {
					Integer gridLevel = gridSelectInput.getGridLevel();
					Floor floor = new Floor();
					MultistageGrid multistageGrid = new MultistageGrid();
					switch (gridLevel) {
					case 2:
						floor = floorService.getById(gridSelectInput.getGridId());
						break;
					default:
						multistageGrid = multistageGridService.getById(gridSelectInput.getGridId());
						break;
					}
					Toilet toilet = new Toilet();
					BeanUtils.copyProperties(scenesInsertInput, toilet);
					toilet.setNo(scenesInsertInput.getName());// 兼容老的
					toilet.setInstallType(0);
					toilet.setAirdetectorFlag(0);
					toilet.setOrderby(0);
					toilet.setGateAzimuth(2);// 厕所入口位置 0:上;1:左上;2:左下;3:下
					toilet.setStatus(0);
					toilet.setLength(100L);
					toilet.setWidth(100L);
					toilet.seth5ModelId(2L);// 通用的
					toilet.setGridLevel(gridLevel);
					if (gridLevel == 2) {
						toilet.setAgentId(district.getAgentId());
						toilet.setPropertyId(district.getPropertyId());
						toilet.setDistrictId(districtId);
						toilet.setBuildingId(floor.getBuildingId());
						toilet.setFloorId(floor.getId());
						toilet.setAgentName(floor.getAgentName());
						toilet.setPropertyName(floor.getPropertyName());
						toilet.setDistrictName(floor.getDistrictName());
						toilet.setBuildingName(floor.getSuperiorName());
						toilet.setFloor(floor.getName());
						toilet.setCreateName(user.getName());
						toilet.setCreateId(user.getId());
						toilet.setCreateTime(new Date());
						toilet.setSuperiorGridName(floor.getSuperiorName() + "->" + floor.getName());

					} else {
						toilet.setAgentId(district.getAgentId());
						toilet.setPropertyId(district.getPropertyId());
						toilet.setDistrictId(districtId);
						toilet.setBuildingId(multistageGrid.getBuildingId());
						toilet.setFloorId(multistageGrid.getId());
						toilet.setAgentName(multistageGrid.getAgentName());
						toilet.setPropertyName(multistageGrid.getPropertyName());
						toilet.setDistrictName(multistageGrid.getDistrictName());
						toilet.setBuildingName(multistageGrid.getBuildingName());
						toilet.setFloor(multistageGrid.getFloor());
						toilet.setCreateName(user.getName());
						toilet.setCreateId(user.getId());
						toilet.setCreateTime(new Date());
						toilet.setMultistageGridId(multistageGrid.getId());
						toilet.setMultistageGridName(multistageGrid.getName());
						toilet.setSuperiorGridName(multistageGrid.getSuperiorName() + "->" + multistageGrid.getName());
					}
					toiletService.save(toilet);
					// 判读网格级别
					if (gridLevel == 2) {
						QueryWrapper<UserToServiceArea> queryWrapper = WrapperUtils.getWrapper(false);
						queryWrapper.eq("service_area_id", gridSelectInput.getGridId());
						queryWrapper.eq("service_type", 0);
						queryWrapper.eq("grid_scenes_level", 2);
						List<UserToServiceArea> temList = userToServiceAreaService.list(queryWrapper);
						if (StringUtil.isNotEmpty(temList)) {
							for (UserToServiceArea temUserToServiceArea : temList) {
								Long userId = temUserToServiceArea.getUserId();
								UserToServiceArea userToServiceArea = new UserToServiceArea();
								userToServiceArea.setUserId(userId);
								userToServiceArea.setCreateId(user.getId());
								userToServiceArea.setCreateTime(new Date());
//							    @ApiModelProperty(value = "服务区域ID")
								userToServiceArea.setServiceAreaId(toilet.getId());
//							    @ApiModelProperty(value = "服务区域")
								userToServiceArea.setServiceAreaName(toilet.getName());
//							    @ApiModelProperty(value = "服务分类0:区域;1:场景")
								userToServiceArea.setServiceType(1);
//							    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
								userToServiceArea.setGridScenesLevel(1);
								userToServiceArea.setDistrictId(districtId);
								userToServiceAreaService.save(userToServiceArea);
							}
						}
					} else if (gridLevel == 3) {
						QueryWrapper<UserToServiceArea> queryWrapper = WrapperUtils.getWrapper(false);
						queryWrapper.eq("service_area_id", gridSelectInput.getGridId());
						queryWrapper.eq("service_type", 0);
						queryWrapper.eq("grid_scenes_level", 3);
						List<UserToServiceArea> temList = userToServiceAreaService.list(queryWrapper);
						if (StringUtil.isNotEmpty(temList)) {
							for (UserToServiceArea temUserToServiceArea : temList) {
								Long userId = temUserToServiceArea.getUserId();
								UserToServiceArea userToServiceArea = new UserToServiceArea();
								userToServiceArea.setUserId(userId);
								userToServiceArea.setCreateId(user.getId());
								userToServiceArea.setCreateTime(new Date());
//							    @ApiModelProperty(value = "服务区域ID")
								userToServiceArea.setServiceAreaId(toilet.getId());
//							    @ApiModelProperty(value = "服务区域")
								userToServiceArea.setServiceAreaName(toilet.getName());
//							    @ApiModelProperty(value = "服务分类0:区域;1:场景")
								userToServiceArea.setServiceType(1);
//							    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
								userToServiceArea.setGridScenesLevel(1);
								userToServiceArea.setDistrictId(districtId);
								userToServiceAreaService.save(userToServiceArea);
							}
						}
					}

				}

				break;
			case 2:
				Toilet toilet2 = toiletService.getById(scenesInsertInput.getSuperiorScenesId());
				if (toilet2 == null) {
					return ResultResponseBeanUtil.fail("一级场景没传或不存在");
				}
				Positions positions = new Positions();
				BeanUtils.copyProperties(toilet2, positions, "id", "modifyTime", "modifyId", "createTime", "modifyName", "createName");
				BeanUtils.copyProperties(scenesInsertInput, positions);
				positions.setSuperiorScenesName(toilet2.getName());
				positions.setToiletId(toilet2.getId());
				positions.setMemo(scenesInsertInput.getName());
				positions.setCreateName(user.getName());
				positions.setCreateId(user.getId());
				positions.setCreateTime(new Date());
				positions.setGender(0);
				positions.setWidth(100);
				positions.setLength(100);
				positions.setWcType("0");// 0:坐便A;1:蹲便B;2:残疾人坐便C;3:其它N
				positions.setCubiclePosition(0);// 0:上;1:下
				positions.setBindStatus(0);// 未绑定设备
				positions.setServiceStatus(2);// 有人无人显示未知
				positions.setCleanStatus(0);// 已清洁
				positions.setScenesLevel(2);
				positions.setToiletOrder("1");
				positionsService.save(positions);

				// 判读网格级别
				int tempGridLevel = positions.getGridLevel();
				if (tempGridLevel == 2) {
					QueryWrapper<UserToServiceArea> queryWrapper = WrapperUtils.getWrapper(false);
					queryWrapper.eq("service_area_id", positions.getFloorId());
					queryWrapper.eq("service_type", 0);
					queryWrapper.eq("grid_scenes_level", 2);
					List<UserToServiceArea> temList = userToServiceAreaService.list(queryWrapper);
					if (StringUtil.isNotEmpty(temList)) {
						for (UserToServiceArea temUserToServiceArea : temList) {
							Long userId = temUserToServiceArea.getUserId();
							UserToServiceArea userToServiceArea = new UserToServiceArea();
							userToServiceArea.setUserId(userId);
							userToServiceArea.setCreateId(user.getId());
							userToServiceArea.setCreateTime(new Date());
//						    @ApiModelProperty(value = "服务区域ID")
							userToServiceArea.setServiceAreaId(positions.getId());
//						    @ApiModelProperty(value = "服务区域")
							userToServiceArea.setServiceAreaName(positions.getName());
//						    @ApiModelProperty(value = "服务分类0:区域;1:场景")
							userToServiceArea.setServiceType(1);
//						    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
							userToServiceArea.setGridScenesLevel(2);
							userToServiceArea.setDistrictId(districtId);
							userToServiceAreaService.save(userToServiceArea);
						}
					}
				} else if (tempGridLevel == 3) {
					QueryWrapper<UserToServiceArea> queryWrapper = WrapperUtils.getWrapper(false);
					queryWrapper.eq("service_area_id", positions.getMultistageGridId());
					queryWrapper.eq("service_type", 0);
					queryWrapper.eq("grid_scenes_level", 3);
					List<UserToServiceArea> temList = userToServiceAreaService.list(queryWrapper);
					if (StringUtil.isNotEmpty(temList)) {
						for (UserToServiceArea temUserToServiceArea : temList) {
							Long userId = temUserToServiceArea.getUserId();
							UserToServiceArea userToServiceArea = new UserToServiceArea();
							userToServiceArea.setUserId(userId);
							userToServiceArea.setCreateId(user.getId());
							userToServiceArea.setCreateTime(new Date());
//						    @ApiModelProperty(value = "服务区域ID")
							userToServiceArea.setServiceAreaId(positions.getId());
//						    @ApiModelProperty(value = "服务区域")
							userToServiceArea.setServiceAreaName(positions.getName());
//						    @ApiModelProperty(value = "服务分类0:区域;1:场景")
							userToServiceArea.setServiceType(1);
//						    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
							userToServiceArea.setGridScenesLevel(2);
							userToServiceArea.setDistrictId(districtId);
							userToServiceAreaService.save(userToServiceArea);
						}
					}
				}
				break;
			}
		}
		return ResultResponseBeanUtil.success("添加成功");
	}

	@Autowired
	RedisService4 redisService4;
	@Autowired
	RedisService5 RedisService5;

	@ApiOperation(value = "编辑场景")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public BaseOutput<String> update(HttpServletRequest request, @RequestBody ScenesUpdateInput input) {
		log.info("场景修改=" + JSON.toJSONString(input));
		Long recordId = input.getId();
		Long districtId = input.getDistrictId();
		Integer scenesLevel = input.getScenesLevel();
		if (recordId == null || recordId == 0) {
			return ResultResponseBeanUtil.fail("选择的记录不存在");
		}
		if (scenesLevel == null || scenesLevel == 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);
		switch (scenesLevel) {
		case 1:
			Toilet toilet = toiletService.getById(recordId);
			if (!toilet.getName().equals(input.getName())) {
				QueryWrapper<Toilet> wrapperB = WrapperUtils.getWrapper(false);
				wrapperB.eq("name", input.getName());
				wrapperB.eq("district_id", districtId);
				wrapperB.eq("floor_id", toilet.getFloorId());
				wrapperB.eq("multistage_grid_id", toilet.getMultistageGridId());
				int countB = toiletService.count(wrapperB);
				if (countB > 0) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				// 更新名称
				NameModifyNotice nameModifyNotice = new NameModifyNotice();
				nameModifyNotice.setId(toilet.getId());
				nameModifyNotice.setLevel(toilet.getScenesLevel());
				nameModifyNotice.setNewName(input.getName());
				nameModifyNotice.setOldName(toilet.getName());
				nameModifyNotice.setType(1);
				redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
			}
			if (input.getScenesType().intValue()!=toilet.getScenesType().intValue()) {
				QueryWrapper<Positions> wrapperB = WrapperUtils.getWrapper(false);
				wrapperB.eq("toilet_id", input.getId());
				List<Positions> positionsList = positionsService.list(wrapperB);
				if (positionsList.size()>0) {
					for (Positions positions : positionsList) {
						positions.setScenesType(input.getScenesType());
						positionsService.updateById(positions);
					}
				}
			}
			BeanUtils.copyProperties(input, toilet);
			toilet.setModifyName(user.getName());
			toilet.setModifyId(user.getId());
			toilet.setModifyTime(new Date());
			toiletService.updateById(toilet);
			break;
		case 2:
			Positions positions = positionsService.getById(recordId);
			if (!positions.getName().equals(input.getName())) {
				QueryWrapper<Positions> wrapperB = WrapperUtils.getWrapper(false);
				wrapperB.eq("name", input.getName());
				wrapperB.eq("district_id", districtId);
				wrapperB.eq("floor_id", positions.getFloorId());
				wrapperB.eq("multistage_grid_id", positions.getMultistageGridId());
				int countB = positionsService.count(wrapperB);
				if (countB > 0) {
					return ResultResponseBeanUtil.fail("记录已存在，请修改后再提交");
				}
				// 更新名称
				NameModifyNotice nameModifyNotice = new NameModifyNotice();
				nameModifyNotice.setId(positions.getId());
				nameModifyNotice.setLevel(positions.getScenesLevel());
				nameModifyNotice.setNewName(input.getName());
				nameModifyNotice.setOldName(positions.getName());
				nameModifyNotice.setType(1);
				redisService4.lPush("NameModifyNotice", JSON.toJSONString(nameModifyNotice));
			}
			BeanUtils.copyProperties(input, positions);
			positions.setModifyName(user.getName());
			positions.setModifyId(user.getId());
			positions.setModifyTime(new Date());
			positionsService.updateById(positions);
			break;
		}
		return ResultResponseBeanUtil.success("更新成功");
	}

	@ApiOperation(value = "导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody DistrictIdInput input) throws IOException {
//		0:卫生间;1:电梯;99:其他
		String scenes = (String) RedisService5.hmGet("Dictionary", "ScenesType");
		String[] scenesS = scenes.split(";");
		Map<String, String> paraMap = new HashMap<String, String>();
		for (String string : scenesS) {
			String[] tempS = string.split(":");
			paraMap.put(tempS[0], tempS[01]);
		}

		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return;
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return;
		}
		Integer superiorSceneSize = 0;
		Integer scenesNameSize = 0;
		Integer threeGridSize = 0;
		Integer twoGridSize = 0;
		Integer oneGridSize = 0;
		List<DistrictUnionInfoOutput> list = new ArrayList<DistrictUnionInfoOutput>();
		DistrictUnionInfoOutput districtUnionInfoOutput = new DistrictUnionInfoOutput();
		districtUnionInfoOutput.setId(district.getId());
		districtUnionInfoOutput.setName(district.getDistrictName());
		List<BuildingUnionInfoOutput> dropDownList = new ArrayList<BuildingUnionInfoOutput>();
		QueryWrapper<Building> BuildingWrapper = WrapperUtils.getWrapper(false);
		BuildingWrapper.eq("district_id", districtId);
		BuildingWrapper.orderByAsc("id");
		List<Building> buildingList = buildingService.list(BuildingWrapper);

		if (buildingList != null && buildingList.size() > 0) {
			oneGridSize = buildingList.size();
			// 查楼座
			for (Building building : buildingList) {
				BuildingUnionInfoOutput BuildingUnionInfoEntity = new BuildingUnionInfoOutput();
				BuildingUnionInfoEntity.setId(building.getId());
				BuildingUnionInfoEntity.setName(building.getName());
				QueryWrapper<Floor> floorWrapper = WrapperUtils.getWrapper(false);
				floorWrapper.eq("building_id", building.getId());
				floorWrapper.orderByAsc("id");
				List<Floor> floors = floorService.list(floorWrapper);
				twoGridSize = twoGridSize + floors.size();
				List<FloorUnionOutout> floorsOut = new ArrayList<FloorUnionOutout>();
				for (Floor floor : floors) {// 查楼层
					FloorUnionOutout floorUnionOutout = new FloorUnionOutout();
					floorUnionOutout.setName(floor.getName());
					floorUnionOutout.setId(floor.getId());
					QueryWrapper<MultistageGrid> MultistageGridWrapper = WrapperUtils.getWrapper(false);
					MultistageGridWrapper.eq("floor_id", floor.getId());
					MultistageGridWrapper.orderByAsc("id");
					List<MultistageGrid> multistageGrids = multistageGridService.list(MultistageGridWrapper);
					List<MultistageGridOutput> multistageGridOutputs = new ArrayList<MultistageGridOutput>();
					if (multistageGrids != null && multistageGrids.size() > 0) {
						threeGridSize = threeGridSize + multistageGrids.size();
						for (MultistageGrid multistageGrid : multistageGrids) {
							MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
							multistageGridOutput.setId(multistageGrid.getId());
							multistageGridOutput.setName(multistageGrid.getName());
							QueryWrapper<Toilet> ToiletGridWrapper = WrapperUtils.getWrapper(false);
							ToiletGridWrapper.eq("multistage_grid_id", multistageGrid.getId());
							ToiletGridWrapper.orderByAsc("id");
							List<SuperiorScenesUnionOutput> superiorScenes = new ArrayList<SuperiorScenesUnionOutput>();
							List<Toilet> Toilets = toiletService.list(ToiletGridWrapper);
							if (StringUtil.isNotEmpty(Toilets)) {
								superiorSceneSize = superiorSceneSize + Toilets.size();
								scenesNameSize = scenesNameSize + Toilets.size();
								SuperiorScenesUnionOutput superiorScenesUnionOutput = new SuperiorScenesUnionOutput();
								for (Toilet toilet : Toilets) {
									superiorScenesUnionOutput.setId(0L);
									List<ScenesUnionOutput> toiletScenes = new ArrayList<ScenesUnionOutput>();
									ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, paraMap);
									toiletScenes.add(toiletUnionOutput);
									superiorScenesUnionOutput.setScenes(toiletScenes);
									superiorScenes.add(superiorScenesUnionOutput);
									// 查2级场景
									QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
									positionsWrapper.eq("district_id", districtId);
									positionsWrapper.eq("building_id", building.getId());
									positionsWrapper.eq("floor_id", floor.getId());
									positionsWrapper.eq("toilet_id", toilet.getId());
									positionsWrapper.orderByAsc("id");
									List<Positions> positionss = positionsService.list(positionsWrapper);
									if (StringUtil.isNotEmpty(positionss)) {
										SuperiorScenesUnionOutput toiletScenesUnionOutput = new SuperiorScenesUnionOutput();
										toiletScenesUnionOutput.setId(toilet.getId());
										toiletScenesUnionOutput.setName(toilet.getName());
										List<ScenesUnionOutput> positionsScenes = new ArrayList<ScenesUnionOutput>();
										scenesNameSize = scenesNameSize + positionss.size();
										for (Positions positions : positionss) {
											ScenesUnionOutput positionsUnionOutput = GetScenesPosition(positions, paraMap);
											positionsScenes.add(positionsUnionOutput);
										}
										toiletScenesUnionOutput.setScenes(positionsScenes);
										superiorScenes.add(toiletScenesUnionOutput);
									}
								}
							}
							multistageGridOutput.setSuperiorScenes(superiorScenes);
							multistageGridOutputs.add(multistageGridOutput);
						}
					}

					MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
					QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
					toiletWrapper.eq("district_id", districtId);
					toiletWrapper.eq("building_id", building.getId());
					toiletWrapper.eq("floor_id", floor.getId());
					toiletWrapper.eq("multistage_grid_id", 0);
					toiletWrapper.orderByAsc("id");
					List<SuperiorScenesUnionOutput> superiorScenes = new ArrayList<SuperiorScenesUnionOutput>();
					List<Toilet> Toilets = toiletService.list(toiletWrapper);
					if (StringUtil.isNotEmpty(Toilets)) {
						superiorSceneSize = superiorSceneSize + Toilets.size();
						scenesNameSize = scenesNameSize + Toilets.size();
						for (Toilet toilet : Toilets) {
							SuperiorScenesUnionOutput superiorScenesUnionOutput = new SuperiorScenesUnionOutput();
							// 装一遍自身
							superiorScenesUnionOutput.setId(0L);
							List<ScenesUnionOutput> toiletScenes = new ArrayList<ScenesUnionOutput>();
							ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, paraMap);
							toiletScenes.add(toiletUnionOutput);
							superiorScenesUnionOutput.setScenes(toiletScenes);
							superiorScenes.add(superiorScenesUnionOutput);
							// 查一级场景下的2级场景
							QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
							positionsWrapper.eq("district_id", districtId);
							positionsWrapper.eq("building_id", building.getId());
							positionsWrapper.eq("floor_id", floor.getId());
							positionsWrapper.eq("toilet_id", toilet.getId());
							positionsWrapper.eq("multistage_grid_id", 0);
							positionsWrapper.orderByAsc("id");
							List<Positions> positionss = positionsService.list(positionsWrapper);
							if (StringUtil.isNotEmpty(positionss)) {
								SuperiorScenesUnionOutput toiletScenesUnionOutput = new SuperiorScenesUnionOutput();
								toiletScenesUnionOutput.setId(toilet.getId());
								toiletScenesUnionOutput.setName(toilet.getName());
								List<ScenesUnionOutput> positionsScenes = new ArrayList<ScenesUnionOutput>();
								scenesNameSize = scenesNameSize + positionss.size();
								for (Positions positions : positionss) {
									ScenesUnionOutput positionsUnionOutput = GetScenesPosition(positions, paraMap);
									positionsScenes.add(positionsUnionOutput);
								}
								toiletScenesUnionOutput.setScenes(positionsScenes);
								superiorScenes.add(toiletScenesUnionOutput);
							}
						}
						multistageGridOutput.setSuperiorScenes(superiorScenes);
						multistageGridOutputs.add(multistageGridOutput);
					}
					floorUnionOutout.setMultistageGrid(multistageGridOutputs);
					floorsOut.add(floorUnionOutout);
				}
				BuildingUnionInfoEntity.setFloor(floorsOut);
				dropDownList.add(BuildingUnionInfoEntity);
			}
		}
		districtUnionInfoOutput.setBuilding(dropDownList);
		list.add(districtUnionInfoOutput);
		Map<String, Object> map = new HashMap<String, Object>();
		String fileTemplate = "./temp/sceneTemplate.xlsx";
		File fileOut = new File(fileTemplate);
		// 从jar里读取文件 然后建立临时文件模板 如果temp 目录已经有了就不读取了
		if (!fileOut.exists()) {
			File dirPath = new File("./temp");
			if (!dirPath.exists()) {
				dirPath.mkdir();
			}
			fileOut.createNewFile();// 将模板文件放到临时目录
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/sceneTemplate.xlsx");
			FileOutputStream fos = new FileOutputStream(fileTemplate);
			byte[] b = new byte[1024];
			while ((inputStream.read(b)) != -1) {
				fos.write(b);// 写入数据
			}
			inputStream.close();
			fos.close();// 保存数据
		}
		TemplateExportParams params = new TemplateExportParams(fileTemplate);
		params.setColForEach(true);
		log.info("场景导出对象=" + JSON.toJSONString(list));
		map.put("list", list);
		map.put("superiorSceneSize", superiorSceneSize);
		map.put("scenesNameSize", scenesNameSize);
		map.put("threeGridSize", threeGridSize);
		map.put("twoGridSize", twoGridSize);
		map.put("oneGridSize", oneGridSize);
		Workbook workbook = ExcelExportUtil.exportExcel(params, map);
		String fileName = "场景导出" + DateUtil.format(new Date(), "yyyMMddHHmmss") + ".xlsx";
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
		workbook.write(bufferedOutPut);
		bufferedOutPut.flush();
		bufferedOutPut.close();
	}

	private ScenesUnionOutput GetScenesPosition(Positions positions, Map<String, String> paraMap) {
		ScenesUnionOutput toiletUnionOutput = new ScenesUnionOutput();
		toiletUnionOutput.setId(positions.getId());
		toiletUnionOutput.setName(positions.getName());
		if (positions.getQualityLevel() == 0) {
			toiletUnionOutput.setQualityLevelA("▲");
		}
		if (positions.getQualityLevel() == 1) {
			toiletUnionOutput.setQualityLevelB("▲");
		}
		if (positions.getQualityLevel() == 2) {
			toiletUnionOutput.setQualityLevelC("▲");
		}
		if (positions.getQualityLevel() == 3) {
			toiletUnionOutput.setQualityLevelD("▲");
		}
		// 场景属性赋值
		toiletUnionOutput.setScenesType(paraMap.get(positions.getScenesType() + ""));
		toiletUnionOutput.setSuperiorScenesName(positions.getSuperiorScenesName());
		return toiletUnionOutput;
	}

	private ScenesUnionOutput GetScenesOutput(Toilet toilet, Map<String, String> paraMap) {
		ScenesUnionOutput toiletUnionOutput = new ScenesUnionOutput();
		toiletUnionOutput.setId(toilet.getId());
		toiletUnionOutput.setName(toilet.getName());
		toiletUnionOutput.setSuperiorScenesName("");
		if (toilet.getQualityLevel() == 0) {
			toiletUnionOutput.setQualityLevelA("▲");
		}
		if (toilet.getQualityLevel() == 1) {
			toiletUnionOutput.setQualityLevelB("▲");
		}
		if (toilet.getQualityLevel() == 2) {
			toiletUnionOutput.setQualityLevelC("▲");
		}
		if (toilet.getQualityLevel() == 3) {
			toiletUnionOutput.setQualityLevelD("▲");
		}
		// 场景属性赋值
		toiletUnionOutput.setScenesType(paraMap.get(toilet.getScenesType() + ""));
		return toiletUnionOutput;
	}

	public static void main(String[] args) throws Exception {

		Resource resource = new ClassPathResource("template/场景数据模板.xlsx");
		System.out.println(resource.getFile().getAbsolutePath());
	}

}
