/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.person.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.DictCodeConstant;
import org.springblade.community.entity.*;
import org.springblade.community.feign.*;
import org.springblade.community.vo.*;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.enterprise.vo.ChartDataVO;
import org.springblade.enterprise.vo.EnterpriseBizTypePieDataVO;
import org.springblade.estate.feign.IUserAccessPermissionsClient;
import org.springblade.person.entity.*;
import org.springblade.person.service.*;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.person.wrapper.HouseUserWrapper;
import org.springblade.system.entity.DictBiz;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.feign.IDictBizClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import org.springblade.core.boot.ctrl.BladeController;

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

/**
 * 控制器
 *
 * @author BladeX
 * @since 2021-04-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/houseuser")
@Api(value = "", tags = "接口")
public class HouseUserController extends BladeController {

	private final HouseUserService houseUserService;
	private final IElderlyPeopleService elderlyPeopleService;
	private final IKeyPeopleService keyPeopleService;
	private final IDisablerService disablerService;
	private IAgencyClient agencyClient;
	private IResidentialClient residentialClient;
	private IBuildingClient buildingClient;
	private IRoomClient roomClient;
	private IUserService<HouseUser> userService;
	private final IDrugService drugService;
	private final IAdolescentService adolescentService;
	private IAidsService aidsService;
	private ICorrectionalStaffService correctionalStaffService;
	private IEstablishFilecardService establishFilecardService;
	private IFertileWomanService fertileWomanService;
	private IPrisonerService prisonerService;
	private IPsychiatricService psychiatricService;
	private IVeteransService veteransService;
	private IAllowancesPeopleService allowancesPeopleService;
	private final IOrgPositionClient orgPositionClient;
	private final IConfClient confClient;
	private final IUserAccessPermissionsClient userAccessPermissionsClient;
	private final IDictBizClient dictBizClient;


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入basicInfo")
	public R<HouseUserVO> detail(HouseUser houseUser) {
		HouseUser detail = houseUserService.getOne(Condition.getQueryWrapper(houseUser));
		return R.data(HouseUserWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入basicInfo")
	public R<IPage<HouseUserVO>> list(@RequestParam Map<String, Object> houseUser, Query query, BladeUser bladeUser) {
//		Integer auditStatus = null;
//		Long residentialId = null;
//		if(basicInfo.get("auditStatus") != null){
//			auditStatus = Integer.parseInt(String.valueOf(basicInfo.get("auditStatus")));
//			basicInfo.remove("auditStatus");
//		}
//		if(basicInfo.get("residentialId") != null){
//			residentialId = Long.parseLong(String.valueOf(basicInfo.get("residentialId")));
//			basicInfo.remove("residentialId");
//		}
//		LambdaQueryWrapper<HouseUser> wrapper = new QueryWrapperUtil<HouseUser>().getBasicQueryWrapperByMap(HouseUser::getOrgPosition, basicInfo, new HouseUser(), bladeUser, orgPositionClient);
		QueryWrapper<HouseUser> queryWrapper = Condition.getQueryWrapper(houseUser, HouseUser.class);
		queryWrapper.lambda().orderByDesc(HouseUser::getCreateTime);
		IPage<HouseUser> pages = houseUserService.page(Condition.getPage(query), queryWrapper);
		return R.data(HouseUserWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入basicInfo")
	public R<IPage<HouseUserVO>> page(HouseUserVO basicInfo, Query query) {
		IPage<HouseUserVO> pages = houseUserService.selectBasicInfoPage(Condition.getPage(query), basicInfo);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入basicInfo")
	public R save(@Valid @RequestBody HouseUser houseUser) {
		String faceUrl = houseUser.getFaceUrl();
		if (StrUtil.isNotBlank(faceUrl)) {
			houseUser.setFaceUrl(confClient.removePrefix(houseUser.getFaceUrl()));
		}
		return R.status(houseUserService.save(houseUser));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入basicInfo")
	public R update(@Valid @RequestBody HouseUser houseUser) {
		return R.status(houseUserService.updateById(houseUser));
	}


	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入houseUser")
	public R submit(@Valid @RequestBody HouseUser houseUser) {

		String orgPositiontemp = null;
		Residential residential = new Residential();
		residential.setId(houseUser.getResidentialId());
		ResidentialVO residentialVO = residentialClient.detail(residential);
		Assert.notNull(residentialVO, "选择的小区不存在");

		Agency agency = agencyClient.getById(residentialVO.getAgencyId());
		Assert.notNull(agency, "园区不存在");

		houseUser.setAgencyId(agency.getId());
		houseUser.setAgencyName(agency.getName());
		houseUser.setResidentialName(residentialVO.getName());

		if (houseUser.getBuildingId() != null) {
			Building building = new Building();
			building.setId(houseUser.getBuildingId());
			BuildingVO buildingVO = buildingClient.detail(building);
			Assert.notNull(buildingVO, "选择的楼栋不存在");
			houseUser.setBuildingName(buildingVO.getName());
		}
		if (houseUser.getRoomId() != null) {
			Room room = new Room();
			room.setId(houseUser.getRoomId());
			RoomVO roomVO = roomClient.detail(room);
			Assert.notNull(roomVO, "选择的房间不存在");

			houseUser.setFloorId(roomVO.getFloorId());
			houseUser.setFloorName(roomVO.getFloorName());
			houseUser.setRoomName(roomVO.getName());
			//添加房间Orgposition
			orgPositiontemp = roomVO.getOrgPosition() + "/" + houseUser.getId();
			houseUser.setOrgPosition(roomVO.getOrgPosition() + "/" + houseUser.getId());
		}
		houseUser.setFaceUrl(confClient.removePrefix(houseUser.getFaceUrl()));
		boolean saveOrUpdate = houseUserService.saveOrUpdate(houseUser);

		if (houseUser.getTags().contains("高龄老人")) {
			//判断原来是否存在
			ElderlyPeople ifelderlyPeople = elderlyPeopleService.getBaseMapper().selectOne(new QueryWrapper<>(new ElderlyPeople()).eq("parent_id", houseUser.getId()));
			if (ifelderlyPeople == null) {//不存在则新增
				ElderlyPeople elderlyPeople = new ElderlyPeople();
				elderlyPeople.setParentId(houseUser.getId());
				elderlyPeople.setName(houseUser.getName());
				elderlyPeople.setOrgPosition(orgPositiontemp);
				elderlyPeopleService.save(elderlyPeople);
			}
		} else {
			//修改时取消了该标签则删除
			ElderlyPeople ifelderlyPeople = elderlyPeopleService.getBaseMapper().selectOne(new QueryWrapper<>(new ElderlyPeople()).eq("parent_id", houseUser.getId()));
			if (ifelderlyPeople != null) {//存在则逻辑删除
				elderlyPeopleService.getBaseMapper().delete(new QueryWrapper<ElderlyPeople>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("残障人士")) {
			//判断原来是否存在
			Disabler ifdisabler = disablerService.getBaseMapper().selectOne(new QueryWrapper<>(new Disabler()).eq("parent_id", houseUser.getId()));
			if (ifdisabler == null) {//不存在则新增
				Disabler disabler = new Disabler();
				disabler.setParentId(houseUser.getId());
				disabler.setName(houseUser.getName());
				disabler.setOrgPosition(orgPositiontemp);
				disablerService.save(disabler);
			}
		} else {
			//修改时取消了该标签则删除
			Disabler ifdisabler = disablerService.getBaseMapper().selectOne(new QueryWrapper<>(new Disabler()).eq("parent_id", houseUser.getId()));
			if (ifdisabler != null) {//存在则逻辑删除
				disablerService.getBaseMapper().delete(new QueryWrapper<Disabler>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("吸毒人员")) {
			//判断原来是否存在
			Drug ifdrug = drugService.getBaseMapper().selectOne(new QueryWrapper<>(new Drug()).eq("parent_id", houseUser.getId()));
			if (ifdrug == null) {//不存在则新增
				Drug drug = new Drug();
				drug.setParentId(houseUser.getId());
				drug.setName(houseUser.getName());
				drug.setOrgPosition(orgPositiontemp);
				drugService.save(drug);
			}
		} else {
			//修改时取消了该标签则删除
			Drug ifdrug = drugService.getBaseMapper().selectOne(new QueryWrapper<>(new Drug()).eq("parent_id", houseUser.getId()));
			if (ifdrug != null) {//存在则逻辑删除
				drugService.getBaseMapper().delete(new QueryWrapper<Drug>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("重点青少年")) {
			//判断原来是否存在
			Adolescent ifadolescent = adolescentService.getBaseMapper().selectOne(new QueryWrapper<>(new Adolescent()).eq("parent_id", houseUser.getId()));
			if (ifadolescent == null) {//不存在则新增
				Adolescent adolescent = new Adolescent();
				adolescent.setParentId(houseUser.getId());
				adolescent.setName(houseUser.getName());
				adolescent.setOrgPosition(orgPositiontemp);
				adolescentService.save(adolescent);
			}
		} else {
			//修改时取消了该标签则删除
			CorrectionalStaff ifcorrectionalStaff = correctionalStaffService.getBaseMapper().selectOne(new QueryWrapper<>(new CorrectionalStaff()).eq("parent_id", houseUser.getId()));
			if (ifcorrectionalStaff != null) {//存在则逻辑删除
				correctionalStaffService.getBaseMapper().delete(new QueryWrapper<CorrectionalStaff>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("矫正人员")) {
			//判断原来是否存在
			CorrectionalStaff ifcorrectionalStaff = correctionalStaffService.getBaseMapper().selectOne(new QueryWrapper<>(new CorrectionalStaff()).eq("parent_id", houseUser.getId()));
			if (ifcorrectionalStaff == null) {//不存在则新增
				CorrectionalStaff correctionalStaff = new CorrectionalStaff();
				correctionalStaff.setParentId(houseUser.getId());
				correctionalStaff.setName(houseUser.getName());
				correctionalStaff.setOrgPosition(orgPositiontemp);
				correctionalStaffService.save(correctionalStaff);
			}
		} else {
			//修改时取消了该标签则删除
			CorrectionalStaff ifcorrectionalStaff = correctionalStaffService.getBaseMapper().selectOne(new QueryWrapper<>(new CorrectionalStaff()).eq("parent_id", houseUser.getId()));
			if (ifcorrectionalStaff != null) {//存在则逻辑删除
				correctionalStaffService.getBaseMapper().delete(new QueryWrapper<CorrectionalStaff>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("建档立卡")) {
			//判断原来是否存在
			EstablishFilecard ifestablishFilecard = establishFilecardService.getBaseMapper().selectOne(new QueryWrapper<>(new EstablishFilecard()).eq("parent_id", houseUser.getId()));
			if (ifestablishFilecard == null) {//不存在则新增
				EstablishFilecard establishFilecard = new EstablishFilecard();
				establishFilecard.setParentId(houseUser.getId());
				establishFilecard.setName(houseUser.getName());
				establishFilecard.setOrgPosition(orgPositiontemp);
				establishFilecardService.save(establishFilecard);
			}
		} else {
			//修改时取消了该标签则删除
			EstablishFilecard ifestablishFilecard = establishFilecardService.getBaseMapper().selectOne(new QueryWrapper<>(new EstablishFilecard()).eq("parent_id", houseUser.getId()));
			if (ifestablishFilecard != null) {//存在则逻辑删除
				establishFilecardService.getBaseMapper().delete(new QueryWrapper<EstablishFilecard>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("育龄妇女")) {
			//判断原来是否存在
			FertileWoman iffertileWoman = fertileWomanService.getBaseMapper().selectOne(new QueryWrapper<>(new FertileWoman()).eq("parent_id", houseUser.getId()));
			if (iffertileWoman == null) {//不存在则新增
				FertileWoman fertileWoman = new FertileWoman();
				fertileWoman.setParentId(houseUser.getId());
				fertileWoman.setName(houseUser.getName());
				fertileWoman.setOrgPosition(orgPositiontemp);
				fertileWomanService.save(fertileWoman);
			}
		} else {
			//修改时取消了该标签则删除
			FertileWoman iffertileWoman = fertileWomanService.getBaseMapper().selectOne(new QueryWrapper<>(new FertileWoman()).eq("parent_id", houseUser.getId()));
			if (iffertileWoman != null) {//存在则逻辑删除
				fertileWomanService.getBaseMapper().delete(new QueryWrapper<FertileWoman>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("刑释人员")) {
			//判断原来是否存在
			Prisoner ifprisoner = prisonerService.getBaseMapper().selectOne(new QueryWrapper<>(new Prisoner()).eq("parent_id", houseUser.getId()));
			if (ifprisoner == null) {//不存在则新增
				Prisoner prisoner = new Prisoner();
				prisoner.setParentId(houseUser.getId());
				prisoner.setName(houseUser.getName());
				prisoner.setOrgPosition(orgPositiontemp);
				prisonerService.save(prisoner);
			}
		} else {
			//修改时取消了该标签则删除
			Prisoner ifprisoner = prisonerService.getBaseMapper().selectOne(new QueryWrapper<>(new Prisoner()).eq("parent_id", houseUser.getId()));
			if (ifprisoner != null) {//存在则逻辑删除
				prisonerService.getBaseMapper().delete(new QueryWrapper<Prisoner>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("精神病人")) {
			//判断原来是否存在
			Psychiatric ifpsychiatric = psychiatricService.getBaseMapper().selectOne(new QueryWrapper<>(new Psychiatric()).eq("parent_id", houseUser.getId()));
			if (ifpsychiatric == null) {//不存在则新增
				Psychiatric psychiatric = new Psychiatric();
				psychiatric.setParentId(houseUser.getId());
				psychiatric.setName(houseUser.getName());
				psychiatric.setOrgPosition(orgPositiontemp);
				psychiatricService.save(psychiatric);
			}
		} else {
			//修改时取消了该标签则删除
			Psychiatric ifpsychiatric = psychiatricService.getBaseMapper().selectOne(new QueryWrapper<>(new Psychiatric()).eq("parent_id", houseUser.getId()));
			if (ifpsychiatric != null) {//存在则逻辑删除
				psychiatricService.getBaseMapper().delete(new QueryWrapper<Psychiatric>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("退伍军人")) {
			//判断原来是否存在
			Veterans ifveterans = veteransService.getBaseMapper().selectOne(new QueryWrapper<>(new Veterans()).eq("parent_id", houseUser.getId()));
			if (ifveterans == null) {//不存在则新增
				Veterans veterans = new Veterans();
				veterans.setParentId(houseUser.getId());
				veterans.setName(houseUser.getName());
				veterans.setOrgPosition(orgPositiontemp);
				veteransService.save(veterans);
			}
		} else {
			//修改时取消了该标签则删除
			Veterans ifveterans = veteransService.getBaseMapper().selectOne(new QueryWrapper<>(new Veterans()).eq("parent_id", houseUser.getId()));
			if (ifveterans != null) {//存在则逻辑删除
				veteransService.getBaseMapper().delete(new QueryWrapper<Veterans>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("艾滋病人")) {
			//判断原来是否存在
			Aids ifaids = aidsService.getBaseMapper().selectOne(new QueryWrapper<>(new Aids()).eq("parent_id", houseUser.getId()));
			if (ifaids == null) {//不存在则新增
				Aids aids = new Aids();
				aids.setParentId(houseUser.getId());
				aids.setName(houseUser.getName());
				aids.setOrgPosition(orgPositiontemp);
				aidsService.save(aids);
			}
		} else {
			//修改时取消了该标签则删除
			Aids ifaids = aidsService.getBaseMapper().selectOne(new QueryWrapper<>(new Aids()).eq("parent_id", houseUser.getId()));
			if (ifaids != null) {//存在则逻辑删除
				aidsService.getBaseMapper().delete(new QueryWrapper<Aids>().eq("parent_id", houseUser.getId()));
			}
		}

		if (houseUser.getTags().contains("低保人员")) {
			//判断原来是否存在
			AllowancesPeople ifallowancesPeople = allowancesPeopleService.getBaseMapper().selectOne(new QueryWrapper<>(new AllowancesPeople()).eq("parent_id", houseUser.getId()));
			if (ifallowancesPeople == null) {//不存在则新增
				AllowancesPeople allowancesPeople = new AllowancesPeople();
				allowancesPeople.setParentId(houseUser.getId());
				allowancesPeople.setName(houseUser.getName());
				allowancesPeople.setOrgPosition(orgPositiontemp);
				allowancesPeopleService.save(allowancesPeople);
			}
		} else {
			//修改时取消了该标签则删除
			AllowancesPeople ifallowancesPeople = allowancesPeopleService.getBaseMapper().selectOne(new QueryWrapper<>(new AllowancesPeople()).eq("parent_id", houseUser.getId()));
			if (ifallowancesPeople != null) {//存在则逻辑删除
				allowancesPeopleService.getBaseMapper().delete(new QueryWrapper<AllowancesPeople>().eq("parent_id", houseUser.getId()));
			}
		}
		if (saveOrUpdate) {
			//下发人脸
			if (StringUtil.isNotBlank(houseUser.getFaceUrl())) {
				houseUser.setFaceUrl(confClient.addPrefix(houseUser.getFaceUrl()));
				R result = userService.pushAddFace(houseUser, new HashMap<>());
				if (result.isSuccess()) {
					return R.success("保存住户成功");
				} else {
					return R.fail("保存住户成功，人脸下发失败");
				}
			} else {
				return R.success("保存住户成功");
			}
		} else {
			return R.fail("保存住户失败");
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/delFace")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R delFace(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idsList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		;
		//批量关联删除
		List<HouseUser> houseUserList = null;
		if (idsList != null && idsList.size() > 0) {
			houseUserList = houseUserService.listByIds(idsList);
		}
		//下发删除人脸指令
		if (houseUserList != null && houseUserList.size() > 0) {
			return userService.pushDelFace(houseUserList, new HashMap<>());
		} else {
			return R.status(true);
		}
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {

		List<Long> idsList = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		;
		//批量关联删除
		List<HouseUser> houseUserList = null;
		if (idsList != null && idsList.size() > 0) {
			houseUserList = houseUserService.listByIds(idsList);
		}
		for (Long id : idsList) {
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("parent_id", id);
			disablerService.getBaseMapper().delete(queryWrapper);
			keyPeopleService.getBaseMapper().delete(queryWrapper);
			elderlyPeopleService.getBaseMapper().delete(queryWrapper);
			adolescentService.getBaseMapper().delete(queryWrapper);
			aidsService.getBaseMapper().delete(queryWrapper);
			correctionalStaffService.getBaseMapper().delete(queryWrapper);
			disablerService.getBaseMapper().delete(queryWrapper);
			drugService.getBaseMapper().delete(queryWrapper);
			elderlyPeopleService.getBaseMapper().delete(queryWrapper);
			establishFilecardService.getBaseMapper().delete(queryWrapper);
			prisonerService.getBaseMapper().delete(queryWrapper);
			psychiatricService.getBaseMapper().delete(queryWrapper);
			veteransService.getBaseMapper().delete(queryWrapper);
		}
		boolean b = houseUserService.deleteLogic(Func.toLongList(ids));
		if (b) {
			//下发删除人脸指令
			if (houseUserList != null && houseUserList.size() > 0) {
				return userService.pushDelFace(houseUserList, new HashMap<>());
			} else {
				return R.status(true);
			}
		} else {
			return R.status(false);
		}
	}

	/**
	 * 入场记录初始化，关联新的小区和图片去除前缀
	 */
	@PostMapping("/initData")
	@ApiOperationSupport(order = 8)
	public R initData() {
		long beginTime = System.currentTimeMillis();
		List<HouseUser> houseUsers = this.houseUserService.getBaseMapper().selectList(new QueryWrapper<>(new HouseUser()));
		houseUsers.forEach(houseUser -> {
			if (houseUser.getResidentialId() != null) {
				Residential residential = residentialClient.getById(houseUser.getResidentialId());
				if (residential != null) {
					houseUser.setAgencyId(residential.getAgencyId());
					houseUser.setAgencyName(residential.getAgencyName());
				}
			}

			houseUserService.updateById(houseUser);

		});
		long endTime = System.currentTimeMillis();
		return R.data("耗时：" + (endTime - beginTime) / 1000 + "秒");
	}

	/**
	 * 【web端】一联通-人脸权限-常住人员下发列表
	 * 获取常住人员，下发列表
	 * type:0待下发,1已下发
	 */
	@GetMapping("/getHouseUserXFList")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "常住人员下发列表")
	public R getHouseUserXFList(Query query, @RequestParam Integer type) {
		List<Long> userIdList = userAccessPermissionsClient.getUserIdsByUserType(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue());
		LambdaQueryWrapper<HouseUser> queryWrapper = null;
		if (type.equals(0)) {
			//常住人员待下发列表
			queryWrapper = Condition.getQueryWrapper(new HouseUser()).lambda().eq(HouseUser::getAuditStatus, CommonConstant.UserAuditStatus.pass.getValue()).notIn(CollUtil.isNotEmpty(userIdList), HouseUser::getId, userIdList);
		} else if (type.equals(1)) {
			//常驻人员已下发列表
			queryWrapper = Condition.getQueryWrapper(new HouseUser()).lambda().eq(HouseUser::getAuditStatus, CommonConstant.UserAuditStatus.pass.getValue()).in(CollUtil.isNotEmpty(userIdList), HouseUser::getId, userIdList);
		}
		IPage<HouseUser> houseUserIPage = houseUserService.page(Condition.getPage(query), queryWrapper);
		return R.data(houseUserIPage);
	}


	/**
	 * 剧名用户类型统计【web端智能运营中心】
	 */
	@GetMapping("/userType")
	@ApiOperationSupport(order = 1)
	public R bizType() {
		String OTHER_BIZ_TYPE = "其他";
		List<DictBiz> dictList = dictBizClient.getList(DictCodeConstant.HOUSEHOLD_TYPE).getData();
		Assert.isTrue(CollUtil.isNotEmpty(dictList), DictCodeConstant.DICT_LIST_IS_EMPTY);
		List<HouseUser> houseUsers = houseUserService.list(Condition.getQueryWrapper(new HouseUser()).lambda().select(HouseUser::getId, HouseUser::getType));
		long otherCount =houseUsers.size() - houseUsers.stream().filter(item -> Objects.isNull(item.getType())).count();
		Map<Integer, List<HouseUser>> collect = houseUsers.stream().filter(item -> Objects.nonNull(item.getType())).collect(Collectors.groupingBy(HouseUser::getType));
		List<String> legendData = new ArrayList<>();
		List<ChartDataVO> chartData = new ArrayList<>();
		for (DictBiz dictBiz : dictList) {
			String dictValue = dictBiz.getDictValue();
			Integer dictKey = Convert.toInt(dictBiz.getDictKey());
			int count = collect.get(dictKey).size();
			legendData.add(dictValue);
			chartData.add(ChartDataVO.builder()
				.name(dictValue)
				.value(Convert.toLong(count))
				.build());
		}
		legendData.add(OTHER_BIZ_TYPE);
		chartData.add(ChartDataVO.builder()
			.name(OTHER_BIZ_TYPE)
			.value(Convert.toLong(otherCount))
			.build());
		return R.data(EnterpriseBizTypePieDataVO.builder()
			.legendData(legendData)
			.data(chartData)
			.build());
	}

}
