package org.springblade.app.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springblade.app.dto.OpenDoorDto;
import org.springblade.app.util.CommonUtil;
import org.springblade.app.util.SendSms;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.OperationConstant;
import org.springblade.common.entity.CustInfoVerify;
import org.springblade.community.entity.Residential;
import org.springblade.community.entity.Room;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.feign.IRoomClient;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
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.DoorDeviceDTO;
import org.springblade.device.entity.DoorDevice;
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.entity.GuestRecord;
import org.springblade.estate.feign.IApplyUserClient;
import org.springblade.estate.feign.IGuestRecordClient;
import org.springblade.estate.feign.IUserAccessPermissionsClient;
import org.springblade.estate.vo.ApplyUserVO;
import org.springblade.estate.vo.UserAccessPermissionsVO;
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.person.vo.MemberVO;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.third.doordevice.feign.IDoorDeviceButtClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created By lidexi in 2021/4/25
 **/
@RestController
@RequiredArgsConstructor
@Api(value = "", tags = "接口")
@RequestMapping(value = "/app/member")
@Slf4j
public class MemberController {

	private final IMemberClient memberClient;
	private final IHouseUserClient houseUserClient;
	private final IRoomClient roomClient;
	private final IApplyUserClient applyUserClient;
	private final RedisTemplate<String, String> redisTemplate;
	private final IDoorDeviceClient doorDeviceClient;
	private final IDoorDeviceButtClient doorDeviceButtClient;
	private final IConfClient confClient;
	private final IUserAccessPermissionsClient userAccessPermissionsClient;
	private final IGuestRecordClient guestRecordClient;
	private final IResidentialClient residentialClient;
	/**
	 * 短信缓存名称
	 */
	private final static String VERIFICATION_CODE = "verification:code";


	/**
	 * 注销账户
	 * @param memberId
	 * @return
	 */
	@PostMapping("logout")
	public R logout(@RequestParam Long memberId) {
		applyUserClient.logout(memberId);
		houseUserClient.logout(memberId);
		memberClient.remove(memberId.toString());
		return R.data(true);
	}

