package org.springblade.app.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.OperationConstant;
import org.springblade.core.mp.support.BladePage;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.dto.DispatchTask;
import org.springblade.device.dto.UserInfoDto;
import org.springblade.device.feign.IDoorDeviceClient;
import org.springblade.device.vo.DoorDeviceVO;
import org.springblade.estate.dto.ApplyUserDTO;
import org.springblade.estate.dto.UserAccessPermissionsDTO;
import org.springblade.estate.entity.ApplyUser;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.feign.IUserAccessPermissionsClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.person.dto.HouseUserDTO;
import org.springblade.person.dto.MemberDTO;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.entity.Member;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.person.feign.IMemberClient;
import org.springblade.person.vo.HouseUserVO;
import org.springblade.system.expand.entity.Conf;
import org.springblade.system.expand.feign.IConfClient;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

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

/**
 * Created By lidexi in 2021/4/29
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/app/houseuser")
@Slf4j
public class HouseUserController {

	private final IHouseUserClient houseUserClient;
	private final IConfClient confClient;
	private final IApplyUserClient applyUserClient;
	private final IDoorDeviceClient doorDeviceClient;
	private final IMemberClient memberClient;
	private final IUserAccessPermissionsClient userAccessPermissionsClient;


	/**
	 * 判断业主房间是否存在成员
	 * @param memberId
	 * @return
	 */
	@PostMapping("hasMember")
	public R hasMember(@RequestParam Long memberId){
		HouseUser houseUser = new HouseUser();
		//业主
		houseUser.setType(0);
		houseUser.setMemberId(memberId);
		List<HouseUserVO> houseUserVOS = houseUserClient.list(houseUser);
		if (CollUtil.isEmpty(houseUserVOS)) {
			return R.data(false);
		}
		List<Long> roomIds = houseUserVOS.stream().map(HouseUser::getRoomId).collect(Collectors.toList());
		if (CollUtil.isEmpty(roomIds)) {
			return R.data(false);
		}
		List<HouseUser> users = houseUserClient.listInRoomIds(roomIds);
		if (CollUtil.isEmpty(users)) {
			return R.data(false);
		}
		return R.data(true);
	}

	/**
	 * 新会员绑定房间
	 *
	 * @param ids      houseUserIds
	 * @param memberId 会员id
	 * @return
	 */
	@PostMapping("bindRoom")
	public R bindRoom(@RequestBody List<Long> ids, String memberId) {
		return R.status(houseUserClient.updateUserByIds(ids, memberId));
	}

	/**
	 * 功能描述: 根据房屋id查询房屋下面的成员
	 *
	 * @param map {
	 *            room_id       :   房屋id
	 *            pageNum       :   分页页数
	 *            pageSize      :   分页大小
	 *            org_id        :   机构授权org_id，机构id,
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getUserByRoomId")
	public Map<String, Object> getUserByRoomId(@RequestBody Map<String, String> map) {

		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "获取列表失败");
		String room_id = map.get("room_id");
		String pageNum = map.get("pageNum");
		String pageSize = map.get("pageSize");
		try {

			if (room_id == null) {
				hashMap.put("result_msg", "room_id不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageNum)) {
				hashMap.put("result_msg", "分页页码不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageSize)) {
				hashMap.put("result_msg", "分页大小不能为空");
				return hashMap;
			}
			List<Long> roomIds = new ArrayList<>(1);
			roomIds.add(Long.valueOf(room_id));

			Query query = new Query();
			query.setSize(Integer.valueOf(pageSize));
			query.setCurrent(Integer.valueOf(pageNum));

			Page<HouseUserVO> page = this.houseUserClient.getPageByRoomIds(roomIds, query);
			Long totalPageNum = (page.getTotal() + page.getSize() - 1) / page.getSize();
			List<HouseUserVO> users = page.getRecords();
			hashMap.put("result_code", 1);
			Conf searchConf = new Conf();
			searchConf.setConfToken("file.server.host");
			for (HouseUserVO user : users) {
				if (user.getFaceEndDate() != null) {
					Conf noticeConf = new Conf();
					noticeConf.setConfToken("expire.notice.days");
					Conf conf = this.confClient.detail(noticeConf);
					if (conf != null) {
						Integer days = Integer.parseInt(conf.getConfValue());
						int compare = DateUtil.compare(DateUtil.offsetDay(new Date(), days), user.getFaceEndDate());
						user.setFaceValid(compare > 0 ? false : true);
					}
				}
			}
			hashMap.put("list", users);
			hashMap.put("pages", totalPageNum);
			if (users.size() == 0) {
				hashMap.put("result_msg", "没有相关房屋信息");
			} else {
				hashMap.put("result_msg", "获取列表成功");
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	@GetMapping(value = "/list")
	public R houseList(HouseUser houseUser){
		return R.data(houseUserClient.list(houseUser));
	}


	/**
	 * 功能描述: 获取房屋成员 By  memberId
	 *
	 * @param map {
	 *            member_id     :   会员id
	 *            pageNum       :   分页页数
	 *            pageSize      :   分页大小
	 *            org_id        :   机构授权org_id，机构id,
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getAllUserByMemberIdBak")
	public Map<String, Object> getAllUserByMemberIdBak(@RequestBody Map<String, String> map) {

		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "获取列表失败");
		String member_id = map.get("member_id");
		String pageNum = map.get("pageNum");
		String pageSize = map.get("pageSize");
		String roomId = map.get("roomId");
		try {

			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "member_id不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageNum)) {
				hashMap.put("result_msg", "分页页码不能为空");
				return hashMap;
			}
			if (StringUtils.isEmpty(pageSize)) {
				hashMap.put("result_msg", "分页大小不能为空");
				return hashMap;
			}
			//查询会员对应的user
			ApplyUser applyUser = new ApplyUser();
			applyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
			applyUser.setMemberId(Long.valueOf(member_id));
			List<ApplyUserVO> applyUserVOList = applyUserClient.list(applyUser);
//			MemberAndUser memberAndUser = new MemberAndUser();
//			memberAndUser.setMemberId(Long.valueOf(member_id));
//			List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
			if (applyUserVOList == null || applyUserVOList.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
				return hashMap;
			} else {
				List<Long> roomIds = new ArrayList<>();
				if (null != roomId) {
					roomIds.add(Long.valueOf(roomId));
				} else {
					for (ApplyUser mu : applyUserVOList) {
						roomIds.add(mu.getRoomId());
					}
				}


				Query query = new Query();
				query.setSize(Integer.valueOf(pageSize));
				query.setCurrent(Integer.valueOf(pageNum));
				Page<HouseUserVO> page = this.houseUserClient.getPageByRoomIds(roomIds, query);
				Long totalPageNum = (page.getTotal() + page.getSize() - 1) / page.getSize();
				List<HouseUserVO> users = page.getRecords();
				hashMap.put("result_code", 1);
				Conf searchConf = new Conf();
				searchConf.setConfToken("file.server.host");
				for (HouseUserVO user : users) {
					if (user.getFaceEndDate() != null) {
						Conf noticeConf = new Conf();
						noticeConf.setConfToken("expire.notice.days");
						Conf conf = this.confClient.detail(noticeConf);
						if (conf != null) {
							Integer days = Integer.parseInt(conf.getConfValue());
							int compare = DateUtil.compare(DateUtil.offsetDay(new Date(), days), user.getFaceEndDate());
							user.setFaceValid(compare > 0 ? false : true);
						}
					}
				}

				List<HouseUserVO> houseUsers = page.getRecords();
				if (houseUsers == null || houseUsers.size() == 0) {
					hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
					return hashMap;
				}
				hashMap.put("result_code", 1);
				hashMap.put("list", houseUsers);
				hashMap.put("pages", totalPageNum);
				if (houseUsers.size() == 0) {
					hashMap.put("result_msg", "没有相关数据");
				} else {
					hashMap.put("result_msg", "查询数据成功");
				}
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 获取房屋成员 By  memberId
	 */
	@PostMapping(value = "/getRoomUserByMemberId")
	public R<BladePage<HouseUserVO>> getRoomUserByMemberId(@RequestBody MemberDTO memberDTO) {
		Assert.notNull(memberDTO.getResidentialId(), "小区必传");
//		Assert.notNull(memberDTO.getId(), "会员必传");
		Assert.notNull(memberDTO.getRoomId(), "房间必传");
		return houseUserClient.getPageByMember(memberDTO);
	}

	/**
	 * 功能描述: 修改我的家人
	 *
	 * @param map {
	 *            user_id               :   修改的住户id
	 *            type                  :   住户类型,['业主','成员','租户'],
	 *            id_card               :   身份证号，
	 *            sex                   :   性别，
	 *            nationality           :   国籍， 0 中国大陆 1 中国香港/澳门 2 中国台湾 3 海外
	 *            face_url             :   脸部照片url（没有域名）
	 *            face_code             :   根据图片生成的faceId--图片的md5
	 *            passport_img_uri      :   护照照片url（没有域名，nationality = 3时,国籍为海外）
	 *            entry_img_uri         :   入境证明url（没有域名，nationality = 3时,国籍为海外）
	 *            phone                   :   电话，
	 *            member_id             :   会员id
	 *            create_type           :   申请来源0-小程序添加 1-后台添加  2-后台导入 3-app添加
	 *            face_image_base64     :   人脸图片的base64字符串，
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/editUserBak")
	public Map<String, Object> editUserBak(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "提交修改失败");

		String user_id = map.get("user_id");
		String type = map.get("type");
		String nationality = map.get("nationality");
		String face_url = map.get("face_rul");
		String face_code = map.get("face_code");
		String passport_img_uri = map.get("passport_img_uri");
		String entry_img_uri = map.get("entry_img_uri");
		String id_card = map.get("id_card");
		String sex = map.get("sex");
		String phone = map.get("phone");
		String member_id = map.get("member_id");
		String create_type = map.get("create_type");
		String operUserType = map.get("oper_user_type");
		String operatorName = map.get("operatorName");
		String name = map.get("name");
		try {

			if (StringUtils.isBlank(type)) {
				hashMap.put("result_msg", "住户身份类型（user_id）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(sex)) {
				hashMap.put("result_msg", "住户性别（sex）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(phone)) {
				hashMap.put("result_msg", "电话（tel）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id（member_id）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(create_type)) {
				hashMap.put("result_msg", "数据申请来源（create_type）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(user_id)) {
				hashMap.put("result_msg", "user_id不能为空");
				return hashMap;
			} else {
				HouseUser searchHouseUser = new HouseUser();
				searchHouseUser.setId(Long.valueOf(user_id));
				HouseUser user = this.houseUserClient.detail(searchHouseUser);
				if (user == null) {
					hashMap.put("result_msg", "修改的住户不存在");
					return hashMap;
				} else {
					//一个房间下面同一个名字只能一条待审核的申请记录
					ApplyUser applyUser = new ApplyUser();
					if (operUserType != null) {
						if (OperationConstant.ZERO == Integer.parseInt(operUserType) && OperationConstant.ZERO != Integer.parseInt(type)) {
							//如果不是审核的业主信息，就直接通过
							boolean needPushFace = false;
							if (!user.getFaceUrl().equals(face_url)) {
								needPushFace = true;
							}
							if (StringUtil.isNotBlank(face_url)) {
								user.setFaceUrl(confClient.removePrefix(face_url));
								user.setImageMd5(face_code);
							} else {
								user.setFaceUrl(confClient.removePrefix(user.getFaceUrl()));
							}
							user.setIdCard(id_card);
							user.setSex(Integer.parseInt(sex));
							user.setPhone(phone);
							user.setCreateType(Integer.parseInt(create_type));
							user.setType(Integer.parseInt(type));
							user.setNationality(Integer.parseInt(nationality));

							boolean b = houseUserClient.update(user);
							if (b) {
								applyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
								applyUser.setUserId(user.getId());
								applyUser.setRoomId(user.getRoomId());
								applyUser.setOperatorType(OperationConstant.ONE);//后台审核类型
								applyUser.setOperatorName(operatorName);
								applyUser.setCheckDate(new Date());
								hashMap.put("result_msg", "提交修改成功");
							}
						} else {
							applyUser.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());
							applyUser.setUserId(user.getId());
							applyUser.setRoomId(user.getRoomId());
							ApplyUserVO applyUserVO = this.applyUserClient.detail(applyUser);
							if (applyUserVO != null) {
								hashMap.put("result_msg", "名字" + name + "已有一条申请记录处于待审核状态，请勿重复提交，等待物业审核");
								return hashMap;
							} else {
								hashMap.put("result_msg", "提交修改成功，请等待物业审核");
							}
						}
					}
					//查询用户之前是否有申请过的数据，有就把人脸拿出来set到旧人脸，没有旧人脸为空
					ApplyUser applyUserDto = new ApplyUser();
					applyUserDto.setMemberId(Long.valueOf(member_id));
					applyUserDto.setUserId(user.getId());
					List<ApplyUserVO> applyUserList = this.applyUserClient.list(applyUserDto);
					ApplyUser applyUser1 = null;
					if (applyUserList.size() > 0) {
						applyUser1 = applyUserList.get(0);
					} else {
						applyUser1 = new ApplyUser();
					}

					applyUser.setUserId(Long.valueOf(user_id));
					applyUser.setRoomName(user.getRoomName());
					//申请记录审核状态：0-待审核 1-审核通过 2-审核不通过

					applyUser.setUnitId(user.getUnitId());
					applyUser.setUnitName(user.getUnitName());
					applyUser.setBuildingName(user.getBuildingName());
					applyUser.setBuildingId(user.getBuildingId());
					applyUser.setResidentialName(user.getResidentialName());
					applyUser.setResidentialId(user.getResidentialId());
					applyUser.setCreateType(Integer.valueOf(create_type));
					applyUser.setRecordType(OperationConstant.TWO);
					//修改的属性**********开始*******
					if (StringUtils.isNotEmpty(applyUser1.getFaceUrl())) {
						applyUser.setOldFaceUrl(applyUser1.getFaceUrl());
					} else {
						applyUser.setOldFaceUrl(user.getFaceUrl());
					}
					applyUser.setType(Integer.valueOf(type));
					if (StringUtils.isNotBlank(id_card)) {
						applyUser.setIdCard(id_card);
					}
					applyUser.setSex(Integer.valueOf(sex));
					if (StringUtils.isBlank(nationality)) {
						applyUser.setNationality(user.getNationality());
					} else {
						applyUser.setNationality(NumberUtils.INTEGER_ZERO);
					}
					if (StringUtils.isNotBlank(face_url)) {
						applyUser.setFaceUrl(confClient.removePrefix(face_url));
						applyUser.setImageMd5(face_code);
					} else {
						applyUser.setFaceUrl(confClient.removePrefix(user.getFaceUrl()));
						applyUser.setImageMd5(user.getImageMd5());
					}
					if (StringUtils.isNotBlank(passport_img_uri)) {
						applyUser.setPassportImgUri(confClient.removePrefix(passport_img_uri));
					}
					if (StringUtils.isNotBlank(entry_img_uri)) {
						applyUser.setEntryImgUri(confClient.removePrefix(entry_img_uri));
					}
					applyUser.setPhone(phone);
					applyUser.setMemberId(Long.valueOf(member_id));
					applyUser.setName(user.getName());
					//申请的记录类型 0--认证类型 1--新增类型 2--编辑类型
//					applyUser.setRecordType(2);
//					applyUser.setCheckState(CommonConstant.UserAuditStatus.pass.getValue());
					//修改的属性**********结束*******
					boolean result = this.applyUserClient.save(applyUser);
					if (result) {
						hashMap.put("result_code", 1);
						hashMap.put("result_msg", "修改成功");
					}
				}
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	@PostMapping(value = "/editUser")
	public R editUser(@RequestBody HouseUserDTO houseUserDTO) {
		HouseUser houseUser = houseUserClient.getById(houseUserDTO.getId());
		Assert.notNull(houseUser, "编辑的住户不存在");
		BeanUtil.copy(houseUserDTO, houseUser);
		if (StringUtil.isNotBlank(houseUserDTO.getFaceUrl())) {
			houseUserDTO.setFaceUrl(confClient.removePrefix(houseUserDTO.getFaceUrl()));
		}
		if (Objects.nonNull(houseUserDTO.getFaceUrl()) && !houseUserDTO.equals(houseUser.getFaceUrl())) {
			//修改人脸，下发人脸
			this.modifyFace(houseUserDTO);
		}
		boolean update = houseUserClient.update(houseUser);
		if (update) {
			return R.success("更新成功");
		} else {
			return R.fail("更新失败");
		}
	}

	/**
	 * 功能描述: 删除User
	 *
	 * @param map {
	 *            member_id     :   会员id
	 *            user_id       :   要删除的住户id
	 *            org_id        :   机构授权org_id，机构id,
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/deleteUserByIdBak")
	public Map<String, Object> deleteUserByIdBak(@RequestBody Map<String, String> map) {

		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "删除失败");
		String user_id = map.get("user_id");
		String member_id = map.get("member_id");
		try {

			if (StringUtils.isBlank(user_id)) {
				hashMap.put("result_msg", "user_id不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "member_id不能为空");
				return hashMap;
			}
			ApplyUser applyUser = new ApplyUser();
			applyUser.setMemberId(Long.valueOf(member_id));
			applyUser.setUserId(Long.valueOf(user_id));
			//判断会员和住户是否存在关系
			ApplyUserVO applyUserVO = this.applyUserClient.detail(applyUser);
			//会员和住户存在关系
			if (applyUserVO == null) {
				hashMap.put("result_msg", "找不到该住户的认证信息");
				return hashMap;
			}
			//校验权限
			Member searchMember = new Member();
			searchMember.setId(Long.valueOf(member_id));
			Member member = this.memberClient.detail(searchMember);
			if (member == null) {
				hashMap.put("result_msg", "操作的会员不存在");
				return hashMap;
			}
			HouseUser houseUser = new HouseUser();
			houseUser.setId(Long.valueOf(user_id));
			HouseUser user = this.houseUserClient.detail(houseUser);
			if (user == null) {
				hashMap.put("result_msg", "要删除的住户不存在");
				return hashMap;
			}
			//业主---不能删除
			if (user.getType() == OperationConstant.ZERO) {
				hashMap.put("result_msg", "该住户身份为业主不能删除");
				return hashMap;
			}
			//从新拼凑条件
			applyUser.setUserId(null);
			List<ApplyUserVO> list = this.applyUserClient.list(applyUser);
			if (list == null || list.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
				return hashMap;
			} else {
				boolean result = false;
				for (ApplyUser mau : list) {
					//会员也是房屋下的成员
					if (mau.getRoomId().equals(user.getRoomId())) {
						HouseUser searchHouseUser = new HouseUser();
						searchHouseUser.setId(mau.getUserId());
						HouseUser memberUser = this.houseUserClient.detail(searchHouseUser);
						//会员在要删除的住户房屋下是业主身份
						if (memberUser.getType().equals(OperationConstant.ZERO)) {
							result = true;
						}
						break;
					}
				}
				if (!result) {
					hashMap.put("result_msg", "会员无权限删除该住户");
					return hashMap;
				}
			}
			HouseUserDTO userDto = new HouseUserDTO();
			userDto.setId(user.getId());
			userDto.setMemberId(member.getId());
			//删除user，而且删除与会员的关系，修改会员的状态
			boolean result = this.houseUserClient.deleteUserAndRelationship(userDto);
			if (result) {
				hashMap.put("result_code", 1);
				hashMap.put("result_msg", "删除成功");
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 根据member和所在小区获取家人
	 *
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getHouseUserByMemberAndRoom")
	public R<HouseUserVO> getHouseUserByMemberAndRoom(@RequestBody HouseUserDTO houseUserDTO) {
		Assert.notNull(houseUserDTO.getMemberId(), "会员必传");
		Assert.notNull(houseUserDTO.getRoomId(), "房间必传");
		try {
			List<ApplyUser> applyUserList = applyUserClient.getListByMember(houseUserDTO.getMemberId(), null, houseUserDTO.getRoomId(), CommonConstant.UserAuditStatus.pass.getValue());
			Assert.notEmpty(applyUserList, "请先完成住户认证");
			ApplyUser applyUser = applyUserList.get(0);
			HouseUser houseUser = new HouseUser();
			houseUser.setId(applyUser.getUserId());
			HouseUserVO houseUserVO = houseUserClient.detail(houseUser);
			return R.data(houseUserVO);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 功能描述: 根据member和所在小区获取自己和家人列表
	 *
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getHouseUserListByMemberAndResidential")
	public R<List<HouseUserVO>> getHouseUserListByMemberAndResidential(@RequestBody HouseUserDTO houseUserDTO) {
		Assert.notNull(houseUserDTO.getMemberId(), "会员必传");
		Assert.notNull(houseUserDTO.getResidentialId(), "所在小区必传");
		List<HouseUserVO> houseUserVOList = new ArrayList<>();
		try {
			List<ApplyUser> applyUserList = applyUserClient.getListByMember(houseUserDTO.getMemberId(), houseUserDTO.getResidentialId(), null, CommonConstant.UserAuditStatus.pass.getValue());
			Assert.notEmpty(applyUserList, "请先完成住户认证");
			List<Long> userIdList = applyUserList.stream().map(ApplyUser::getUserId).collect(Collectors.toList());
			if (userIdList.size() > 0) {
				houseUserVOList = houseUserClient.getListByUserIds(userIdList);
			}
			return R.data(houseUserVOList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	/**
	 * 功能描述: 删除User
	 *
	 * @param map {
	 *            member_id     :   会员id
	 *            user_id       :   要删除的住户id
	 *            org_id        :   机构授权org_id，机构id,
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/deleteUserById")
	public Map<String, Object> deleteUserById(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "删除失败");
		String user_id = map.get("user_id");
		String member_id = map.get("member_id");
		if (StringUtils.isBlank(user_id)) {
			hashMap.put("result_msg", "user_id不能为空");
			return hashMap;
		}
		try {
			ApplyUserDTO applyUserDTO = new ApplyUserDTO();
			applyUserDTO.setUserId(Long.valueOf(user_id));
			if (StringUtil.isNotBlank(member_id)) {
				applyUserDTO.setMemberId(Long.valueOf(member_id));
			}
			applyUserDTO.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
			List<ApplyUser> applyUserList = applyUserClient.getByAuditStatus(applyUserDTO);
			List<Long> idList = applyUserList.stream().map(ApplyUser::getId).collect(Collectors.toList());
			if (idList.size() > 0) {
				applyUserClient.remove(Func.join(idList));
			}
			houseUserClient.remove(user_id);
			hashMap.put("result_code", 1);
			hashMap.put("result_msg", "删除成功");
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 更新人脸下发
	 * @param houseUserDTO
	 * @return
	 */
	@PostMapping(value = "/modifyFace")
	public R modifyFace(@RequestBody HouseUserDTO houseUserDTO) {
		HouseUser houseUser = houseUserClient.getById(houseUserDTO.getId());
		Assert.notNull(houseUser, "住户不存在");
		if (StringUtil.isNotBlank(houseUserDTO.getFaceUrl())) {
			houseUser.setFaceUrl(confClient.removePrefix(houseUserDTO.getFaceUrl()));
		}
		boolean update = houseUserClient.update(houseUser);
		if (update) {
			//重新下发人脸
			UserAccessPermissionsDTO userAccessPermissionsDTO = new UserAccessPermissionsDTO();
			userAccessPermissionsDTO.setUserId(Func.toStr(houseUser.getId()));
			userAccessPermissionsDTO.setUserFace(houseUserDTO.getFaceUrl());
			userAccessPermissionsDTO.setUserType(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue());
			userAccessPermissionsDTO.setTargetType(1);
			List<DoorDeviceVO> doorDeviceVOList = doorDeviceClient.getListByResidentialAndUnit(houseUser.getResidentialId(), houseUser.getUnitId(), 1);
			if (doorDeviceVOList.size() == 0) {
				return R.status(true);
			}
			List<Long> deviceIdList = doorDeviceVOList.stream().map(DoorDeviceVO::getId).collect(Collectors.toList());
			userAccessPermissionsDTO.setDeviceIds(StringUtil.join(deviceIdList, ","));
			userAccessPermissionsClient.pushFace(userAccessPermissionsDTO);
			return R.success("人脸更换成功");
		} else {
			return R.fail("人脸更换失败");
		}
	}

	/**
	 * 下发人脸方法
	 *
	 * @param user
	 * @param operType
	 */
	private void pushFace(HouseUser user, Integer operType) {
		log.warn("/app/user/editUser-pushFace?userId=" + user.getId());

		if (StringUtils.isNotBlank(user.getFaceUrl())) {
			String imgHost = this.confClient.getValueByToken(CommonConstant.SystemConf.FILESERVER.getValue());
			List<Map<String, Object>> userFaceList = new ArrayList<>(1);
			Map<String, Object> map = new HashMap<>(3);
			map.put("imgMd5", user.getImageMd5());
			String faceUrl = imgHost + user.getFaceUrl();
			map.put("imgSrc", faceUrl);
			userFaceList.add(map);
			//  下发人脸-到通用设备
			UserInfoDto dto = new UserInfoDto();
			dto.setId(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue() + user.getId());
			dto.setFaceCodeList(userFaceList);
			dto.setFaceUrl(faceUrl);
			dto.setBeginDate(user.getFaceBeginDate());
			dto.setEndDate(user.getFaceEndDate());
			DispatchTask task = new DispatchTask();
			task.setUnitId(user.getUnitId());
			task.setXqId(user.getResidentialId());
			task.setData(dto);
			this.doorDeviceClient.pushUserFace(task, operType);
		}
	}


}
