package xiaoqu.home.open.task;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
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.db1.UserDistrictAttendance;
import xiaoqu.home.open.model.db2.Matter;
import xiaoqu.home.open.model.db2.Object;
import xiaoqu.home.open.model.db2.Operation;
import xiaoqu.home.open.model.db2.PunchRecord;
import xiaoqu.home.open.model.db2.PunchRecordDayStatis;
import xiaoqu.home.open.model.db2.SceneObject;
import xiaoqu.home.open.model.db2.Tools;
import xiaoqu.home.open.model.db2.UserToMatter;
import xiaoqu.home.open.model.db2.UserToServiceArea;
import xiaoqu.home.open.publicBean.AttendanceStatusMessage;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
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.db1.UserDistrictAttendanceService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.MatterService;
import xiaoqu.home.open.service.db2.ObjectService;
import xiaoqu.home.open.service.db2.OperationService;
import xiaoqu.home.open.service.db2.PunchRecordDayStatisService;
import xiaoqu.home.open.service.db2.PunchRecordService;
import xiaoqu.home.open.service.db2.SceneObjectService;
import xiaoqu.home.open.service.db2.ToolsService;
import xiaoqu.home.open.service.db2.UserToMatterService;
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.StringUtil;
import xiaoqu.home.open.utils.WrapperUtils;

@Component
@Slf4j(topic = "task")
public class ScheduledTask {

	@Autowired
	private RedisService4 redisService4;
	@Autowired
	private RedisService5 redisService5;
	@Autowired
	private FloorService floorService;
	@Autowired
	private MultistageGridService multistageGridService;
	@Autowired
	private ToiletService toiletService;
	@Autowired
	private PositionsService positionsService;
	@Autowired
	private UserToServiceAreaService userToServiceAreaService;

	@Autowired
	private MatterService matterService;
	@Autowired
	private ObjectService objectService;
	@Autowired
	private OperationService operationService;
	@Autowired
	private ToolsService toolsService;
	@Autowired
	private SceneObjectService sceneObjectService;
	@Autowired
	private UserToMatterService userToMatterService;
	@Autowired
	private UserDistrictAttendanceService userDistrictAttendanceService;

	/******************
	 ** 人员考勤状态变更
	 ******************/
	@Scheduled(cron = "0/1 * * * * ?")
	public void CleanOffWork() {
		Integer autoOffWorkTime = Integer.parseInt(redisService5.hmGet("Dictionary", "AutoOffWorkTime") + "");
		QueryWrapper<UserDistrictAttendance> queryWrapper = WrapperUtils.getWrapper(false);
		int page = 1;
		Page<UserDistrictAttendance> pageList = new Page<UserDistrictAttendance>(page, 100);
		List<UserDistrictAttendance> list = userDistrictAttendanceService.page(pageList, queryWrapper).getRecords();
		long pages = pageList.getPages();
		if (pages == 1) {
			AutoOffWork(autoOffWorkTime, list);
		} else {
			//把第一页的先处理掉
			AutoOffWork(autoOffWorkTime, list);
			//然后处理第二页
			page++;
			for (; page <= pages; page++) {
				QueryWrapper<UserDistrictAttendance> queryWrapper1 = WrapperUtils.getWrapper(false);
				Page<UserDistrictAttendance> pageList1 = new Page<UserDistrictAttendance>(page, 100);
				List<UserDistrictAttendance> list1 = userDistrictAttendanceService.page(pageList1, queryWrapper1).getRecords();
				AutoOffWork(autoOffWorkTime, list1);
			}
		}

	}