	/**
	 * 功能描述: 获取验证码
	 *
	 * @param map {
	 *            tel           :   手机号码,
	 *            play_type     :   操作类型   1：需要存着手机号  2：不需要存在手机号
	 *            org_id        :   机构授权org_id，机构id
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getSmsCode")
	public Map<String, Object> getSmsCode(@RequestBody Map<String, String> map) {

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

			if (StringUtils.isBlank(tel)) {
				hashMap.put("result_msg", "电话号码不能为空");
				return hashMap;
			} else {
				//正则手机号码校验
//                String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
				String regex = "^1[23456789]\\d{9}$";
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(tel);
				boolean isMatch = m.matches();
				if (!isMatch) {
					hashMap.put("result_msg", "手机号码不正确");
					return hashMap;
				}
				//验证手机号是否存在或不存在
				Member member = new Member();
				member.setPhone(tel);
				Member memberCheck = memberClient.detail(member);
				if (memberCheck != null) {
					hashMap.put("result_msg", "该手机号已注册");
					return hashMap;
				}
			}
			//生成6位数字的验证码
			String verify_code = String.valueOf(CommonUtil.generateNumber(6));
			//发短信
			SendSmsResponse response = SendSms.sendSms(tel, verify_code);
			//发送成功
			if ("OK".equals(response.getCode())) {
				String key = VERIFICATION_CODE + tel;
				//  验证码存入缓存
				this.redisTemplate.opsForValue().set(key, verify_code);
				//  设置缓存有效期 20分钟
				this.redisTemplate.expire(key, 1200, TimeUnit.SECONDS);


				hashMap.put("result_code", 1);
				hashMap.put("result_msg", "短信发送成功");

			} else {
				hashMap.put("result_msg", response.getMessage());
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述:会员注册--小程序
	 *
	 * @param map {
	 *            name         :   姓名,
	 *            tel          :   手机号码,
	 *            verify_code  :   验证码,
	 *            openid       :   微信openid，----小程序端注册时必填
	 *            org_id       :   机构授权org_id机构id
	 *            token        :   对接令牌
	 *            }
	 * @return
	 */
	@PostMapping(value = "/memberRegister")
	public Map<String, Object> memberRegister(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		try {
			String name = map.get("name");
			String tel = map.get("tel");
			String verify_code = map.get("verify_code");
			String openid = map.get("openid");

			if (StringUtils.isBlank(name)) {
				hashMap.put("result_msg", "姓名不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(tel)) {
				hashMap.put("result_msg", "手机号码不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(verify_code)) {
				hashMap.put("result_msg", "验证码不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(openid)) {
				hashMap.put("result_msg", "openid不能为空");
				return hashMap;
			}
			//获取存在redis上的验证码
			String key = VERIFICATION_CODE + tel;
			String redis_verify_code = this.redisTemplate.opsForValue().get(key);
			//验证码过期 || 没有获取验证码操作
			if (redis_verify_code == null) {
				hashMap.put("result_msg", "验证码过期，或者无效验证码");
				return hashMap;
			}
			if (!verify_code.equals(redis_verify_code)) {
				hashMap.put("result_msg", "验证码不正确");
				return hashMap;
			}
			//一个手机号码只能注册一个会员
			Member checkMember = new Member();
			checkMember.setPhone(tel);
			Member isExist = memberClient.detail(checkMember);
			//号码已经注册
			if (isExist != null) {
				//检测名字是否匹配
				checkMember.setName(name);
				Member checkTelAndName = memberClient.detail(checkMember);
				//匹配成功
				if (checkTelAndName != null) {
					//关联会员
					checkTelAndName.setOpenid(openid);
					boolean update = memberClient.update(checkTelAndName);
					if (update) {
						hashMap.put("result_code", 1);
						hashMap.put("result_msg", "注册成功");
					} else {
						hashMap.put("result_code", "注册失败");
					}
				} else {
					//手机号码已注册--名字不匹配
					hashMap.put("result_msg", "手机号码已注册，姓名不匹配，注册失败");
					return hashMap;
				}
			} else {
				Member member = new Member();
				member.setName(name);
				member.setPhone(tel);
				//create_type : 会员注册来源，0-小程序注册 1-app注册,
				member.setCreateType(0);
				member.setOpenid(openid);
				//新增会员--注册
				boolean save = this.memberClient.save(member);
				if (save) {
					List<HouseUserVO> houseUser = this.findHouseUser(name, tel);
					hashMap.put("result_code", 1);
					hashMap.put("result_msg", "注册成功");
					hashMap.put("result_data", houseUser);

				} else {
					hashMap.put("result_code", "注册失败");
				}
			}

		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}


	private List<HouseUserVO> findHouseUser(String name, String phone) {
		HouseUser houseUser = new HouseUser();
		houseUser.setPhone(phone);
		houseUser.setName(name);
		List<HouseUserVO> list = houseUserClient.list(houseUser);
		return list;
	}

	/**
	 * 功能描述: 会员--认证成住户 | 新增家人
	 *
	 * @param map {
	 *            type                  : 住户类型,['业主','成员','租户'],
	 *            id_card               :  身份证号，
	 *            sex                   :  性别，
	 *            nationality           :  国籍， 0 中国大陆 1 中国香港/澳门 2 中国台湾 3 海外
	 *            image_uri             :  脸部照片url（没有域名）
	 *            face_code              :  根据图片生成的faceId--图片的md5
	 *            passport_img_uri        :  护照照片url（没有域名，nationality = 3时,国籍为海外）
	 *            entry_img_uri           :  入境证明url（没有域名，nationality = 3时,国籍为海外）
	 *            name                  :  名字，
	 *            tel                   :  电话，
	 *            room_id               :  房间id，
	 *            member_id             :  会员id
	 *            org_id                :  机构授权org_id，机构id,
	 *            token                 :  对接令牌
	 *            create_type           :  申请来源0-小程序添加 1-后台添加  2-后台导入 3-app添加
	 *            record_type           :  申请的记录类型 0--认证类型 1--新增类型 2--编辑类型
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/authenticationBak")
	public Map<String, Object> authenticationBak(@RequestBody Map<String, String> map) {
		Map<String, Object> hashMap = new HashMap<>();
		//result_code:0-失败  1-成功
		hashMap.put("result_code", 0);
		hashMap.put("result_msg", "提交失败");
		try {
			String type = map.get("type");
			String id_card = map.get("id_card");
			String sex = map.get("sex");
			String nationality = map.get("nationality");
			String face_url = map.get("face_url");

			String image_md5 = map.get("imgMd5");
			String passport_img_uri = map.get("passport_img_uri");
			String entry_img_uri = map.get("entry_img_uri");
			String name = map.get("name");
			String phone = map.get("phone");
			String room_id = map.get("room_id");
			String member_id = map.get("member_id");
			String operatorName = map.get("operatorName");

			String create_type = map.get("create_type");
			String record_type = map.get("record_type");
			Room room;

			if (StringUtils.isBlank(type)) {
				hashMap.put("result_msg", "住户类型不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(nationality)) {
				nationality = NumberUtils.INTEGER_ZERO.toString();
			}
			if (StringUtils.isBlank(id_card)) {
				hashMap.put("result_msg", "身份证号不能为空");
				return hashMap;
			}
			if (StringUtils.isNotBlank(id_card)) {
				boolean timeRange = false;
				try {
					timeRange = CommonUtil.isTimeRange("7:00", "22:00");
				} catch (Exception e) {
					hashMap.put("result_msg", "认证申请失败");
					return hashMap;
				}
//				Assert.isTrue(timeRange, "请在7:00-22:00时间内申请认证！");
				CustInfoVerify custInfoVerify = new CustInfoVerify();
				custInfoVerify.setCustName(name);
				custInfoVerify.setCertNumber(id_card);
				custInfoVerify.setCertType("1");
				//开发环境不启用
//				Boolean result = CustInfoVerifyUtil.custInfoVerify(custInfoVerify);
//				if(!result){
//					hashMap.put("result_msg", "身份证验证失败，请填写正确的身份证信息");
//					return hashMap;
//				}
			}
			if (Integer.valueOf(type) == 0 && Integer.valueOf(nationality) == 3) {
				if (StringUtils.isBlank(passport_img_uri)) {
					hashMap.put("result_msg", "(passport_img_uri)请上传护照图片");
					return hashMap;
				}
				if (StringUtils.isBlank(entry_img_uri)) {
					hashMap.put("result_msg", "(entry_img_uri)请上传入境证明");
					return hashMap;
				}
			}
			if (StringUtils.isBlank(sex)) {
				hashMap.put("result_msg", "性别不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(name)) {
				hashMap.put("result_msg", "名字不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(phone)) {
				hashMap.put("result_msg", "电话号码不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(room_id)) {
				hashMap.put("result_msg", "房间id不能为空");
				return hashMap;
			} else {
				Room searchRoom = new Room();
				searchRoom.setId(Long.valueOf(room_id));
				room = this.roomClient.detail(searchRoom);
				if (room == null) {
					hashMap.put("result_msg", "房间id有误，没有与之对应房间");
					return hashMap;
				}
			}
			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(create_type)) {
				hashMap.put("result_msg", "数据申请来源（create_type）不能为空");
				return hashMap;
			}
			if (StringUtils.isBlank(record_type)) {
				hashMap.put("result_msg", "申请的记录类型（record_type）不能为空");
				return hashMap;
			}

			//添加家人
			if (record_type.equals("1")) {
				ApplyUser applyUser = new ApplyUser();
				applyUser.setMemberId(Long.valueOf(member_id));
				applyUser.setRoomId(Long.valueOf(room_id));
				applyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
				List<ApplyUserVO> list = this.applyUserClient.list(applyUser);
				if (list == null || list.size() == 0) {
					hashMap.put("result_msg", "用户不是该房屋成员");
					return hashMap;
				}
				long count = list.stream().filter(applyUserVO -> applyUserVO.getType() == 0).count();
				if (count <= 0) {
					hashMap.put("result_msg", "无权限在该房屋下添加成员");
					return hashMap;
				}
			}
			//检测房间下的住户是否已经存在同名
			HouseUser nameAndRoom = new HouseUser();
			nameAndRoom.setName(name);
			nameAndRoom.setRoomId(Long.valueOf(room_id));
			HouseUser isExist = this.houseUserClient.detail(nameAndRoom);
			if (isExist != null) {
				hashMap.put("result_msg", "房屋下已经存在名字为" + name + "的住户,请勿重复添加");
				return hashMap;
			}
//			HouseUser idCardUser = new HouseUser();
//			idCardUser.setIdCard(id_card);
//			HouseUser userByCondition = this.houseUserClient.detail(idCardUser);
//			if (userByCondition != null) {
//				hashMap.put("result_msg", "该身份证号已被名字为" + name + "的住户使用,请更换身份证号再试");
//				return hashMap;
//			}
			//一个房间下面同一个名字只能一条待审核的申请记录
			ApplyUser applyUser = new ApplyUser();
			applyUser.setName(name);
			applyUser.setRoomId(Long.valueOf(room_id));
			applyUser.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());
			ApplyUserVO applyUserVO = this.applyUserClient.detail(applyUser);
			if (applyUserVO != null) {
				hashMap.put("result_msg", "名字" + name + "已有一条申请记录处于待审核状态，请勿重复提交，等待物业审核");
				return hashMap;
			} else {
				applyUser.setType(Integer.valueOf(type));
				applyUser.setIdCard(id_card);
				applyUser.setSex(Integer.valueOf(sex));
				applyUser.setNationality(Integer.valueOf(nationality));
				if (StringUtils.isNotBlank(face_url)) {
					applyUser.setFaceUrl(confClient.removePrefix(face_url));
				}
				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);
				//根据姓名和手机号先查找该房屋成员是否已经有memberId，若有使用该成员自己的memberId,没有则使用该业主的memberId
				Member member = new Member();
				member.setPhone(phone);
				member.setName(name);
				member.setState(CommonConstant.MemberAuditStatus.authed.getValue());
				MemberVO memberVO = this.memberClient.detail(member);

				if (null != memberVO && record_type.equals("1")) {//添加家人时该家人若有memberId，则使用该家人自己的memberId
					applyUser.setMemberId(memberVO.getId());
				} else if (null == memberVO && record_type.equals("1")) {//添加家人时该家人没有memberId，使用业主memberId
					applyUser.setMemberId(Long.valueOf(member_id));
				} else {//业务提交审核
					applyUser.setMemberId(Long.valueOf(member_id));

				}
				applyUser.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());


				applyUser.setCreateType(Integer.valueOf(create_type));
				applyUser.setRoomName(room.getName());
				applyUser.setUnitId(room.getUnitId());
				applyUser.setUnitName(room.getUnitName());
				applyUser.setBuildingId(room.getBuildingId());
				applyUser.setBuildingName(room.getBuildingName());
				applyUser.setResidentialId(room.getResidentialId());
				applyUser.setResidentialName(room.getResidentialName());
				applyUser.setRecordType(Integer.valueOf(record_type));

				//认证
				if (applyUser.getRecordType() == 0) {
					boolean result = this.applyUserClient.authentication(applyUser);
					//申请成功
					if (result) {
						hashMap.put("result_code", 1);
						hashMap.put("result_msg", "认证申请成功，请等待物业审核");
					} else {
						hashMap.put("result_msg", "认证申请失败");
					}
					//添加家人
				} else if (applyUser.getRecordType() == 1) {
					applyUser.setOperatorType(OperationConstant.ONE);//后台审核类型
					if (applyUser.getType() == OperationConstant.ZERO) {
						applyUser.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());
						boolean save = this.applyUserClient.save(applyUser);
						if (save) {
							hashMap.put("result_code", 1);
							hashMap.put("result_msg", "认证业主申请成功，请等待物业审核");
						} else {
							hashMap.put("result_msg", "认证申请失败");
						}
					} else {
						applyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
						applyUser.setOperatorName(operatorName);
						applyUser.setCheckDate(new Date());
						if (this.applyUserClient.addApplyUserForFamily(applyUser)) {
							hashMap.put("result_code", 1);
							hashMap.put("result_msg", "添加家人成功");
						} else {
							hashMap.put("result_msg", "提交添加家人申请失败");
						}
					}
				} else {
					hashMap.put("result_msg", "record_type的值不合法：" + record_type);
				}

			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 会员--认证成住户 | 新增家人
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/authentication")
	public R authentication(@RequestBody ApplyUserDTO applyUserDTO) {
		Assert.notNull(applyUserDTO.getMemberId(), "会员必传");
		Assert.notNull(applyUserDTO.getType(), "认证住户类型必传");
		Assert.notNull(applyUserDTO.getResidentialId(), "小区必传");
		Assert.notNull(applyUserDTO.getRoomId(), "房间必传");
		Assert.notNull(applyUserDTO.getIdCard(), "身份证必传");
		Residential residential = residentialClient.getById(applyUserDTO.getResidentialId());
		Assert.notNull(residential, "所属小区不存在");
		applyUserDTO.setAgencyId(residential.getAgencyId());
		List<HouseUserVO> userList = houseUserClient.getListByMember(applyUserDTO.getMemberId(), applyUserDTO.getResidentialId(), applyUserDTO.getRoomId());
		for(HouseUserVO houseUserVO : userList){
			String name = applyUserDTO.getName();
			String idCard = applyUserDTO.getIdCard();
			Assert.isTrue(!(houseUserVO.getName().equals(name) && houseUserVO.getIdCard().equals(idCard)), "该住户已完成认证，请勿重复认证");
		}
		//校验房间内的住户，是否有相同身份
		HouseUser houseUser = new HouseUser();
		houseUser.setRoomId(applyUserDTO.getRoomId());
		houseUser.setIdCard(applyUserDTO.getIdCard());
		HouseUserVO dbHouseUser = houseUserClient.detail(houseUser);
		if(applyUserDTO.getRecordType() == 0){ //认证
			Assert.isTrue(dbHouseUser == null, "房间已存在该身份住户，请勿重复认证");
			return R.status(applyUserClient.authentication(applyUserDTO));
		}else if(applyUserDTO.getRecordType() == 1){ //添加家人
			Assert.isTrue(dbHouseUser == null, "该房间已存在该身份住户，请勿重复申请");
			return R.status(applyUserClient.addApplyUserForFamily(applyUserDTO));
		}else{
			return R.fail("认证失败，未知住户类型");
		}
	}


	/**
	 * 功能描述: 通过会员id获取授权的设备列表
	 *
	 * @param map {
	 *            member_id     :   会员id,
	 *            org_id        :   机构授权org_id，机构id
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/getAuthDeviceByMemberIdBak")
	public Map<String, Object> getAuthDeviceByMemberIdBak(@RequestBody Map<String, String> map) {

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

			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空");
				return hashMap;
			}

			if (StringUtils.isBlank(residential_id)) {
				hashMap.put("result_msg", "小区id不能为空");
				return hashMap;
			}

			ApplyUser searchApplyUser = new ApplyUser();
			searchApplyUser.setMemberId(Long.valueOf(member_id));
			searchApplyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
			searchApplyUser.setResidentialId(Long.valueOf(residential_id));
			List<ApplyUserVO> list = this.applyUserClient.list(searchApplyUser);
			if (list == null || list.size() == 0) {
				hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
				return hashMap;
			} else {
				List<Long> userIds = new ArrayList<>();
				for (ApplyUser mau : list) {
					userIds.add(mau.getUserId());
				}
				List<HouseUserVO> users = this.houseUserClient.getListByUserIds(userIds);
				List<DoorDevice> collect = new ArrayList<>();
				for (HouseUser user : users) {
					List<DoorDeviceVO> devices = this.doorDeviceClient.getListByResidentialAndUnit(user.getResidentialId(), user.getUnitId(), 1);
					collect.addAll(devices);
				}
				hashMap.put("result_code", 1);
				hashMap.put("list", collect);
				if (collect.size() == 0) {
					hashMap.put("result_msg", "没有相关数据");
				} else {
					hashMap.put("result_msg", "查询数据成功");
				}
			}
		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 通过会员id获取授权的设备列表
	 */
	@PostMapping(value = "/getAuthDeviceByMemberId")
	public R<List<UserAccessPermissionsVO>> getAuthDeviceByMemberId(@RequestBody MemberDTO memberDTO) {
		Assert.notNull(memberDTO.getId(), "会员必传");
		Assert.notNull(memberDTO.getResidentialId(), "所在小区必传");
		List<HouseUserVO> houseUserVOList = houseUserClient.getListByMember(memberDTO.getId(), memberDTO.getResidentialId(), null);
		Assert.notEmpty(houseUserVOList, "请先完成住户认证");
		try {
			List<UserAccessPermissionsVO> userAccessPermissionsVOList = new ArrayList<>();
			for (HouseUser user : houseUserVOList) {
				List<UserAccessPermissionsVO> tempList = userAccessPermissionsClient.getListByUserAndAddress(Func.toStr(user.getId()), CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue(), user.getResidentialId(), user.getUnitId(), 1);
				userAccessPermissionsVOList.addAll(tempList);
			}
			return R.data(userAccessPermissionsVOList);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("系统异常");
		}
	}

	/**
	 * 功能描述: 一键开门
	 *
	 * @param map {
	 *            device_id     :   设备id
	 *            member_id     :   会员id,
	 *            org_id        :   机构授权org_id，机构id
	 *            token         :   对接令牌
	 *            }
	 * @return ResultBean<hashMap> 返回结果
	 */
	@PostMapping(value = "/openDoorBak")
	public Map<String, Object> openDoorBak(@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 is_guest = map.get("is_guest");//是否是访客开门
		String phone = map.get("phone");//访客开门需要手机号作为userId
		String device_id = map.get("device_id");
		String member_id = map.get("member_id");
		String user_id = map.get("user_id");

		try {

			if (StringUtils.isBlank(device_id)) {
				hashMap.put("result_msg", "设备id不能为空（device_id）");
				return hashMap;
			}
			if (StringUtils.isBlank(member_id)) {
				hashMap.put("result_msg", "会员id不能为空（member_id）");
				return hashMap;
			}
			DoorDevice searchEntity = new DoorDevice();
			searchEntity.setId(Long.valueOf(device_id));
			DoorDevice doorDevice = this.doorDeviceClient.detail(searchEntity);
			DoorDeviceDTO doorDeviceDTO = Objects.requireNonNull(BeanUtil.copy(doorDevice, DoorDeviceDTO.class));
			if (StringUtils.isNotBlank(is_guest)) {//访客开门
				if (is_guest.equals("1")) {
					if (StringUtils.isNotBlank(phone)) {
						doorDeviceDTO.setUserId(CommonConstant.UserFlag.GUEST_FLAG.getValue() + phone);
					} else {
						hashMap.put("result_msg", "访客开门手机号码必传");
						return hashMap;
					}
				} else {
					hashMap.put("result_msg", "访客开门is_guest必须是字符串1");
					return hashMap;
				}
			} else {
				if (user_id == null) {
					ApplyUser searchApplyUser = new ApplyUser();
					searchApplyUser.setMemberId(Long.valueOf(member_id));
					searchApplyUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
					List<ApplyUserVO> list = applyUserClient.list(searchApplyUser);
					if (list != null && list.size() > 0) {
						user_id = list.get(0).getUserId().toString();
					} else {
						hashMap.put("result_msg", "无审核通过的住户记录");
						return hashMap;
					}
				}
				doorDeviceDTO.setUserId(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue() + user_id);
			}

			//下发开门指令
			Map<String, Object> userInfoDto = new HashMap<>();
			userInfoDto.put("id", doorDeviceDTO.getUserId());
			R resultBean = doorDeviceButtClient.remoteOpenDoor(doorDevice.getSerialNum(), doorDevice.getDeviceFactory(), true);

			if (resultBean != null && ResultCode.SUCCESS.getCode() == resultBean.getCode()) {
				hashMap.put("result_code", 1);
				hashMap.put("result_msg", "开门成功");
			} else {
				hashMap.put("result_msg", resultBean.getMsg());
			}

		} catch (Exception e) {
			log.error("异常", e);
			hashMap.put("result_msg", "后台程序异常");
		}
		return hashMap;
	}

	/**
	 * 功能描述: 一键开门
	 */
	@PostMapping(value = "/openDoor")
	public R openDoor(@RequestBody OpenDoorDto openDoorDto) {
//		Assert.notNull(openDoorDto.getMemberId(), "会员必传");
		Assert.notNull(openDoorDto.getResidentialId(), "所在小区必传");
		Assert.hasText(openDoorDto.getSerialNum(), "设备序列号必传");
		Assert.hasText(openDoorDto.getDeviceFactory(), "设备厂商必传");
		Assert.hasText(openDoorDto.getUserType(), "用户类型必传");
		DoorDeviceVO doorDeviceVO = this.doorDeviceClient.getBySerialNum(openDoorDto.getSerialNum());
		Assert.notNull(doorDeviceVO, "设备不存在");
		if (CommonConstant.UserFlag.GUEST_FLAG.getValue().equals(openDoorDto.getUserType())) {
			GuestRecord guestRecord = guestRecordClient.getById(openDoorDto.getGuestId());
			Assert.notNull(guestRecord, "访客记录不存在，请重新登记");
			return doorDeviceClient.remoteOpenDoor(guestRecord.getId().toString(), guestRecord.getGuestName(), CommonConstant.UserFlag.GUEST_FLAG.getValue(), openDoorDto.getSerialNum(), openDoorDto.getDeviceFactory(), true);
		} else if (CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue().equals(openDoorDto.getUserType())) {
			List<HouseUserVO> houseUserList = houseUserClient.getListByMember(openDoorDto.getMemberId(), openDoorDto.getResidentialId(), openDoorDto.getRoomId());
			Assert.notEmpty(houseUserList, "设备所在小区无住户");
			HouseUser one = houseUserList.get(0);
			return doorDeviceClient.remoteOpenDoor(one.getId().toString(), one.getName(), CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue(), openDoorDto.getSerialNum(), openDoorDto.getDeviceFactory(), true);
		} else {
			return R.fail("非法用户类型，无法开门");
		}
	}

}
