package xiaoqu.home.open.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
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 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 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.UserExportOutput;
import xiaoqu.home.open.controller.input.DistrictIdIAndUserIdnput;
import xiaoqu.home.open.controller.input.grid.GridSelectInput2;
import xiaoqu.home.open.controller.input.task.GridAndSceneInput;
import xiaoqu.home.open.controller.input.user.UserDistrictMenuInput;
import xiaoqu.home.open.controller.input.user.UserInsertInput;
import xiaoqu.home.open.controller.input.user.UserPageInput;
import xiaoqu.home.open.controller.input.user.UserParamInput;
import xiaoqu.home.open.controller.output.MenuOutInfo;
import xiaoqu.home.open.controller.output.MyUserMenuOutput;
import xiaoqu.home.open.controller.output.user.UserAuthorityOutput;
import xiaoqu.home.open.controller.output.user.UserOutput;
import xiaoqu.home.open.controller.output.user.UserSelectOutput;
import xiaoqu.home.open.model.db1.Agent;
import xiaoqu.home.open.model.db1.AppMenu;
import xiaoqu.home.open.model.db1.District;
import xiaoqu.home.open.model.db1.MyMenu;
import xiaoqu.home.open.model.db1.MyUserMenu;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db1.UserDistrictAttendance;
import xiaoqu.home.open.model.db1.UserMenuDistrict;
import xiaoqu.home.open.model.db1.UserProper;
import xiaoqu.home.open.model.db1.UserToilet;
import xiaoqu.home.open.model.db2.FieldWebpageAuthority;
import xiaoqu.home.open.model.db2.LabelManage;
import xiaoqu.home.open.model.db2.SkillManage;
import xiaoqu.home.open.model.db2.UserToLabel;
import xiaoqu.home.open.model.db2.UserToMatter;
import xiaoqu.home.open.model.db2.UserToServiceArea;
import xiaoqu.home.open.model.db2.UserToSkill;
import xiaoqu.home.open.model.db2.WorkGroup;
import xiaoqu.home.open.model.db2.WorkGroupToPrincipal;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.IdToNameEntity;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.AgentService;
import xiaoqu.home.open.service.db1.AppMenuService;
import xiaoqu.home.open.service.db1.DistrictService;
import xiaoqu.home.open.service.db1.MyMenuService;
import xiaoqu.home.open.service.db1.MyUserMenuService;
import xiaoqu.home.open.service.db1.UserDistrictAttendanceService;
import xiaoqu.home.open.service.db1.UserMenuDistrictService;
import xiaoqu.home.open.service.db1.UserProperService;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db1.UserToiletService;
import xiaoqu.home.open.service.db2.FieldWebpageAuthorityService;
import xiaoqu.home.open.service.db2.LabelManageService;
import xiaoqu.home.open.service.db2.SkillManageService;
import xiaoqu.home.open.service.db2.UserToLabelService;
import xiaoqu.home.open.service.db2.UserToMatterService;
import xiaoqu.home.open.service.db2.UserToServiceAreaService;
import xiaoqu.home.open.service.db2.UserToSkillService;
import xiaoqu.home.open.service.db2.WorkGroupService;
import xiaoqu.home.open.service.db2.WorkGroupToPrincipalService;
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 = "/userCenter")
@Api(value = "用户中心服务", description = "用户中心服务")
@Slf4j(topic = "Controller")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private UserProperService userProperService;
	@Autowired
	private SkillManageService skillManageService;
	@Autowired
	private UserToSkillService userToSkillService;
	@Autowired
	private LabelManageService labelManageService;
	@Autowired
	private UserToLabelService userToLabelService;
	@Autowired
	private UserToMatterService userToMatterService;
	@Autowired
	private UserToServiceAreaService userToServiceAreaService;
	@Autowired
	private WorkGroupService workGroupService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private RedisService5 redisService5;
	@Autowired
	private WorkGroupToPrincipalService workGroupToPrincipalService;
	@Autowired
	private UserToiletService userToiletService;

	@Autowired
	private FieldWebpageAuthorityService fieldWebpageAuthorityService;
	@Autowired
	private UserDistrictAttendanceService userDistrictAttendanceService;

	@ApiOperation(value = "用户分页查询")
	@ResponseBody
	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<UserOutput>> pageList(HttpServletRequest request, @RequestBody UserPageInput input) {
		PageOutput<UserOutput> output = new PageOutput<UserOutput>();
		Long districtId = input.getDistrictId();
		if (StringUtil.isNull(districtId)) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (StringUtil.isNull(district)) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		QueryWrapper<UserProper> queryWrapper = WrapperUtils.getWrapper(false);
		queryWrapper.eq("district_id", districtId);
		queryWrapper.in("type", 0, 1);
		List<UserProper> userPropers = userProperService.list(queryWrapper);
		Set<Long> userIds = userPropers.stream().map(userProper -> userProper.getUserId()).collect(Collectors.toSet());
		if (userIds.size() == 0) {
			return ResultResponseBeanUtil.success(output);
		}
		input.setDistrictId(null);
		QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);

		wrapper.in("id", userIds);
		// 特殊处理 连表查询
		List<GridAndSceneInput> serviceAreas1 = input.getServiceAreas();
		if (StringUtil.isNotEmpty(serviceAreas1)) {
			Set<Long> userIds1 = new HashSet<Long>();
			for (GridAndSceneInput gridSelectInput : serviceAreas1) {
				QueryWrapper<UserToServiceArea> userToServiceAreaWrapper = WrapperUtils.getWrapper(false);
				userToServiceAreaWrapper.eq("district_id", districtId);
				userToServiceAreaWrapper.eq("service_area_id", gridSelectInput.getGridId());
				userToServiceAreaWrapper.eq("grid_scenes_level", gridSelectInput.getLevel());
				userToServiceAreaWrapper.eq("service_type", gridSelectInput.getIsscene());
				List<UserToServiceArea> tempList = userToServiceAreaService.list(userToServiceAreaWrapper);
				if (StringUtil.isNotEmpty(tempList)) {
					userIds1.addAll(tempList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds1.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			}
			wrapper.in("id", userIds1);
		}
		input.setServiceAreas(null);
		List<IdToNameEntity> serviceEvents1 = input.getServiceEvents();
		if (StringUtil.isNotEmpty(serviceEvents1)) {
			Set<Long> userIds2 = new HashSet<Long>();
			for (IdToNameEntity idToNameEntity : serviceEvents1) {
				QueryWrapper<UserToMatter> wrapperM = WrapperUtils.getWrapper(false);
				wrapperM.eq("district_id", districtId);
				wrapperM.eq("matter_id", idToNameEntity.getId());
				List<UserToMatter> userToMatterList = userToMatterService.list(wrapperM);
				if (StringUtil.isNotEmpty(userToMatterList)) {
					userIds2.addAll(userToMatterList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds2.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			}
			wrapper.in("id", userIds2);
		}
		input.setServiceEvents(null);
		List<IdToNameEntity> groupsQ = input.getGroups();
		if (StringUtil.isNotEmpty(groupsQ)) {
			Set<Long> userIds3 = new HashSet<Long>();
			for (IdToNameEntity idToNameEntity : groupsQ) {
				QueryWrapper<WorkGroupToPrincipal> wrapperM = WrapperUtils.getWrapper(false);
				wrapperM.eq("district_id", districtId);
				wrapperM.eq("work_group_id", idToNameEntity.getId());
				List<WorkGroupToPrincipal> userToMatterList = workGroupToPrincipalService.list(wrapperM);
				if (StringUtil.isNotEmpty(userToMatterList)) {
					userIds3.addAll(userToMatterList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds3.size() == 0) {
				return ResultResponseBeanUtil.success(output);
			}
			wrapper.in("id", userIds3);
		}
		input.setGroups(null);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		User user = UserUtils.getUser(request);
		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] columns = WrapperUtils.entityToColumns(fieldList);
		wrapper.select(columns);
		Page<User> pageList = new Page<User>(input.getPage(), input.getRows());
		List<User> userList = userService.page(pageList, wrapper).getRecords();
		List<UserOutput> userListOut = new ArrayList<UserOutput>();
		for (User userT : userList) {
			UserOutput userOutput = new UserOutput();
			BeanUtils.copyProperties(userT, userOutput);
			userOutput.setDistrictId(districtId);
			userOutput.setDistrictName(district.getDistrictName());
//			@ApiModelProperty(value = "标签名称")
			QueryWrapper<UserToLabel> userTWrapper = WrapperUtils.getWrapper(false);
			userTWrapper.eq("user_id", userOutput.getId());
			userTWrapper.eq("district_id", districtId);
			List<UserToLabel> userToLabelList = userToLabelService.list(userTWrapper);
			userOutput.setLabelName(userToLabelList.stream().map(UserToLabel -> UserToLabel.getLabelName()).collect(Collectors.joining(",")));
			List<IdToNameEntity> lableId = new ArrayList<IdToNameEntity>();
			for (UserToLabel userToLabel : userToLabelList) {
				IdToNameEntity idToNameEntity = new IdToNameEntity();
				idToNameEntity.setId(userToLabel.getLabelId());
				idToNameEntity.setName(userToLabel.getLabelName());
				lableId.add(idToNameEntity);
			}
			userOutput.setLabels(lableId);
//			@ApiModelProperty(value = "技能")
			QueryWrapper<UserToSkill> userSWrapper = WrapperUtils.getWrapper(false);
			userSWrapper.eq("user_id", userOutput.getId());
			userSWrapper.eq("district_id", districtId);
			List<UserToSkill> userToSkilllList = userToSkillService.list(userSWrapper);
			userOutput.setSkillName(userToSkilllList.stream().map(userToSkill -> userToSkill.getSkillName()).collect(Collectors.joining(",")));
//			@ApiModelProperty(value = "技能返现")
			List<IdToNameEntity> skillId = new ArrayList<IdToNameEntity>();
			for (UserToSkill userToSkill : userToSkilllList) {
				IdToNameEntity idToNameEntity = new IdToNameEntity();
				idToNameEntity.setId(userToSkill.getSkillId());
				idToNameEntity.setName(userToSkill.getSkillName());
				skillId.add(idToNameEntity);
			}
			userOutput.setSkills(skillId);
//			@ApiModelProperty(value = "服务区域个数")
//			private int serviceAreaCount;
			QueryWrapper<UserToServiceArea> userToServiceAreaWrapper = WrapperUtils.getWrapper(false);
			userToServiceAreaWrapper.eq("user_id", userOutput.getId());
			userToServiceAreaWrapper.eq("district_id", districtId);
			List<UserToServiceArea> userToServiceAreaList = userToServiceAreaService.list(userToServiceAreaWrapper);
			userOutput.setServiceAreaCount(userToServiceAreaList.size());
			List<GridSelectInput2> serviceAreas = new ArrayList<GridSelectInput2>();
			for (UserToServiceArea userToServiceArea : userToServiceAreaList) {
				GridSelectInput2 gridSelectInput2 = new GridSelectInput2();
				if (userToServiceArea.getServiceType() == 0) {
					gridSelectInput2.setGridIdAndLevel(userToServiceArea.getServiceAreaId() + "_" + userToServiceArea.getGridScenesLevel());
				} else {
					gridSelectInput2.setGridIdAndLevel(userToServiceArea.getServiceAreaId() + "_s" + userToServiceArea.getGridScenesLevel());
				}
				serviceAreas.add(gridSelectInput2);
			}
			userOutput.setServiceAreas(serviceAreas);
//			@ApiModelProperty(value = "服务事项个数")
//			private int serviceEventCount;
			QueryWrapper<UserToMatter> userToMatterWrapper = WrapperUtils.getWrapper(false);
			userToMatterWrapper.eq("user_id", userOutput.getId());
			userToMatterWrapper.eq("district_id", districtId);
			List<UserToMatter> userToMatterlisList = userToMatterService.list(userToMatterWrapper);
			userOutput.setServiceEventCount(userToMatterlisList.size());
			List<IdToNameEntity> serviceEventId = new ArrayList<IdToNameEntity>();
			for (UserToMatter userToMatter : userToMatterlisList) {
				IdToNameEntity idToNameEntity = new IdToNameEntity();
				idToNameEntity.setId(userToMatter.getMatterId());
				idToNameEntity.setName(userToMatter.getMatterName());
				serviceEventId.add(idToNameEntity);
			}
			userOutput.setServiceEvents(serviceEventId);

			QueryWrapper<WorkGroupToPrincipal> workGroupToPrincipalWrapper = WrapperUtils.getWrapper(false);
			workGroupToPrincipalWrapper.eq("user_id", userOutput.getId());
			workGroupToPrincipalWrapper.eq("district_id", districtId);
			List<WorkGroupToPrincipal> workGroupToPrincipalList = workGroupToPrincipalService.list(workGroupToPrincipalWrapper);
			List<IdToNameEntity> groups = new ArrayList<IdToNameEntity>();
			userOutput.setGroupsName(workGroupToPrincipalList.stream().map(workGroupToPrincipal -> workGroupToPrincipal.getWorkGroupName()).collect(Collectors.joining(",")));
			for (WorkGroupToPrincipal workGroupToPrincipal : workGroupToPrincipalList) {
				IdToNameEntity idToNameEntity = new IdToNameEntity();
				idToNameEntity.setId(workGroupToPrincipal.getWorkGroupId());
				idToNameEntity.setName(workGroupToPrincipal.getWorkGroupName());
				groups.add(idToNameEntity);
			}
			userOutput.setGroups(groups);
			if (StringUtil.isNotEmpty(userT.getBirthday())) {
				userOutput.setAge(DateUtil.age(DateUtil.parse(userT.getBirthday(), "yyyy-MM-dd"), DateUtil.date()));
			}
			UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(districtId, userT.getId());
			userOutput.setOffTime(userDistrictAttendance.getOffTime());
			userOutput.setOnTime(userDistrictAttendance.getOnTime());
			userOutput.setWorkStatus(userDistrictAttendance.getWorkStatus());
			userOutput.setWorkAtStatus(userDistrictAttendance.getWorkAtStatus());
			if (StringUtil.isNotEmpty(userOutput.getOnTime())) {
				userOutput.setOnAndOffTime(userOutput.getOnTime() + "至" + userOutput.getOffTime());
			}
			userListOut.add(userOutput);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(userListOut);
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "人员导出")
	@PostMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody UserPageInput input) throws IOException {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return;
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return;
		}
		List<UserExportOutput> outList = new ArrayList<UserExportOutput>();
		User user = UserUtils.getUser(request);
		QueryWrapper<UserProper> queryWrapper = WrapperUtils.getWrapper(false);
		queryWrapper.eq("district_id", districtId);
		queryWrapper.in("type", 0, 1);
		List<UserProper> userPropers = userProperService.list(queryWrapper);
		Set<Long> userIds = userPropers.stream().map(userProper -> userProper.getUserId()).collect(Collectors.toSet());
		if (userIds.size() == 0) {
			return;
		}
		input.setDistrictId(null);
		QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		wrapper.in("id", userIds);

		// 特殊处理 连表查询
		List<GridAndSceneInput> serviceAreas1 = input.getServiceAreas();
		if (StringUtil.isNotEmpty(serviceAreas1)) {
			Set<Long> userIds1 = new HashSet<Long>();
			for (GridAndSceneInput gridSelectInput : serviceAreas1) {
				QueryWrapper<UserToServiceArea> userToServiceAreaWrapper = WrapperUtils.getWrapper(false);
				userToServiceAreaWrapper.eq("district_id", districtId);
				userToServiceAreaWrapper.eq("service_areas_id", gridSelectInput.getGridId());
				userToServiceAreaWrapper.eq("grid_scenes_level", gridSelectInput.getLevel());
				userToServiceAreaWrapper.eq("service_type", gridSelectInput.getIsscene());
				List<UserToServiceArea> tempList = userToServiceAreaService.list(userToServiceAreaWrapper);
				if (StringUtil.isNotEmpty(tempList)) {
					userIds1.addAll(tempList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds1.size() == 0) {
				return;
			}
			wrapper.in("id", userIds1);
		}
		input.setServiceAreas(null);
		List<IdToNameEntity> serviceEvents1 = input.getServiceEvents();
		if (StringUtil.isNotEmpty(serviceEvents1)) {
			Set<Long> userIds2 = new HashSet<Long>();
			for (IdToNameEntity idToNameEntity : serviceEvents1) {
				QueryWrapper<UserToMatter> wrapperM = WrapperUtils.getWrapper(false);
				wrapperM.eq("district_id", districtId);
				wrapperM.eq("matter_id", idToNameEntity.getId());
				List<UserToMatter> userToMatterList = userToMatterService.list(wrapperM);
				if (StringUtil.isNotEmpty(userToMatterList)) {
					userIds2.addAll(userToMatterList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds2.size() == 0) {
				return;
			}
			wrapper.in("id", userIds2);
		}
		input.setServiceEvents(null);
		List<IdToNameEntity> groups = input.getGroups();
		if (StringUtil.isNotEmpty(groups)) {
			Set<Long> userIds3 = new HashSet<Long>();
			for (IdToNameEntity idToNameEntity : serviceEvents1) {
				QueryWrapper<WorkGroupToPrincipal> wrapperM = WrapperUtils.getWrapper(false);
				wrapperM.eq("district_id", districtId);
				wrapperM.eq("work_group_id", idToNameEntity.getId());
				List<WorkGroupToPrincipal> userToMatterList = workGroupToPrincipalService.list(wrapperM);
				if (StringUtil.isNotEmpty(userToMatterList)) {
					userIds3.addAll(userToMatterList.stream().map(bean -> bean.getUserId()).collect(Collectors.toSet()));
				}
			}
			if (userIds3.size() == 0) {
				return;
			}
			wrapper.in("id", userIds3);
		}
		input.setGroups(null);

		List<User> userList = userService.list(wrapper);
		for (User userT : userList) {
			UserExportOutput userOutput = new UserExportOutput();
			BeanUtils.copyProperties(userT, userOutput);
			UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(districtId, userT.getId());
			userT.setOffTime(userDistrictAttendance.getOffTime());
			userT.setOnTime(userDistrictAttendance.getOnTime());
			userOutput.setWorkStatus(userDistrictAttendance.getWorkStatus());
			userOutput.setWorkAtStatus(userDistrictAttendance.getWorkAtStatus());
			if (StringUtil.isNotEmpty(userT.getOnTime())) {
				userOutput.setOnAndOffTime(userT.getOnTime() + "至" + userT.getOffTime());
			}
			userOutput.setDistrictName(district.getDistrictName());
			QueryWrapper<UserToLabel> userTWrapper = WrapperUtils.getWrapper(false);
			userTWrapper.eq("user_id", userOutput.getId());
			userTWrapper.eq("district_id", districtId);
			List<UserToLabel> userToLabelList = userToLabelService.list(userTWrapper);
			userOutput.setLabelName(userToLabelList.stream().map(UserToLabel -> UserToLabel.getLabelName()).collect(Collectors.joining(",")));
			QueryWrapper<UserToSkill> userSWrapper = WrapperUtils.getWrapper(false);
			userSWrapper.eq("user_id", userOutput.getId());
			userSWrapper.eq("district_id", districtId);
			List<UserToSkill> userToSkilllList = userToSkillService.list(userSWrapper);
			userOutput.setSkillName(userToSkilllList.stream().map(userToSkill -> userToSkill.getSkillName()).collect(Collectors.joining(",")));
			QueryWrapper<UserToServiceArea> userToServiceAreaWrapper = WrapperUtils.getWrapper(false);
			userToServiceAreaWrapper.eq("user_id", userOutput.getId());
			userToServiceAreaWrapper.eq("district_id", districtId);
			List<UserToServiceArea> userToServiceAreaList = userToServiceAreaService.list(userToServiceAreaWrapper);
			userOutput.setServiceAreaCount(userToServiceAreaList.size());
			QueryWrapper<UserToMatter> userToMatterWrapper = WrapperUtils.getWrapper(false);
			userToMatterWrapper.eq("user_id", userOutput.getId());
			userToMatterWrapper.eq("district_id", districtId);
			List<UserToMatter> userToMatterlisList = userToMatterService.list(userToMatterWrapper);
			userOutput.setServiceEventCount(userToMatterlisList.size());

			QueryWrapper<WorkGroupToPrincipal> workGroupToPrincipalWrapper = WrapperUtils.getWrapper(false);
			workGroupToPrincipalWrapper.eq("user_id", userOutput.getId());
			workGroupToPrincipalWrapper.eq("district_id", districtId);
			List<WorkGroupToPrincipal> workGroupToPrincipalList = workGroupToPrincipalService.list(workGroupToPrincipalWrapper);
			userOutput.setGroupsName(workGroupToPrincipalList.stream().map(workGroupToPrincipal -> workGroupToPrincipal.getWorkGroupName()).collect(Collectors.joining(",")));
			if (StringUtil.isNotEmpty(userT.getBirthday())) {
				userOutput.setAge(DateUtil.age(DateUtil.parse(userT.getBirthday(), "yyyy-MM-dd"), DateUtil.date()));
			}
			
			outList.add(userOutput);
		}

		List<FieldWebpageAuthority> fieldList = fieldWebpageAuthorityService.getExportFieldList(input.getWebId(), user.getPropertyAuthorityId());
		String[] exportColumns = WrapperUtils.entityToColumns(fieldList);
		ExcelUtil<UserExportOutput> util = new ExcelUtil<UserExportOutput>(UserExportOutput.class);
		util.exportExcelByColumns(response, outList, "人员管理", exportColumns);
	}

	@ApiOperation(value = "负责人选择列表")
	@ResponseBody
	@RequestMapping(value = "/selectList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<User>> selectList(HttpServletRequest request, @RequestBody UserPageInput input) {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		PageOutput<User> output = new PageOutput<User>();
		QueryWrapper<UserProper> wrapperUP = WrapperUtils.getWrapper(false);
		wrapperUP.eq("district_id", districtId);
		wrapperUP.in("type", 0, 1);// 保洁和物业
		List<UserProper> userPropers = userProperService.list(wrapperUP);
		if (userPropers == null || userPropers.size() == 0) {
			return ResultResponseBeanUtil.success(output);
		}
		Set<Long> userIds = userPropers.stream().map(userProper -> userProper.getUserId()).collect(Collectors.toSet());
		input.setDistrictId(null);
		QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
		wrapper.in("id", userIds);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		Page<User> pageList = new Page<User>(input.getPage(), input.getRows());
		List<User> userList = userService.page(pageList, wrapper).getRecords();
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(userList);
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "新增或更新")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
	public BaseOutput<String> addOrUpdate(HttpServletRequest request, @RequestBody UserInsertInput input) {
		Integer autoOffWorkTime = Integer.parseInt(redisService5.hmGet("Dictionary", "AutoOffWorkTime") + "");
		log.info("用户中心添加=" + JSON.toJSONString(input));
		User user = UserUtils.getUser(request);
		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.getId() != null && input.getId() != 0) {// 修改
			User userNew = userService.getById(input.getId());
			if (userNew == null) {
				return ResultResponseBeanUtil.fail("该客户不存在,请确认");
			}
			QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("mobile", input.getMobile());
			wrapper.eq("soft_delete", 0);
			User temp = userService.getOne(wrapper);
			if (temp != null && input.getId().intValue() != temp.getId().intValue()) {
				return ResultResponseBeanUtil.fail("该手机号已经存在");
			}
			BeanUtils.copyProperties(input, userNew);
			userNew.setModifyName(user.getName());
			userNew.setModifyId(user.getId());
			userNew.setModifyTime(new Date());
			if (StringUtil.isNotEmpty(input.getBirthday())) {
				userNew.setAge(DateUtil.age(DateUtil.parse(input.getBirthday(), "yyyy-MM-dd"), DateUtil.date()));
			}
			UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(input.getDistrictId(), input.getId());
			userDistrictAttendance.setOffTime(input.getOffTime());
			userDistrictAttendance.setOnTime(input.getOnTime());
			userDistrictAttendance.setCrossDay(0);
			if (StringUtil.isNotEmpty(userDistrictAttendance.getOffTime())) {
				String onTime = userDistrictAttendance.getOnTime();
				String offTime = userDistrictAttendance.getOffTime();
				Integer onTimeInt = Integer.parseInt(onTime.substring(0, 2));
				Integer offTimeInt = Integer.parseInt(offTime.substring(0, 2));
				if (offTimeInt > onTimeInt) {
					userDistrictAttendance.setCrossDay(0);
				} else {
					userDistrictAttendance.setCrossDay(1);
				}
				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);
			}
			userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
			userService.updateById(userNew);
			Long userId = userNew.getId();
			List<IdToNameEntity> skills = input.getSkills();
			// 先删除之前的
			UpdateWrapper<UserToSkill> updateWrapperSk = Wrappers.update();
			updateWrapperSk.eq("user_id", userId);
			updateWrapperSk.eq("soft_delete", 0);
			updateWrapperSk.eq("district_id", districtId);
			updateWrapperSk.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			userToSkillService.update(updateWrapperSk);
			if (StringUtil.isNotEmpty(skills)) {
				for (IdToNameEntity idToNameEntity : skills) {
					UserToSkill userToSkill = new UserToSkill();
					SkillManage skillManage = skillManageService.getById(idToNameEntity.getId());
					userToSkill.setUserId(userId);
					userToSkill.setColorValue(skillManage.getColorValue());
					userToSkill.setSkillId(idToNameEntity.getId());
					userToSkill.setSkillName(skillManage.getSkillName());
					userToSkill.setCreateId(user.getId());
					userToSkill.setCreateTime(new Date());
					userToSkill.setDistrictId(districtId);
					userToSkillService.save(userToSkill);
				}
			}
			List<IdToNameEntity> lables = input.getLabels();
			// 先删除之前的
			UpdateWrapper<UserToLabel> updateWrapperLa = Wrappers.update();
			updateWrapperLa.eq("user_id", userId);
			updateWrapperLa.eq("soft_delete", 0);
			updateWrapperLa.eq("district_id", districtId);
			updateWrapperLa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			userToLabelService.update(updateWrapperLa);
			if (StringUtil.isNotEmpty(lables)) {
				for (IdToNameEntity idToNameEntity : lables) {
					UserToLabel userToLable = new UserToLabel();
					LabelManage labelManage = labelManageService.getById(idToNameEntity.getId());
					userToLable.setUserId(userId);
					userToLable.setColorValue(labelManage.getColorValue());
					userToLable.setLabelId(idToNameEntity.getId());
					userToLable.setLabelName(labelManage.getLabelName());
					userToLable.setCreateId(user.getId());
					userToLable.setCreateTime(new Date());
					userToLable.setDistrictId(districtId);
					userToLabelService.save(userToLable);
				}

			}
			// 先删除之前的
			UpdateWrapper<WorkGroupToPrincipal> updateWrapperPr = Wrappers.update();
			updateWrapperPr.eq("user_id", userId);
			updateWrapperPr.eq("soft_delete", 0);
			updateWrapperPr.eq("district_id", districtId);
			updateWrapperPr.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			workGroupToPrincipalService.update(updateWrapperPr);
			List<IdToNameEntity> groups = input.getGroups();
			if (StringUtil.isNotEmpty(groups)) {
				for (IdToNameEntity idToNameEntity : groups) {
					WorkGroupToPrincipal workGroupToPrincipal = new WorkGroupToPrincipal();
					WorkGroup workGroup = workGroupService.getById(idToNameEntity.getId());
					BeanUtils.copyProperties(workGroup, workGroupToPrincipal, "id", "modifyTime", "modifyId", "modifyName");
					workGroupToPrincipal.setCreateId(user.getId());
					workGroupToPrincipal.setCreateTime(new Date());
					workGroupToPrincipal.setCreateName(user.getName());
// 					@ApiModelProperty(value = "班组ID")
					workGroupToPrincipal.setWorkGroupId(workGroup.getId());
//					@ApiModelProperty(value = "所属班组")
					workGroupToPrincipal.setWorkGroupName(workGroup.getWorkGroupName());
//					@ApiModelProperty(value = "人员ID")
					workGroupToPrincipal.setUserId(userId);
//					@ApiModelProperty(value = "姓名")
					workGroupToPrincipal.setUserName(userNew.getName());
//					@ApiModelProperty(value = "手机号")
					workGroupToPrincipal.setMobile(userNew.getMobile());
//					@ApiModelProperty(value = "账号角色类型1:运维;2:保洁;3:富士康;4:老化;5:物业;6:代理")
					workGroupToPrincipal.setApprole(userNew.getApprole());
//				    @ApiModelProperty(value = "系统权限0:管理权限;1:普通权限")
					workGroupToPrincipal.setRoleType(userNew.getRoleType());
//					@ApiModelProperty(value = "负责人标识0:否;1:是")
					workGroupToPrincipal.setPrincipalFlag(0);
					workGroupToPrincipal.setDistrictId(districtId);
					workGroupToPrincipalService.save(workGroupToPrincipal);
				}
			}
// 			先删除之前的
			QueryWrapper<UserToServiceArea> updateWrapperUa = WrapperUtils.getWrapper(false);
			updateWrapperUa.eq("user_id", userId);
			updateWrapperUa.eq("soft_delete", 0);
			updateWrapperUa.eq("district_id", districtId);
			List<UserToServiceArea> tempToServiceAreas = userToServiceAreaService.list(updateWrapperUa);
			for (UserToServiceArea userToServiceArea : tempToServiceAreas) {
				userToServiceArea.setSoftDelete(1);
				userToServiceArea.setModifyId(user.getId());
				userToServiceArea.setModifyTime(new Date());
				userToServiceAreaService.updateById(userToServiceArea);
			}
			QueryWrapper<UserToilet> userToiletWrapper = WrapperUtils.getWrapper(false);
			userToiletWrapper.eq("user_id", userId);
			userToiletWrapper.eq("soft_delete", 0);
			userToiletWrapper.eq("district_id", districtId);
			List<UserToilet> userToilets = userToiletService.list(userToiletWrapper);
			for (UserToilet userToilet : userToilets) {
				userToilet.setSoftDelete(1);
				userToilet.setModifyId(user.getId());
				userToilet.setModifyTime(new Date());
				userToiletService.updateById(userToilet);
				redisService5.setRemove("ToiletToUser:" + userToilet.getToiletId(), userId + "");
			}
			redisService5.remove("UserToilet:" + userId + "_" + input.getDistrictId());
			List<GridAndSceneInput> serviceAreas = input.getServiceAreas();
			if (StringUtil.isNotEmpty(serviceAreas)) {
				for (GridAndSceneInput gridSelectInput : serviceAreas) {
					UserToServiceArea userToServiceArea = new UserToServiceArea();
					userToServiceArea.setUserId(userId);
					userToServiceArea.setCreateId(user.getId());
					userToServiceArea.setCreateTime(new Date());
//				    @ApiModelProperty(value = "服务区域")
					userToServiceArea.setServiceAreaName(gridSelectInput.getName());
//				    @ApiModelProperty(value = "服务分类0:区域;1:场景")
					userToServiceArea.setServiceType(gridSelectInput.getIsscene());
//				    @ApiModelProperty(value = "服务区域ID")
					userToServiceArea.setServiceAreaId(gridSelectInput.getGridId());
					if (gridSelectInput.getIsscene() == 1) {
						userToServiceArea.setServiceAreaId(gridSelectInput.getSceneId());
					}
//				    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
					userToServiceArea.setGridScenesLevel(gridSelectInput.getLevel());
					userToServiceArea.setDistrictId(districtId);
					userToServiceAreaService.save(userToServiceArea);
					// 同步内存数据 只同步厕所属性的
					if (gridSelectInput.getIsscene().intValue() == 1 && gridSelectInput.getLevel().intValue() == 1) {
						redisService5.add("UserToilet:" + userId + "_" + input.getDistrictId(), gridSelectInput.getSceneId() + "");
						redisService5.add("ToiletToUser:" + gridSelectInput.getSceneId(), userId + "");
						UserToilet userToilet = new UserToilet();
						userToilet.setDistrictId(input.getDistrictId());
						userToilet.setUserId(userId);
						userToilet.setToiletNo(gridSelectInput.getName());
						userToilet.setToiletId(gridSelectInput.getSceneId());
						userToiletService.save(userToilet);
					}
				}
			}
// 			先删除之前的
			UpdateWrapper<UserToMatter> updateWrapperUm = Wrappers.update();
			updateWrapperUm.eq("user_id", userId);
			updateWrapperUm.eq("soft_delete", 0);
			updateWrapperUm.eq("district_id", districtId);
			updateWrapperUm.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			userToMatterService.update(updateWrapperUm);
			List<IdToNameEntity> serviceEvents = input.getServiceEvents();
			if (StringUtil.isNotEmpty(serviceEvents)) {
				for (IdToNameEntity idToNameEntity : serviceEvents) {
					UserToMatter userToMatter = new UserToMatter();
					userToMatter.setUserId(userId);
					userToMatter.setCreateId(user.getId());
					userToMatter.setCreateTime(new Date());
//					@ApiModelProperty(value = "服务事项ID")
					userToMatter.setMatterId(idToNameEntity.getId());
//				    @ApiModelProperty(value = "服务事项名称")
					userToMatter.setMatterName(idToNameEntity.getName());
//				    @ApiModelProperty(value = "所属站点ID")
					userToMatter.setDistrictId(districtId);
					userToMatterService.save(userToMatter);
				}
			}
			UpdateWrapper<UserMenuDistrict> updateWrapperUmD = Wrappers.update();
			updateWrapperUmD.eq("user_id", userId);
			updateWrapperUmD.eq("district_id", districtId);
			updateWrapperUmD.eq("soft_delete", 0);
			updateWrapperUmD.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			userMenuDistrictService.update(updateWrapperUmD);
//			@ApiModelProperty(value="站点菜单")
//			private List<MenuOutInfo> districtMenu;
			List<MenuOutInfo> districtMenu = input.getDistrictMenu();
			if (StringUtil.isNotEmpty(districtMenu)) {
				for (MenuOutInfo menuOutInfo : districtMenu) {
					UserMenuDistrict userMenuDistrict = new UserMenuDistrict();
					BeanUtils.copyProperties(menuOutInfo, userMenuDistrict);
					userMenuDistrict.setDistrictId(districtId);
					userMenuDistrict.setUserId(userId);
					userMenuDistrictService.save(userMenuDistrict);
				}
			}
			UpdateWrapper<MyUserMenu> updateWrapperMm = Wrappers.update();
			updateWrapperMm.eq("user_id", userId);
			updateWrapperMm.eq("soft_delete", 0);
			updateWrapperMm.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			myUserMenuService.update(updateWrapperMm);
//			@ApiModelProperty(value="我的菜单")
//			private List<MyUserMenuOutput> myMenu;
			List<MyUserMenuOutput> myMenu = input.getMyMenu();
			if (StringUtil.isNotEmpty(myMenu)) {
				for (MyUserMenuOutput myUserMenuOutput : myMenu) {
					MyUserMenu myUserMenu = new MyUserMenu();
					BeanUtils.copyProperties(myUserMenuOutput, myUserMenu);
					MyMenu myMenuT = myMenuService.getById(myUserMenuOutput.getMyMenuId());
					myUserMenu.setUserId(userId);
					myUserMenu.setOrderby(myMenuT.getOrderby());
					myUserMenu.setParam(myMenuT.getParam());
					myUserMenu.setType(myMenuT.getType());
					myUserMenu.setUrl(myMenuT.getUrl());
					myUserMenu.setIcon(myMenuT.getIcon());
					myUserMenuService.save(myUserMenu);
				}
			}
			UserProper userProper = userProperService.getOne(new QueryWrapper<UserProper>().eq("user_id", userId).eq("soft_delete", 0).eq("district_id", districtId));
			if (input.getApprole().intValue() == 2) {
				userProper.setType(0);
			} else {
				userProper.setType(1);
			}
			userProper.setStatus(1);
			userProperService.updateById(userProper);
		} else {// 新增
			QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
			wrapper.eq("mobile", input.getMobile());
			wrapper.eq("soft_delete", 0);
			User temp = userService.getOne(wrapper);
			if (temp != null) {
				return ResultResponseBeanUtil.fail("手机号已经存在");
			}
			User userNew = new User();
			BeanUtils.copyProperties(input, userNew);
			userNew.setCreateName(user.getName());
			userNew.setCreateId(user.getId());
			userNew.setCreateTime(new Date());
			userNew.setAgentId(district.getAgentId());
			userNew.setPropertyId(district.getPropertyId());
			userNew.setEnterpriseType(2);
			userNew.setWorkStatus(1);
			if (StringUtil.isNotEmpty(input.getBirthday())) {
				userNew.setAge(DateUtil.age(DateUtil.parse(input.getBirthday(), "yyyy-MM-dd"), DateUtil.date()));
			}
			userService.save(userNew);
			UserDistrictAttendance userDistrictAttendance = userDistrictAttendanceService.getUserDistrictAttendance(input.getDistrictId(), userNew.getId());
			userDistrictAttendance.setOffTime(input.getOffTime());
			userDistrictAttendance.setOnTime(input.getOnTime());
			userDistrictAttendance.setCrossDay(0);
			if (StringUtil.isNotEmpty(userDistrictAttendance.getOffTime())) {
				String onTime = userDistrictAttendance.getOnTime();
				String offTime = userDistrictAttendance.getOffTime();
				Integer onTimeInt = Integer.parseInt(onTime.substring(0, 2));
				Integer offTimeInt = Integer.parseInt(offTime.substring(0, 2));
				if (offTimeInt > onTimeInt) {
					userDistrictAttendance.setCrossDay(0);
				} else {
					userDistrictAttendance.setCrossDay(1);
				}
				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);
			}
			userDistrictAttendanceService.updateMysqlAndReis(userDistrictAttendance);
			Long userId = userNew.getId();
			List<IdToNameEntity> skills = input.getSkills();
			if (StringUtil.isNotEmpty(skills)) {
				for (IdToNameEntity idToNameEntity : skills) {
					UserToSkill userToSkill = new UserToSkill();
					SkillManage skillManage = skillManageService.getById(idToNameEntity.getId());
					userToSkill.setUserId(userId);
					userToSkill.setColorValue(skillManage.getColorValue());
					userToSkill.setSkillId(idToNameEntity.getId());
					userToSkill.setSkillName(skillManage.getSkillName());
					userToSkill.setCreateId(user.getId());
					userToSkill.setCreateTime(new Date());
					userToSkill.setDistrictId(districtId);
					userToSkillService.save(userToSkill);
				}
			}
			List<IdToNameEntity> lables = input.getLabels();
			if (StringUtil.isNotEmpty(lables)) {
				for (IdToNameEntity idToNameEntity : lables) {
					UserToLabel userToLable = new UserToLabel();
					LabelManage labelManage = labelManageService.getById(idToNameEntity.getId());
					userToLable.setUserId(userId);
					userToLable.setColorValue(labelManage.getColorValue());
					userToLable.setLabelId(idToNameEntity.getId());
					userToLable.setLabelName(labelManage.getLabelName());
					userToLable.setCreateId(user.getId());
					userToLable.setCreateTime(new Date());
					userToLable.setDistrictId(districtId);
					userToLabelService.save(userToLable);
				}

			}
			List<IdToNameEntity> groups = input.getGroups();
			if (StringUtil.isNotEmpty(groups)) {
				for (IdToNameEntity idToNameEntity : groups) {
					WorkGroupToPrincipal workGroupToPrincipal = new WorkGroupToPrincipal();
					WorkGroup workGroup = workGroupService.getById(idToNameEntity.getId());
					workGroupToPrincipal.setCreateId(user.getId());
					workGroupToPrincipal.setCreateTime(new Date());
					workGroupToPrincipal.setCreateName(user.getName());
// 					@ApiModelProperty(value = "班组ID")
					workGroupToPrincipal.setWorkGroupId(workGroup.getId());
//					@ApiModelProperty(value = "所属班组")
					workGroupToPrincipal.setWorkGroupName(workGroup.getWorkGroupName());
//					@ApiModelProperty(value = "人员ID")
					workGroupToPrincipal.setUserId(userId);
//					@ApiModelProperty(value = "姓名")
					workGroupToPrincipal.setUserName(userNew.getName());
//					@ApiModelProperty(value = "手机号")
					workGroupToPrincipal.setMobile(userNew.getMobile());
//					@ApiModelProperty(value = "账号角色类型1:运维;2:保洁;3:富士康;4:老化;5:物业;6:代理")
					workGroupToPrincipal.setApprole(userNew.getApprole());
//				    @ApiModelProperty(value = "系统权限0:管理权限;1:普通权限")
					workGroupToPrincipal.setRoleType(userNew.getRoleType());
//					@ApiModelProperty(value = "负责人标识0:否;1:是")
					workGroupToPrincipal.setPrincipalFlag(0);
					workGroupToPrincipal.setDistrictId(districtId);
					workGroupToPrincipalService.save(workGroupToPrincipal);
				}
			}
			List<GridAndSceneInput> serviceAreas = input.getServiceAreas();
			if (StringUtil.isNotEmpty(serviceAreas)) {
				for (GridAndSceneInput gridSelectInput : serviceAreas) {
					UserToServiceArea userToServiceArea = new UserToServiceArea();
					userToServiceArea.setUserId(userId);
					userToServiceArea.setCreateId(user.getId());
					userToServiceArea.setCreateTime(new Date());
					userToServiceArea.setServiceAreaId(gridSelectInput.getGridId());
					if (gridSelectInput.getIsscene() == 1) {
						userToServiceArea.setServiceAreaId(gridSelectInput.getSceneId());
					}
//				    @ApiModelProperty(value = "服务区域")
					userToServiceArea.setServiceAreaName(gridSelectInput.getName());
//				    @ApiModelProperty(value = "服务分类0:区域;1:场景")
					userToServiceArea.setServiceType(gridSelectInput.getIsscene());
//				    @ApiModelProperty(value = "网格或场景级别-1:1级;2:2级")
					userToServiceArea.setGridScenesLevel(gridSelectInput.getLevel());
					userToServiceArea.setDistrictId(districtId);
					userToServiceAreaService.save(userToServiceArea);
					// 同步内存数据 只同步厕所属性的
					if (gridSelectInput.getIsscene().intValue() == 1 && gridSelectInput.getLevel().intValue() == 1) {
						redisService5.add("UserToilet:" + userId + "_" + input.getDistrictId(), gridSelectInput.getSceneId() + "");
						redisService5.add("ToiletToUser:" + gridSelectInput.getSceneId(), userId + "");
						UserToilet userToilet = new UserToilet();
						userToilet.setDistrictId(input.getDistrictId());
						userToilet.setUserId(userId);
						userToilet.setToiletNo(gridSelectInput.getName());
						userToilet.setToiletId(gridSelectInput.getSceneId());
						userToiletService.save(userToilet);
					}
					
				}
			}
			List<IdToNameEntity> serviceEvents = input.getServiceEvents();
			if (StringUtil.isNotEmpty(serviceEvents)) {
				for (IdToNameEntity idToNameEntity : serviceEvents) {
					UserToMatter userToMatter = new UserToMatter();
					userToMatter.setUserId(userId);
					userToMatter.setCreateId(user.getId());
					userToMatter.setCreateTime(new Date());
//					@ApiModelProperty(value = "服务事项ID")
					userToMatter.setMatterId(idToNameEntity.getId());
//				    @ApiModelProperty(value = "服务事项名称")
					userToMatter.setMatterName(idToNameEntity.getName());
//				    @ApiModelProperty(value = "所属站点ID")
					userToMatter.setDistrictId(districtId);
					userToMatterService.save(userToMatter);
				}
			}
//			@ApiModelProperty(value="站点菜单")
//			private List<MenuOutInfo> districtMenu;
			List<MenuOutInfo> districtMenu = input.getDistrictMenu();
			if (StringUtil.isNotEmpty(districtMenu)) {
				for (MenuOutInfo menuOutInfo : districtMenu) {
					UserMenuDistrict userMenuDistrict = new UserMenuDistrict();
					BeanUtils.copyProperties(menuOutInfo, userMenuDistrict);
					userMenuDistrict.setDistrictId(districtId);
					userMenuDistrict.setUserId(userId);
					userMenuDistrictService.save(userMenuDistrict);
				}
			}

//			@ApiModelProperty(value="我的菜单")
//			private List<MyUserMenuOutput> myMenu;
			List<MyUserMenuOutput> myMenu = input.getMyMenu();
			if (StringUtil.isNotEmpty(myMenu)) {
				for (MyUserMenuOutput myUserMenuOutput : myMenu) {
					MyUserMenu myUserMenu = new MyUserMenu();
					BeanUtils.copyProperties(myUserMenuOutput, myUserMenu);
					MyMenu myMenuT = myMenuService.getById(myUserMenuOutput.getMyMenuId());
					myUserMenu.setUserId(userId);
					myUserMenu.setOrderby(myMenuT.getOrderby());
					myUserMenu.setParam(myMenuT.getParam());
					myUserMenu.setType(myMenuT.getType());
					myUserMenu.setUrl(myMenuT.getUrl());
					myUserMenu.setIcon(myMenuT.getIcon());
					myUserMenuService.save(myUserMenu);
				}
			}
			// 添加一套user——propter
			UserProper userProper = new UserProper();
			BeanUtils.copyProperties(district, userProper, "id", "create_time", "modify_time");
			userProper.setUserId(userId);
			userProper.setDistrictId(districtId);
			userProper.setStatus(1);
			if (input.getApprole().intValue() == 2) {
				userProper.setType(0);
			} else {
				userProper.setType(1);
			}
			String propertyName = redisService5.get("name:Properyt:" + district.getPropertyId());
			userProper.setName(propertyName);
			userProperService.save(userProper);
		}
		return ResultResponseBeanUtil.success("操作成功");
	}

	/********
	 * 配置权限使用的用户列表
	 *
	 * @param request
	 * @param input
	 * @return
	 */
	@ApiOperation(value = "用户权限组查询")
	@ResponseBody
	@RequestMapping(value = "/userAuthorityPageList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<UserAuthorityOutput>> userAuthorityPageList(HttpServletRequest request, @RequestBody UserParamInput input) {
		User user = UserUtils.getUser(request);
		QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
		PageOutput<UserAuthorityOutput> output = new PageOutput<UserAuthorityOutput>();
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		wrapper.ne("agent_id", 0);
		// 代理
		if (user.getEnterpriseType() == 1) {
			// 总部无限制
			if (user.getAgentId() != 1 && user.getAgentId() != 17) {
				Agent curAgent = agentService.getById(user.getAgentId());
				if (curAgent.getChannelNo().equals("F")) {
					QueryWrapper<Agent> agentQueryWrapper = WrapperUtils.getWrapper(false);
					agentQueryWrapper.eq("supervisor_id", user.getAgentId());
					List<Agent> list = agentService.list(agentQueryWrapper);
					List<Long> ids = list.stream().map(p -> p.getId()).collect(Collectors.toList());
					ids.add(user.getAgentId());
					wrapper.in("agent_id", ids);
				} else {
					wrapper.eq("agent_id", user.getAgentId());

				}
			}
			// 物业
		} else if (user.getEnterpriseType() == 2) {
			if (user.getPropertyId() != null && user.getPropertyId() != 0) {
				wrapper.eq("property_id", user.getPropertyId());
			} else {
				return ResultResponseBeanUtil.success(output);
			}
		} else {
			return ResultResponseBeanUtil.success(output);
		}
		Page<User> pageList = new Page<User>(input.getPage(), input.getRows());
		List<User> userList = userService.page(pageList, wrapper).getRecords();
		List<UserAuthorityOutput> userOutputs = new ArrayList<>();
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			UserAuthorityOutput userOutput = new UserAuthorityOutput();
			User next = iterator.next();
			BeanUtils.copyProperties(next, userOutput);

			String agentName = redisService5.get("name:Agent:" + next.getAgentId());
			userOutput.setAgentName(agentName);
			String propertyname = redisService5.get("name:Properyt:" + next.getPropertyId());
			userOutput.setPropertyName(propertyname);

			// 物业平台
			String authorityName = redisService5.get("name:PropertyAuthority:" + next.getPropertyAuthorityId());
			userOutput.setAuthorityName(authorityName);
			User createUser = userService.getById(next.getCreateId());
			if (createUser != null) {
				userOutput.setCreateName(createUser.getName());

			} else {
				userOutput.setCreateName("未知");
			}
			userOutputs.add(userOutput);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(userOutputs);
		return ResultResponseBeanUtil.success(output);
	}

	@ApiOperation(value = "班组人员选择列表")
	@ResponseBody
	@RequestMapping(value = "/userSelectList", method = RequestMethod.POST)
	public BaseOutput<PageOutput<UserSelectOutput>> userSelectList(HttpServletRequest request, @RequestBody UserPageInput input) {
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		PageOutput<UserSelectOutput> output = new PageOutput<UserSelectOutput>();
		QueryWrapper<UserProper> wrapperUP = WrapperUtils.getWrapper(false);
		wrapperUP.eq("district_id", districtId);
		wrapperUP.in("type", 0, 1);// 保洁和物业
		List<UserProper> userPropers = userProperService.list(wrapperUP);
		if (userPropers == null || userPropers.size() == 0) {
			return ResultResponseBeanUtil.success(output);
		}
		Set<Long> userIds = userPropers.stream().map(userProper -> userProper.getUserId()).collect(Collectors.toSet());
		input.setDistrictId(null);
		QueryWrapper<User> wrapper = WrapperUtils.getWrapper(false);
		wrapper.in("id", userIds);
		wrapper = WrapperUtils.beanToWrapper(wrapper, input);
		Page<User> pageList = new Page<User>(input.getPage(), input.getRows());
		List<User> userList = userService.page(pageList, wrapper).getRecords();
		List<UserSelectOutput> selectOutputs = new ArrayList<UserSelectOutput>();
		for (User user : userList) {
			UserSelectOutput UserSelectOutput = new UserSelectOutput();
			BeanUtils.copyProperties(user, UserSelectOutput);
			selectOutputs.add(UserSelectOutput);
		}
		output.setPage(pageList.getCurrent());
		output.setRecords(pageList.getTotal());
		output.setTotal(pageList.getPages());
		output.setRows(selectOutputs);
		return ResultResponseBeanUtil.success(output);
	}

	@Autowired
	private UserMenuDistrictService userMenuDistrictService;
	@Autowired
	private MyMenuService myMenuService;
	@Autowired
	private AppMenuService appMenuService;
	@Autowired
	private MyUserMenuService myUserMenuService;

	@ApiOperation(value = "获取站点权限的基本菜单")
	@ResponseBody
	@RequestMapping(value = "/getBaseAppMenu", method = RequestMethod.GET)
	public BaseOutput<List<MenuOutInfo>> getBaseAppMenu(HttpServletRequest request, @RequestParam(name = "districtId") Long districtId) {
		User user = UserUtils.getUser(request);
		List<MenuOutInfo> menuList = new ArrayList<>();
		if (user.getApprole() == 5) {
			// 先查当前管理员管理的站点
			Map<String, Object> params = new HashMap<>();
			params.put("user_id", user.getId());
			params.put("district_id", districtId);
			params.put("soft_delete", 0);
			params.put("state", 1);// 当前登录人分配的
			List<UserMenuDistrict> appMenus = userMenuDistrictService.listByMap(params);
			// 根据当前站点查询菜单
			for (UserMenuDistrict appMenu : appMenus) {
				MenuOutInfo menuOutInfo = new MenuOutInfo();
				menuOutInfo.setAppMenuId(appMenu.getAppMenuId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);// 未选中
				menuList.add(menuOutInfo);
			}
		} else {

			// 先查当前管理员管理的站点
			Map<String, Object> params = new HashMap<>();
			params.put("type", 0);
			params.put("soft_delete", 0);
			List<AppMenu> appMenus = appMenuService.listByMap(params);
			// 根据当前站点查询菜单
			for (AppMenu appMenu : appMenus) {
				MenuOutInfo menuOutInfo = new MenuOutInfo();
				menuOutInfo.setAppMenuId(appMenu.getId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);// 未选中
				menuList.add(menuOutInfo);
			}
		}
		return ResultResponseBeanUtil.success(menuList);
	}

	@ApiOperation(value = "获取某个站点权限的配置的菜单")
	@ResponseBody
	@RequestMapping(value = "/getDistrictAppMenu", method = RequestMethod.POST)
	public BaseOutput<List<MenuOutInfo>> getDistrictAppMenu(HttpServletRequest request, @RequestBody UserDistrictMenuInput input) {
		User user = UserUtils.getUser(request);
		// 先查当前修改人管理的站点权限
		Map<String, Object> params = new HashMap<>();
		params.put("user_id", input.getUserId());
		params.put("district_id", input.getDistrictId());
		params.put("soft_delete", 0);
		List<UserMenuDistrict> appMenus = userMenuDistrictService.listByMap(params);
		List<MenuOutInfo> menuList = new ArrayList<>();
		List<Long> menuIds = new ArrayList<Long>();
		// 根据当前站点查询菜单
		for (UserMenuDistrict appMenu : appMenus) {
			menuIds.add(appMenu.getAppMenuId());
			MenuOutInfo menuOutInfo = new MenuOutInfo();
			menuOutInfo.setAppMenuId(appMenu.getAppMenuId());
			menuOutInfo.setName(appMenu.getName());
			menuOutInfo.setState(appMenu.getState());
			menuList.add(menuOutInfo);
		}
		if (user.getApprole() == 5) {
			params.put("user_id", user.getId());
			params.put("state", 1);
			appMenus = userMenuDistrictService.listByMap(params);
			// 根据当前登录人站点查询菜单
			for (UserMenuDistrict appMenu : appMenus) {
				if (menuIds.contains(appMenu.getAppMenuId())) {
					continue;
				}
				MenuOutInfo menuOutInfo = new MenuOutInfo();
				menuOutInfo.setAppMenuId(appMenu.getAppMenuId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);
				menuList.add(menuOutInfo);
			}
		} else {
			Map<String, Object> params1 = new HashMap<>();
			params1.put("type", 0);
			params1.put("soft_delete", 0);
			List<AppMenu> appMenus1 = appMenuService.listByMap(params1);
			// 根据当前登录人站点查询菜单
			for (AppMenu appMenu : appMenus1) {
				if (menuIds.contains(appMenu.getId())) {
					continue;
				}
				MenuOutInfo menuOutInfo = new MenuOutInfo();
				menuOutInfo.setAppMenuId(appMenu.getId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);
				menuList.add(menuOutInfo);
			}
		}
		return ResultResponseBeanUtil.success(menuList);
	}

	@ApiOperation(value = "获取我的基本菜单")
	@ResponseBody
	@RequestMapping(value = "/getMyBaseMenu", method = RequestMethod.GET)
	public BaseOutput<List<MyUserMenuOutput>> getMyBaseMenu(HttpServletRequest request) {
		User user = UserUtils.getUser(request);
		List<MyUserMenuOutput> menuList = new ArrayList<MyUserMenuOutput>();
		if (user.getApprole() == 5) {
			// 先查当前管理员管理的站点
			Map<String, Object> params = new HashMap<>();
			params.put("user_id", user.getId());
			params.put("soft_delete", 0);
			List<MyUserMenu> myUserMenus = myUserMenuService.listByMap(params);
			// 根据当前站点查询菜单
			for (MyUserMenu appMenu : myUserMenus) {
				MyUserMenuOutput menuOutInfo = new MyUserMenuOutput();
				menuOutInfo.setMyMenuId(appMenu.getMyMenuId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);// 未选中
				menuList.add(menuOutInfo);
			}
		} else {
			// 先查当前管理员管理的站点
			Map<String, Object> params = new HashMap<>();
			params.put("property_default", 1);
			params.put("soft_delete", 0);
			List<MyMenu> myUserMenus = myMenuService.listByMap(params);
			// 根据当前站点查询菜单
			for (MyMenu appMenu : myUserMenus) {
				MyUserMenuOutput menuOutInfo = new MyUserMenuOutput();
				menuOutInfo.setMyMenuId(appMenu.getId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);// 未选中
				menuList.add(menuOutInfo);
			}
		}
		return ResultResponseBeanUtil.success(menuList);
	}

	@ApiOperation(value = "获取我的菜单")
	@ResponseBody
	@RequestMapping(value = "/getMyMenu", method = RequestMethod.GET)
	public BaseOutput<List<MyUserMenuOutput>> getMyMenu(HttpServletRequest request, @RequestParam(name = "userId") Long userId) {
		User user = UserUtils.getUser(request);
		// 先查当前修改人管理的站点权限
		Map<String, Object> params = new HashMap<>();
		params.put("user_id", userId);
		params.put("soft_delete", 0);
		List<MyUserMenu> myUserMenus = myUserMenuService.listByMap(params);
		List<MyUserMenuOutput> menuList = new ArrayList<MyUserMenuOutput>();
		List<Long> menuIds = new ArrayList<Long>();
		// 根据当前站点查询菜单
		for (MyUserMenu appMenu : myUserMenus) {
			MyUserMenuOutput menuOutInfo = new MyUserMenuOutput();
			menuIds.add(appMenu.getMyMenuId());
			menuOutInfo.setMyMenuId(appMenu.getMyMenuId());
			menuOutInfo.setName(appMenu.getName());
			menuOutInfo.setState(1);//
			menuList.add(menuOutInfo);
		}
		if (user.getApprole() == 5) {
			params.put("user_id", user.getId());
			myUserMenus = myUserMenuService.listByMap(params);
			// 根据当前登录人站点查询菜单
			for (MyUserMenu appMenu : myUserMenus) {
				if (menuIds.contains(appMenu.getMyMenuId())) {
					continue;
				}
				MyUserMenuOutput menuOutInfo = new MyUserMenuOutput();
				menuOutInfo.setMyMenuId(appMenu.getMyMenuId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);
				menuList.add(menuOutInfo);
			}
		} else {

			Map<String, Object> params1 = new HashMap<>();
			params1.put("property_default", 1);
			params1.put("soft_delete", 0);
			List<MyMenu> myMenus = myMenuService.listByMap(params1);
			// 根据当前登录人站点查询菜单
			for (MyMenu appMenu : myMenus) {
				if (menuIds.contains(appMenu.getId())) {
					continue;
				}
				MyUserMenuOutput menuOutInfo = new MyUserMenuOutput();
				menuOutInfo.setMyMenuId(appMenu.getId());
				menuOutInfo.setName(appMenu.getName());
				menuOutInfo.setState(0);
				menuList.add(menuOutInfo);
			}
		}
		return ResultResponseBeanUtil.success(menuList);
	}

	@ApiOperation(value = "删除人员")
	@ResponseBody
	@AvoidRepeatSubmit
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public BaseOutput<String> delete(HttpServletRequest request, @RequestBody DistrictIdIAndUserIdnput input) {
		User user = UserUtils.getUser(request);
		Long districtId = input.getDistrictId();
		if (districtId == null || districtId == 0) {
			return ResultResponseBeanUtil.fail("请选择站点");
		}
		District district = districtService.getById(districtId);
		if (district == null) {
			return ResultResponseBeanUtil.fail("选择的站点不存在");
		}
		User userNew = userService.getById(input.getUserId());
		if (userNew == null) {
			return ResultResponseBeanUtil.fail("该用户不存在,请确认");
		}
		Long userId = input.getUserId();
		// 技能
		UpdateWrapper<UserToSkill> updateWrapperSk = Wrappers.update();
		updateWrapperSk.eq("user_id", userId);
		updateWrapperSk.eq("district_id", districtId);
		updateWrapperSk.eq("soft_delete", 0);
		updateWrapperSk.setSql("soft_delete=1" + ",modify_time= NOW()");
		userToSkillService.update(updateWrapperSk);
		// 标签
		UpdateWrapper<UserToLabel> updateWrapperLa = Wrappers.update();
		updateWrapperLa.eq("user_id", userId);
		updateWrapperLa.eq("soft_delete", 0);
		updateWrapperLa.eq("district_id", districtId);
		updateWrapperLa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		userToLabelService.update(updateWrapperLa);
		// 工作组
		UpdateWrapper<WorkGroupToPrincipal> updateWrapperPr = Wrappers.update();
		updateWrapperPr.eq("user_id", userId);
		updateWrapperPr.eq("soft_delete", 0);
		updateWrapperPr.eq("district_id", districtId);
		updateWrapperPr.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		workGroupToPrincipalService.update(updateWrapperPr);
//			服务区域
		UpdateWrapper<UserToServiceArea> updateWrapperUa = Wrappers.update();
		updateWrapperUa.eq("user_id", userId);
		updateWrapperUa.eq("soft_delete", 0);
		updateWrapperUa.eq("district_id", districtId);
		updateWrapperUa.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		userToServiceAreaService.update(updateWrapperUa);
		// 负责站点
		UpdateWrapper<UserProper> updateWrapperUp = Wrappers.update();
		updateWrapperUp.eq("user_id", userId);
		updateWrapperUp.eq("soft_delete", 0);
		updateWrapperUp.eq("district_id", districtId);
		updateWrapperUp.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		userProperService.update(updateWrapperUp);
		// 菜单
		UpdateWrapper<UserMenuDistrict> updateWrapperUmD = Wrappers.update();
		updateWrapperUmD.eq("user_id", userId);
		updateWrapperUmD.eq("district_id", districtId);
		updateWrapperUmD.eq("soft_delete", 0);
		updateWrapperUmD.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
		userMenuDistrictService.update(updateWrapperUmD);
		QueryWrapper<UserProper> queryWrapperUp = Wrappers.query();
		queryWrapperUp.eq("user_id", userId);
		queryWrapperUp.eq("soft_delete", 0);
		int count = userProperService.count(queryWrapperUp);
		if (count == 0) {// 没有站点了就都删掉
			// 我的
			UpdateWrapper<MyUserMenu> updateWrapperMm = Wrappers.update();
			updateWrapperMm.eq("user_id", userId);
			updateWrapperMm.eq("soft_delete", 0);
			updateWrapperMm.setSql("soft_delete=1" + ",modify_time= NOW(),modify_id=" + user.getId());
			myUserMenuService.update(updateWrapperMm);
			userNew.setSoftDelete(1);
			userService.updateById(userNew);
		}
		QueryWrapper<UserToilet> userToiletWrapper = WrapperUtils.getWrapper(false);
		userToiletWrapper.eq("user_id", userId);
		userToiletWrapper.eq("soft_delete", 0);
		userToiletWrapper.eq("district_id", districtId);
		List<UserToilet> userToilets = userToiletService.list(userToiletWrapper);
		for (UserToilet userToilet : userToilets) {
			userToilet.setSoftDelete(1);
			userToilet.setModifyId(user.getId());
			userToilet.setModifyTime(new Date());
			userToiletService.updateById(userToilet);
			redisService5.setRemove("ToiletToUser:" + userToilet.getToiletId(), userId + "");
		}
		redisService5.remove("UserToilet:" + userId + "_" + input.getDistrictId());
		return ResultResponseBeanUtil.success("操作成功");
	}
}