	private void AutoOffWork(Integer autoOffWorkTime, List<UserDistrictAttendance> list) {
		for (UserDistrictAttendance userDistrictAttendance : list) {
			if (userDistrictAttendance.getNextOffTime() == null) {
				if (StringUtil.isNotEmpty(userDistrictAttendance.getOffTime())) {
					String yyyyMMdd = DateUtil.format(new Date(), "yyyy-MM-dd");
					Date autoOffTime = DateUtil.parse(yyyyMMdd + " " + userDistrictAttendance.getOffTime() + ":00", "yyyy-MM-dd HH:mm:ss").offset(DateField.HOUR_OF_DAY, autoOffWorkTime);
					userDistrictAttendance.setNextOffTime(autoOffTime);
				} else {
					String yyyyMMdd = DateUtil.format(new Date(), "yyyy-MM-dd");
					userDistrictAttendance.setNextOffTime(DateUtil.parse(yyyyMMdd + " 23:59:00", "yyyy-MM-dd HH:mm:ss"));
				}
				userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
			}
			// 判断下班时间
			if (DateUtil.compare(new Date(), userDistrictAttendance.getNextOffTime()) >= 0) {
				userDistrictAttendance.setWorkStatus(1);// 下班
				userDistrictAttendance.setModifyTime(new Date());
				userDistrictAttendance.setNextOffTime(DateUtil.offsetDay(userDistrictAttendance.getNextOffTime(), 1));// 偏移一天
				userDistrictAttendance.setOnWorkStatus(1);// 可以继续打卡上班
				AttendanceStatusMessage attendanceStatusMessage = new AttendanceStatusMessage();
				attendanceStatusMessage.setMessageType(5);
				attendanceStatusMessage.setUserId(userDistrictAttendance.getUserId());
				attendanceStatusMessage.setAction(0);
				redisService4.lPush("AttendanceStatusMessage", JSON.toJSONString(attendanceStatusMessage));
				userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
			}
		}
	}

	/*************
	 * 删除统一处理
	 */
	@Scheduled(cron = "0/5 * * * * ?")
	public void deleteEntityNotice() {
		while (true) {
			String deleteEntityNoticeString = redisService4.leftPop("DeleteEntityNotice");
			if (deleteEntityNoticeString == null) {
				break;
			}
			log.info("删除统一处理:" + deleteEntityNoticeString);
			DeleteEntityNotice deleteEntityNotice = JSON.parseObject(deleteEntityNoticeString, DeleteEntityNotice.class);
			int type = deleteEntityNotice.getType();
			int level = deleteEntityNotice.getLevel();
			Long id = deleteEntityNotice.getId();
			UpdateWrapper<Floor> floorWrapper = Wrappers.update();
			UpdateWrapper<MultistageGrid> multistageGridWrapper = Wrappers.update();
			UpdateWrapper<Toilet> toiletWrapper = Wrappers.update();
			UpdateWrapper<Positions> positionsWrapper = Wrappers.update();
			UpdateWrapper<UserToServiceArea> userToServiceAreaWrapper = Wrappers.update();
			UpdateWrapper<UserToMatter> userToMatterWrapper = Wrappers.update();
			String classId;
			Date date = new Date();
			switch (type) {
			case 0:
				switch (level) {
				case 1:
					// 更新楼层
					floorWrapper.eq("building_id", id);
					floorWrapper.eq("soft_delete", 0);
					floorWrapper.setSql("soft_delete=1,modify_time= NOW()");
					floorService.update(floorWrapper);
					// 更新3级网格
//					UPDATE `user` SET `name`=REPLACE(`name`,"许三多","许三多1") WHERE mobile='15810934276';
					multistageGridWrapper.eq("building_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("soft_delete=1,modify_time= NOW()");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("building_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("soft_delete=1,modify_time= NOW()");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("building_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("soft_delete=1,modify_time= NOW()");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 1);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("soft_delete=1,modify_time= NOW()");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					classId = "building_id";
					deleteSceneObject(id, classId);
					break;
				case 2:
					// 更新3级网格
					multistageGridWrapper.eq("floor_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("soft_delete=1,modify_time= NOW()");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("floor_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("soft_delete=1,modify_time= NOW()");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("floor_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("soft_delete=1,modify_time= NOW()");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 2);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("soft_delete=1,modify_time= NOW()");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					classId = "floor_id";
					deleteSceneObject(id, classId);
					break;
				case 3:
					// 更新3级网格
					multistageGridWrapper.eq("superior_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("soft_delete=1,modify_time= NOW()");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("multistage_grid_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("soft_delete=1,modify_time= NOW()");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("multistage_grid_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("soft_delete=1,modify_time= NOW()");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 3);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("soft_delete=1,modify_time= NOW()");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					classId = "multistage_grid_id";
					deleteSceneObject(id, classId);
					break;
				case 4:
					// 更新1级场景
					toiletWrapper.eq("multistage_grid_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("soft_delete=1,modify_time= NOW()");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("multistage_grid_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("soft_delete=1,modify_time= NOW()");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 4);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("soft_delete=1,modify_time= NOW()");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					classId = "multistage_grid_id";
					deleteSceneObject(id, classId);
					break;
				}
				break;
			case 1:
				switch (level) {
				case 1:
					// 1级场景对象清除
					classId = "scenes_id";
					deleteSceneObject(id, classId);
					// 2级清除
					QueryWrapper<Positions> wrapper = WrapperUtils.getWrapper(false);
					wrapper.eq("toilet_id", id);
					wrapper.eq("soft_delete", 0);
					List<Positions> list = positionsService.list(wrapper);
					for (Positions positions : list) {
						classId = "scenes_id";
						deleteSceneObject(positions.getId(), classId);
					}
					// 更新2级场景
					positionsWrapper.eq("toilet_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("soft_delete=1,modify_time= NOW()");
					positionsService.update(positionsWrapper);

					break;
				case 2:
					classId = "scenes_id";
					deleteSceneObject(id, classId);
					break;
				}
				break;
			// 对象
			case 2:
				UpdateWrapper<Matter> matterWrapper = Wrappers.update();
				matterWrapper.eq("object_id", id);
				matterWrapper.eq("soft_delete", 0);
				matterWrapper.set("soft_delete", 1);
				matterWrapper.set("modify_time", date);
				matterService.update(matterWrapper);
				UpdateWrapper<Matter> matterParentWrapper = Wrappers.update();
				matterParentWrapper.eq("parent_id", id);
				matterParentWrapper.eq("soft_delete", 0);
				matterParentWrapper.set("soft_delete", 1);
				matterParentWrapper.set("modify_time", date);
				matterService.update(matterParentWrapper);
				UpdateWrapper<Operation> operationWrapper = Wrappers.update();
				operationWrapper.eq("object_id", id);
				operationWrapper.eq("soft_delete", 0);
				operationWrapper.set("soft_delete", 1);
				operationWrapper.set("modify_time", date);
				operationService.update(operationWrapper);
				UpdateWrapper<Operation> operationParentWrapper = Wrappers.update();
				operationParentWrapper.eq("object_parent_id", id);
				operationParentWrapper.eq("soft_delete", 0);
				operationParentWrapper.set("soft_delete", 1);
				operationParentWrapper.set("modify_time", date);
				operationService.update(operationParentWrapper);
				UpdateWrapper<SceneObject> sceneObjectWrapper = Wrappers.update();
				sceneObjectWrapper.eq("object_id", id);
				sceneObjectWrapper.eq("soft_delete", 0);
				sceneObjectWrapper.set("soft_delete", 1);
				sceneObjectWrapper.set("modify_time", date);
				sceneObjectService.update(sceneObjectWrapper);
				UpdateWrapper<SceneObject> sceneObjectParentWrapper = Wrappers.update();
				sceneObjectParentWrapper.eq("object_parent_id", id);
				sceneObjectParentWrapper.eq("soft_delete", 0);
				sceneObjectParentWrapper.set("soft_delete", 1);
				sceneObjectParentWrapper.set("modify_time", date);
				sceneObjectService.update(sceneObjectParentWrapper);
				// 更新人员事项和工作组事项
				userToMatterWrapper.eq("matter_id", id);
				userToMatterWrapper.eq("soft_delete", 0);
				userToMatterWrapper.set("soft_delete", 1);
				userToMatterWrapper.set("modify_time", date);
				userToMatterService.update(userToMatterWrapper);
				UpdateWrapper<Object> objectWrapper = Wrappers.update();
				objectWrapper.eq("parent_id", id);
				objectWrapper.eq("soft_delete", 0);
				objectWrapper.set("soft_delete", 1);
				objectWrapper.set("modify_time", date);
//                    objectWrapper.set("parent_name", newName);
				objectService.update(objectWrapper);
				break;
			// 事项
			case 3:
				break;
			// 作业
			case 4:
				break;
			// 工具
			case 5:

				UpdateWrapper<Operation> operationUpdateWrapper = Wrappers.update();
				operationUpdateWrapper.like("tool_ids", id + ",");
				operationUpdateWrapper.eq("soft_delete", 0);
				operationUpdateWrapper.set("modify_time", date);

				if (deleteEntityNotice.getMemo() != null && !deleteEntityNotice.getMemo().trim().equals("")) {
					operationUpdateWrapper.setSql("tool_names=REPLACE(tool_names,'," + deleteEntityNotice.getMemo() + ",',','),tool_ids=REPLACE(tool_ids,'," + id + ",',',')");
				}
				operationService.update(operationUpdateWrapper);

				UpdateWrapper<Operation> checkoperationUpdateWrapper = Wrappers.update();
				checkoperationUpdateWrapper.eq("tool_ids", ",");
				checkoperationUpdateWrapper.eq("soft_delete", 0);

				if (deleteEntityNotice.getMemo() != null && !deleteEntityNotice.getMemo().trim().equals("")) {
					checkoperationUpdateWrapper.set("tool_ids", ",,");
					checkoperationUpdateWrapper.set("tool_names", ",,");
				}
				operationService.update(checkoperationUpdateWrapper);

				break;
			}

		}
	}

	private void deleteSceneObject(Long id, String classId) {
		UpdateWrapper<SceneObject> sceneObjectWrapper = Wrappers.update();
		sceneObjectWrapper.eq(classId, id);
		sceneObjectWrapper.eq("soft_delete", 0);
		sceneObjectWrapper.set("soft_delete", 1);
		sceneObjectWrapper.set("modify_time", new Date());
		sceneObjectService.update(sceneObjectWrapper);
	}

	/**************
	 * 名称修改统一变更
	 *************/

	@Scheduled(cron = "0/5 * * * * ?")
	public void nameModifyNotice() {
		while (true) {
			String nameModifyNoticeString = redisService4.leftPop("NameModifyNotice");
			if (nameModifyNoticeString == null) {
				break;
			}
			log.info("名称修改统一处理:" + nameModifyNoticeString);
			NameModifyNotice nameModifyNotice = JSON.parseObject(nameModifyNoticeString, NameModifyNotice.class);
			int type = nameModifyNotice.getType();
			int level = nameModifyNotice.getLevel();
			Long id = nameModifyNotice.getId();
			String oldName = nameModifyNotice.getOldName();
			String newName = nameModifyNotice.getNewName();
			UpdateWrapper<Floor> floorWrapper = Wrappers.update();
			UpdateWrapper<MultistageGrid> multistageGridWrapper = Wrappers.update();
			UpdateWrapper<Toilet> toiletWrapper = Wrappers.update();
			UpdateWrapper<Positions> positionsWrapper = Wrappers.update();
			UpdateWrapper<UserToServiceArea> userToServiceAreaWrapper = Wrappers.update();

			switch (type) {
			case 0:
				switch (level) {
				case 1:
					// 更新楼层名称
					floorWrapper.eq("building_id", id);
					floorWrapper.eq("soft_delete", 0);
					floorWrapper.setSql("superior_name='" + newName + "'");
					floorService.update(floorWrapper);
					// 更新3级网格
//					        UPDATE `user` SET `name`=REPLACE(`name`,"许三多","许三多1") WHERE mobile='15810934276';
					multistageGridWrapper.eq("building_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("superior_name=REPLACE(superior_name,'" + oldName + "','" + newName + "')" + ",building_name='" + newName + "'");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("building_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",building_name='" + newName + "'");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("building_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",building_name='" + newName + "'");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 1);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("service_area_name='" + newName + "'");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					// 4.场景对象管理：场景名称中的区域网格?

					updateSceneObjectGrid(id, "building_id", "superior_grid_name", oldName, newName);
					break;
				case 2:
					// 更新3级网格
					multistageGridWrapper.eq("floor_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("superior_name=REPLACE(superior_name,'" + oldName + "','" + newName + "')" + ",floor='" + newName + "'");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("floor_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",floor='" + newName + "'");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("floor_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",floor='" + newName + "'");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 2);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("service_area_name='" + newName + "'");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					// 4.场景对象管理：场景名称中的区域网格?

					updateSceneObjectGrid(id, "floor_id", "superior_grid_name", oldName, newName);

					break;
				case 3:
					// 更新3级网格
					multistageGridWrapper.eq("superior_id", id);
					multistageGridWrapper.eq("soft_delete", 0);
					multistageGridWrapper.setSql("superior_name=REPLACE(superior_name,'" + oldName + "','" + newName + "')");
					multistageGridService.update(multistageGridWrapper);
					// 更新1级场景
					toiletWrapper.eq("multistage_grid_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",multistage_grid_name='" + newName + "'");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("multistage_grid_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",multistage_grid_name='" + newName + "'");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 3);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("service_area_name='" + newName + "'");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					// 4.场景对象管理：场景名称中的区域网格?

					updateSceneObjectGrid(id, "multistage_grid_id", "superior_grid_name", oldName, newName);
					break;
				case 4:
					// 更新1级场景
					toiletWrapper.eq("multistage_grid_id", id);
					toiletWrapper.eq("soft_delete", 0);
					toiletWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",multistage_grid_name='" + newName + "'");
					toiletService.update(toiletWrapper);
					// 更新2级场景
					positionsWrapper.eq("multistage_grid_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("superior_grid_name=REPLACE(superior_grid_name,'" + oldName + "','" + newName + "')" + ",multistage_grid_name='" + newName + "'");
					positionsService.update(positionsWrapper);
					// 3.人员管理：服务区域
					userToServiceAreaWrapper.eq("service_area_id", id);
					userToServiceAreaWrapper.eq("grid_scenes_level", 4);
					userToServiceAreaWrapper.eq("soft_delete", 0);
					userToServiceAreaWrapper.setSql("service_area_name='" + newName + "'");
					userToServiceAreaService.update(userToServiceAreaWrapper);
					// 4.场景对象管理：场景名称中的区域网格?

					updateSceneObjectGrid(id, "multistage_grid_id", "superior_grid_name", oldName, newName);
					break;
				}
				break;
			case 1:
				switch (level) {
				case 1:
					// 更新2级场景
					positionsWrapper.eq("toilet_id", id);
					positionsWrapper.eq("soft_delete", 0);
					positionsWrapper.setSql("superior_scenes_name=REPLACE(superior_scenes_name,'" + oldName + "','" + newName + "')");
					positionsService.update(positionsWrapper);

					updateSceneObjectGrid(id, "scenes_id", "scenes_name", oldName, newName);
					break;
				case 2:
					updateSceneObjectGrid(id, "scenes_id", "scenes_name", oldName, newName);
					break;
				}

				break;
			// 对象
			case 2:
				UpdateWrapper<Matter> matterWrapper = Wrappers.update();
				matterWrapper.eq("object_id", id);
				matterWrapper.eq("soft_delete", 0);
				matterWrapper.set("object_name", newName);
				matterService.update(matterWrapper);
				UpdateWrapper<Matter> matterParentWrapper = Wrappers.update();
				matterParentWrapper.eq("parent_id", id);
				matterParentWrapper.eq("soft_delete", 0);
				matterParentWrapper.set("parent_name", newName);
				matterService.update(matterParentWrapper);
				UpdateWrapper<Operation> operationWrapper = Wrappers.update();
				operationWrapper.eq("object_id", id);
				operationWrapper.eq("soft_delete", 0);
				operationWrapper.set("object_name", newName);
				operationService.update(operationWrapper);
				UpdateWrapper<Operation> operationParentWrapper = Wrappers.update();
				operationParentWrapper.eq("object_parent_id", id);
				operationParentWrapper.eq("soft_delete", 0);
				operationParentWrapper.set("object_parent_name", newName);
				operationService.update(operationParentWrapper);
				UpdateWrapper<SceneObject> sceneObjectWrapper = Wrappers.update();
				sceneObjectWrapper.eq("object_id", id);
				sceneObjectWrapper.eq("soft_delete", 0);
				sceneObjectWrapper.set("object_name", newName);
				sceneObjectService.update(sceneObjectWrapper);
				UpdateWrapper<SceneObject> sceneObjectParentWrapper = Wrappers.update();
				sceneObjectParentWrapper.eq("object_parent_id", id);
				sceneObjectParentWrapper.eq("soft_delete", 0);
				sceneObjectParentWrapper.set("object_parent_name", newName);
				sceneObjectService.update(sceneObjectParentWrapper);
				// 更新人员事项和工作组事项
				UpdateWrapper<UserToMatter> userToMatterWrapper = Wrappers.update();
				userToMatterWrapper.eq("matter_id", id);
				userToMatterWrapper.eq("soft_delete", 0);
				userToMatterWrapper.set("matter_name", newName);
				userToMatterService.update(userToMatterWrapper);
				UpdateWrapper<Object> objectWrapper = Wrappers.update();
				objectWrapper.eq("parent_id", id);
				objectWrapper.eq("soft_delete", 0);
				objectWrapper.set("parent_name", newName);
				objectService.update(objectWrapper);

				break;
			// 事项
			case 3:
				break;
			// 作业
			case 4:
				break;
			// 工具
			case 5:
				UpdateWrapper<Operation> operationUpdateWrapper = Wrappers.update();
				operationUpdateWrapper.like("tool_ids", id);
				operationUpdateWrapper.eq("soft_delete", 0);
				operationUpdateWrapper.setSql("tool_names=REPLACE(tool_names,'," + oldName + ",','," + newName + ",')");
				operationService.update(operationUpdateWrapper);
				UpdateWrapper<Operation> checkoperationUpdateWrapper = Wrappers.update();
				checkoperationUpdateWrapper.eq("tool_ids", ",");
				checkoperationUpdateWrapper.eq("soft_delete", 0);
				checkoperationUpdateWrapper.set("tool_ids", ",,");
				checkoperationUpdateWrapper.set("tool_names", ",,");
				operationService.update(checkoperationUpdateWrapper);

				UpdateWrapper<Tools> toolsWrapper = Wrappers.update();
				toolsWrapper.eq("parent_id", id);
				toolsWrapper.eq("soft_delete", 0);
				toolsWrapper.setSql("parent_name=REPLACE(parent_name,'" + oldName + "','" + newName + "')");
				toolsService.update(toolsWrapper);
				break;
			}
		}
	}

	private void updateSceneObjectGrid(Long id, String classId, String className, String oldName, String newName) {
		UpdateWrapper<SceneObject> sceneObjectWrapper = Wrappers.update();
		sceneObjectWrapper.eq(classId, id);
		sceneObjectWrapper.eq("soft_delete", 0);
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append("modify_time = now(),").append(className).append("=REPLACE(").append(className).append(",'").append(oldName).append("','").append(newName).append("'),");

//                .append(className).append("=").append(newName);
		sceneObjectWrapper.setSql(sqlBuilder.toString());
		sceneObjectService.update(sceneObjectWrapper);

//
//        QueryWrapper<SceneObject> wrapper = WrapperUtils.getWrapper(false);
//        wrapper.eq(classId, id);
//        wrapper.eq("soft_delete", 0);

		UpdateWrapper<SceneObject> parSceneObjectWrapper = Wrappers.update();
		parSceneObjectWrapper.eq("soft_delete", 0);
		parSceneObjectWrapper.eq("superior_scenes_name", oldName);
		parSceneObjectWrapper.set("superior_scenes_name", newName);
		sceneObjectService.update(parSceneObjectWrapper);
	}
	
	@Autowired
	DistrictService districtService;
	@Autowired
	UserService userService;
	@Autowired
	PunchRecordService punchRecordService;
	@Autowired
	PunchRecordDayStatisService punchRecordDayStatisService;
//	/******************
//	 ** 人员打卡记录日统计
//	 ******************/
//	@Scheduled(cron = "0 1 1 * * ?")
//	public void punchRecordStatisDay() {
//		Date yesDate = DateUtil.offsetDay(new Date(), -1);
//		String yesString= DateUtil.format(yesDate, "yyyy-MM-dd");
//		// 先查站点开启打卡的
//		QueryWrapper<District> queryWrapper = WrapperUtils.getWrapper(false);
//		queryWrapper.eq("punch_flag", 1);
//		List<District> districts = districtService.list(queryWrapper);
//		for (District district : districts) {
//			// 哪些人需要统计  当天打过卡的
//			Set<String> districtPunchUserIds = redisService4.setMembers("DistrictPunchUser_"+district.getId());
//			if (districtPunchUserIds.size()==0) {
//				continue;
//			}
//			// 查询所有一级场景
//			QueryWrapper<Toilet> queryWrapperToilet = WrapperUtils.getWrapper(false);
//			queryWrapperToilet.eq("district_id", district.getId());
//			List<Toilet> toilets = toiletService.list(queryWrapperToilet);
//			for (Toilet toilet : toilets) {
//				for (String userId : districtPunchUserIds) {
//					User user = userService.getById(userId);
//					QueryWrapper<PunchRecord> queryWrapperPunchRecord = WrapperUtils.getWrapper(false);
//					queryWrapperPunchRecord.eq("scenes_id", toilet.getId());
//					queryWrapperPunchRecord.eq("scenes_level", 1);
//					queryWrapperPunchRecord.eq("user_id", userId);
//					queryWrapperPunchRecord.ge("punch_time", yesString+" 00:00:00");
//					queryWrapperPunchRecord.le("punch_time", yesString+" 23:59:59");
//					int punchCount = punchRecordService.count(queryWrapperPunchRecord);
//					PunchRecordDayStatis punchRecordDayStatis = new PunchRecordDayStatis();
//					punchRecordDayStatis.setPunchStaisTime(yesDate);
//					punchRecordDayStatis.setAgentId(toilet.getAgentId());
//					punchRecordDayStatis.setAgentName(toilet.getAgentName());
//					punchRecordDayStatis.setPropertyId(toilet.getPropertyId());
//					punchRecordDayStatis.setPropertyName(toilet.getPropertyName());
//					punchRecordDayStatis.setDistrictId(toilet.getDistrictId());
//					punchRecordDayStatis.setDistrictName(toilet.getDistrictName());
//					punchRecordDayStatis.setBuildingId(toilet.getBuildingId());
//					punchRecordDayStatis.setBuildingName(toilet.getBuildingName());
//					punchRecordDayStatis.setFloorId(toilet.getFloorId());
//					punchRecordDayStatis.setFloor(toilet.getFloor());
//					punchRecordDayStatis.setMultistageGridId(toilet.getMultistageGridId());
//					punchRecordDayStatis.setMultistageGridName(toilet.getMultistageGridName());
//					punchRecordDayStatis.setSuperiorGridName(toilet.getSuperiorGridName());
//					punchRecordDayStatis.setGridLevel(toilet.getGridLevel());
//					punchRecordDayStatis.setScenesId(toilet.getId());
//					punchRecordDayStatis.setName(toilet.getName());
//					punchRecordDayStatis.setScenesLevel(toilet.getScenesLevel());
//					punchRecordDayStatis.setUniqueScenesId(toilet.getId()+"_"+toilet.getScenesLevel());
//					String punchAddress=toilet.getSuperiorGridName()+">"+toilet.getName();
//					punchRecordDayStatis.setPunchAddress(punchAddress);
//					punchRecordDayStatis.setUserId(user.getId());
//					punchRecordDayStatis.setUserMobile(user.getMobile());
//					punchRecordDayStatis.setUserName(user.getName());
//					punchRecordDayStatis.setCreateTime(new Date());
//					punchRecordDayStatis.setPunchCount(punchCount);
//					punchRecordDayStatis.setModifyTime(new Date());
//					punchRecordDayStatisService.save(punchRecordDayStatis);
//					
//				}
//			}
//			redisService4.remove("DistrictPunchUser_"+district.getId());
//		}
//		// 哪些人需要统计
//		// 查询所有场景
//		// 匹配人在场景的打卡次数
//		// 入库
//	}
	/******************
	 ** 人员打卡记录日统计测试
	 ******************/
	@Scheduled(cron = "0 */1 * * * ?")
	public void punchRecordStatisDayCeSHi() {
//		Date yesDate = DateUtil.offsetDay(new Date(), -1);
		Date yesDate = new Date();
		String yesString= DateUtil.format(yesDate, "yyyy-MM-dd");
		String yesStringTem= DateUtil.format(yesDate, "yyyy-MM-dd")+" 00:00:00";
		// 先查站点开启打卡的
		QueryWrapper<District> queryWrapper = WrapperUtils.getWrapper(false);
		queryWrapper.eq("punch_flag", 1);
		List<District> districts = districtService.list(queryWrapper);
		for (District district : districts) {
			// 哪些人需要统计  当天打过卡的
			Set<String> districtPunchUserIds = redisService4.setMembers("DistrictPunchUser_"+district.getId());
			if (districtPunchUserIds.size()==0) {
				continue;
			}
			// 查询所有一级场景
			QueryWrapper<Toilet> queryWrapperToilet = WrapperUtils.getWrapper(false);
			queryWrapperToilet.eq("district_id", district.getId());
			List<Toilet> toilets = toiletService.list(queryWrapperToilet);
			for (Toilet toilet : toilets) {
				for (String userId : districtPunchUserIds) {
					User user = userService.getById(userId);
					QueryWrapper<PunchRecord> queryWrapperPunchRecord = WrapperUtils.getWrapper(false);
					queryWrapperPunchRecord.eq("scenes_id", toilet.getId());
					queryWrapperPunchRecord.eq("scenes_level", 1);
					queryWrapperPunchRecord.eq("user_id", userId);
					queryWrapperPunchRecord.ge("punch_time", yesString+" 00:00:00");
					queryWrapperPunchRecord.le("punch_time", yesString+" 23:59:59");
					int punchCount = punchRecordService.count(queryWrapperPunchRecord);
					
					QueryWrapper<PunchRecordDayStatis> queryWrapperPunchRecordDayStatis = WrapperUtils.getWrapper(false);
					queryWrapperPunchRecordDayStatis.eq("punch_stais_time", yesStringTem);
					queryWrapperPunchRecordDayStatis.eq("scenes_id", toilet.getId());
					queryWrapperPunchRecordDayStatis.eq("scenes_level", 1);
					queryWrapperPunchRecordDayStatis.eq("user_id", userId);
					PunchRecordDayStatis punchRecordDayStatis = punchRecordDayStatisService.getOne(queryWrapperPunchRecordDayStatis);
					if (punchRecordDayStatis==null) {
						punchRecordDayStatis = new PunchRecordDayStatis();
						punchRecordDayStatis.setPunchStaisTime(DateUtil.parse(yesStringTem));
						punchRecordDayStatis.setAgentId(toilet.getAgentId());
						punchRecordDayStatis.setAgentName(toilet.getAgentName());
						punchRecordDayStatis.setPropertyId(toilet.getPropertyId());
						punchRecordDayStatis.setPropertyName(toilet.getPropertyName());
						punchRecordDayStatis.setDistrictId(toilet.getDistrictId());
						punchRecordDayStatis.setDistrictName(toilet.getDistrictName());
						punchRecordDayStatis.setBuildingId(toilet.getBuildingId());
						punchRecordDayStatis.setBuildingName(toilet.getBuildingName());
						punchRecordDayStatis.setFloorId(toilet.getFloorId());
						punchRecordDayStatis.setFloor(toilet.getFloor());
						punchRecordDayStatis.setMultistageGridId(toilet.getMultistageGridId());
						punchRecordDayStatis.setMultistageGridName(toilet.getMultistageGridName());
						punchRecordDayStatis.setSuperiorGridName(toilet.getSuperiorGridName());
						punchRecordDayStatis.setGridLevel(toilet.getGridLevel());
						punchRecordDayStatis.setScenesId(toilet.getId());
						punchRecordDayStatis.setName(toilet.getName());
						punchRecordDayStatis.setScenesLevel(toilet.getScenesLevel());
						punchRecordDayStatis.setUniqueScenesId(toilet.getId()+"_"+toilet.getScenesLevel());
						String punchAddress=toilet.getSuperiorGridName()+">"+toilet.getName();
						punchRecordDayStatis.setPunchAddress(punchAddress);
						punchRecordDayStatis.setUserId(user.getId());
						punchRecordDayStatis.setUserMobile(user.getMobile());
						punchRecordDayStatis.setUserName(user.getName());
						punchRecordDayStatis.setCreateTime(new Date());
						punchRecordDayStatis.setPunchCount(punchCount);
						punchRecordDayStatis.setModifyTime(new Date());
						punchRecordDayStatisService.save(punchRecordDayStatis);
						
					}else {
						punchRecordDayStatis.setPunchCount(punchCount);
						punchRecordDayStatis.setModifyTime(new Date());
						punchRecordDayStatisService.updateById(punchRecordDayStatis);
					}
				}
			}
			redisService4.remove("DistrictPunchUser_"+district.getId());
		}
		// 哪些人需要统计
		// 查询所有场景
		// 匹配人在场景的打卡次数
		// 入库
	}

}
