package com.sptg.gateway.controller;

import cn.hutool.core.bean.BeanUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.UserFlagConstant;
import com.sptg.common.core.util.Base64DecodeMultipartFileUtils;
import com.sptg.common.core.util.CommonUtil;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.device.api.constant.DeviceConstants;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.dto.ApplyUserDto;
import com.sptg.estate.api.dto.FaceChargeProjectResidentialUserDto;
import com.sptg.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.gateway.entity.DeviceApi;
import com.sptg.gateway.entity.NoticePushApi;
import com.sptg.gateway.entity.RoomFaceApi;
import com.sptg.gateway.util.DataCheck;
import com.sptg.gateway.util.JwtUtil;
import com.sptg.gateway.util.PojoToApi;
import com.sptg.gateway.util.SendSms;
import com.sptg.permissions.api.entity.*;
import com.sptg.permissions.api.feigns.*;
import com.sptg.permissions.api.utils.CustInfoVerifyUtil;
import com.sptg.statistics.api.entity.AppMemberLoginRecords;
import com.sptg.statistics.api.feigns.AppMemberLoginRecordsFeign;
import com.sptg.third.api.entity.qinlin.QLinUserDevice;
import com.sptg.third.api.feigns.qinlin.QLinFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * title: MemberController
 * package: com.sptg.gateway.controller
 * description: 会员管理控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/member")
public class MemberController {

    private final OrgFeign orgFeign;
    private final RedisTemplate<String, String> redisTemplate;
    private final MemberFeign memberFeign;
    private final MemberLoginStatusFeign memberLoginStatusFeign;
    private final ApplyUserFeign applyUserFeign;
    private final RoomFeign roomFeign;
    private final FastFileStorageClient fastFileStorageClient;
    private final UserFeign userFeign;
    private final MemberAndUserFeign memberAndUserFeign;
    private final DeviceFeign deviceFeign;
    private final AppMemberLoginRecordsFeign appMemberLoginRecordsFeign;
    private final ApiDockingConfFeign apiDockingConfFeign;
    private final NoticePushFeign noticePushFeign;
    private final VideoCallAccountFeign videoCallAccountFeign;
    private final ConfFeign confFeign;
    private final FaceChargeProjectResidentialUserFeign faceChargeProjectResidentialUserFeign;
    private final MemberDeviceFeign memberDeviceFeign;
    private final SmsFeign smsFeign;
    private final SmsTemplateFeign smsTemplateFeign;
    private final QLinFeign qLinFeign;
    private final CustInfoVerifyFeign custInfoVerifyFeign;
    private final FaceVerifyFeign faceVerifyFeign;

    /**
     * 密码加盐
     */
    private static final String PWD_SALT = "sptg";
    /**
     * 短信缓存名称
     */
    private final static String VERIFICATION_CODE = "verification:code";

    /**
     * String格式转时间格式
     */
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 功能描述: 获取验证码
     *
     * @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) {
        log.warn("============================小程序通小程序获取注册验证码(getSmsCode)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        try {
            String org_id = map.get("org_id");
            String tel = map.get("tel");
            String token = map.get("token");
            String play_type = map.get("play_type");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            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.setOrgId(Long.valueOf(org_id));
                member.setTel(tel);
                Member memberCheck = memberFeign.findMemberByTel(member);
                if (play_type.equals("1") && memberCheck == null) {
                    hashMap.put("result_msg", "该手机号尚未注册");
                    return hashMap;
                } else if (play_type.equals("2") && 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 + org_id;
                //  验证码存入缓存
                this.redisTemplate.opsForValue().set(key, verify_code);
                //  设置缓存有效期 20分钟
                this.redisTemplate.expire(key, 1200, TimeUnit.SECONDS);
                SmsTemplate smsTemplate = this.smsTemplateFeign.getByCode("register");
                String content = verify_code;
                if (smsTemplate != null && StringUtils.isNotBlank(smsTemplate.getContent())) {
                    content = smsTemplate.getContent().replace("${code}", verify_code);
                }
                SmsRecords smsRecords = new SmsRecords();
                smsRecords.setContent(content);
                smsRecords.setTel(tel);
                smsRecords.setCreateDate(new Date());
                if (this.smsFeign.insertSms(smsRecords).getData()) {
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "短信发送成功");
                } else {
                    hashMap.put("result_msg", "添加短信记录失败");
                }
            } else {
                hashMap.put("result_msg", response.getMessage());
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:会员注册--app
     *
     * @param map {
     *            name          :  姓名,
     *            tel           :  手机号码,
     *            tel_type      :  手机型号,
     *            verify_code   :  验证码,
     *            password      :  app登录密码 ,
     *            create_ip     :  注册地址
     *            org_id        :  机构授权org_id机构id
     *            token         :  对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/memberRegister")
    public Map<String, Object> memberRegister(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员注册(/app/member/memberRegister)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 tel_type = map.get("tel_type");
            String verify_code = map.get("verify_code");
            String password = map.get("password");
            String create_ip = map.get("create_ip");
            String org_id = map.get("org_id");
            String token = map.get("token");
            Organization organization = null;
            if (org_id == null) {
                hashMap.put("result_msg", "org_id不能为空");
                return hashMap;
            } else {
                organization = orgFeign.getOrgById(Long.valueOf(org_id));
                if (organization == null) {
                    hashMap.put("result_msg", "org_id没有对应的机构，没有权限");
                    return hashMap;
                }
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            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(password)) {
                hashMap.put("result_msg", "密码不能为空");
                return hashMap;
            } else {
                if (password.length() < 4 || password.length() > 6) {
                    hashMap.put("result_msg", "密码只能填写4-6位");
                    return hashMap;
                }
            }
            //获取存在redis上的验证码
            String key = VERIFICATION_CODE + tel + org_id;
            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.setOrgId(Long.valueOf(org_id));
            checkMember.setTel(tel);
            ResultBean<Boolean> checkTel = memberFeign.checkMemberTel(checkMember);
            ResultBean<Boolean> resultBean;
            //号码已经注册
            if (checkTel.getData()) {
                hashMap.put("result_msg", "手机号码已注册");
                return hashMap;
            } else {
                Member member = new Member();
                member.setName(name);
                member.setTel(tel);
                member.setTelType(tel_type);
                //create_type : 会员注册来源，0-小程序添加 1-后台添加  2-后台导入 3-app添加
                member.setCreateType(OperationConstant.THREE);
                member.setCreateDate(new Date());
                //密码md5加密
                member.setPassword(DigestUtils.md5Hex(PWD_SALT + password));
                member.setCreateIp(create_ip);
                member.setOrgId(Long.valueOf(org_id));
                member.setRootOrgId(organization.getRootOrgId());
                member.setOrgPosition(organization.getPosition());
                //新增会员--注册
                resultBean = this.memberFeign.memberRegister(member);
            }
            //注册成功
            if (resultBean.getCode().equals("200") && resultBean.getData()) {
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "注册成功");
            } else {
                hashMap.put("result_code", "注册失败");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:重置密码
     *
     * @param map {
     *            tel          :  手机号码,
     *            verify_code  :  验证码,
     *            password     :  app登录密码 ,
     *            org_id       :  机构授权org_id机构id
     *            token        :  对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/resetPassword")
    public Map<String, Object> resetPassword(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员重置密码(/app/member/resetPassword)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "密码重置失败");
        try {
            String tel = map.get("tel");
            String verify_code = map.get("verify_code");
            String password = map.get("password");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                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(password)) {
                hashMap.put("result_msg", "密码不能为空");
                return hashMap;
            }
            //获取存在redis上的验证码
            String key = VERIFICATION_CODE + tel + org_id;
            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.setOrgId(Long.valueOf(org_id));
            checkMember.setTel(tel);
            ResultBean<Boolean> checkTel = memberFeign.checkMemberTel(checkMember);
            //号码已经注册
            if (checkTel.getData()) {
                checkMember.setPassword(DigestUtils.md5Hex(PWD_SALT + password));
                //修改重置会员密码
                checkTel = this.memberFeign.updateMemberPassword(checkMember);
                if (checkTel.getData()) {
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "密码重置成功");
                }
            } else {
                hashMap.put("result_msg", "修改失败，手机号码未注册");
                return hashMap;
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:会员登录
     *
     * @param map {
     *            tel          : 手机号码,
     *            password     : app登录密码 ,
     *            org_id       : 机构授权org_id机构id
     *            token        : 对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/login")
    public Map<String, Object> login(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员登录(/app/member/login)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "登录失败");
        try {
            String tel = map.get("tel");
            String password = map.get("password");
            String org_id = map.get("org_id");
            String token = map.get("token");
            String mac_url = map.get("mac_url");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(tel)) {
                hashMap.put("result_msg", "手机号码不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(password)) {
                hashMap.put("result_msg", "密码不能为空");
                return hashMap;
            }
            //检测机构下面一个手机号码只能注册一个会员
            Member checkMember = new Member();
            checkMember.setOrgId(Long.valueOf(org_id));
            checkMember.setTel(tel);
            //根据电话号码查询当前机构会员
            Member member = memberFeign.findMemberByTel(checkMember);
            //号码已经注册
            if (member == null) {
                hashMap.put("result_msg", "账号不存在，请先注册");
                return hashMap;
            } else {
                if (Integer.valueOf(OperationConstant.TWO).equals(member.getEnable())) {
                    hashMap.put("result_msg", "该账号已禁用");
                    return hashMap;
                }
                //判断是否已存在房屋认证
                ApplyUserDto applyUserDto = new ApplyUserDto();
                applyUserDto.setMemberId(member.getId());
                boolean anyHousePass = false;
                MemberAndUser memAndUser = new MemberAndUser();
                memAndUser.setMemberId(member.getId());
                List<MemberAndUser> memAndUserList = this.memberAndUserFeign.getByCondition(memAndUser);
                if (memAndUserList != null && memAndUserList.size() > 0) {
                    anyHousePass = true;
                }
                password = DigestUtils.md5Hex(PWD_SALT + password);
                if (!password.equals(member.getPassword())) {
                    hashMap.put("result_msg", "密码不正确");
                } else {
                    //登录互踢-start
                    MemberLoginStatus checkMemberLoginStatus = new MemberLoginStatus();
                    checkMemberLoginStatus.setMemberId(tel);
                    MemberLoginStatus memberLoginStatus = memberLoginStatusFeign.checkMemberLoginStatus(checkMemberLoginStatus);
                    if (null == memberLoginStatus || null == memberLoginStatus.getId()) {
//                      往表写入生成session,tel,mac_url
                        checkMemberLoginStatus.setMacUrl(mac_url);
                        checkMemberLoginStatus.setSessionId(mac_url + CommonUtil.generateNumber(3));
                        Boolean add = memberLoginStatusFeign.addMemberLoginStatus(checkMemberLoginStatus);
                    } else if (memberLoginStatus.getMacUrl() != null && mac_url != null && !mac_url.equals(memberLoginStatus.getMacUrl())) {
                        //如果存在就对比mac_url,相同则不操作，不相同则替换mac_url和session
                        memberLoginStatus.setMacUrl(mac_url);
                        memberLoginStatus.setSessionId(mac_url + CommonUtil.generateNumber(3));
                        Boolean update = memberLoginStatusFeign.updateMemberLoginStatus(memberLoginStatus);
                    }
                    MemberLoginStatus afterLoginStatus = memberLoginStatusFeign.checkMemberLoginStatus(checkMemberLoginStatus);
                    hashMap.put("session_id", afterLoginStatus.getSessionId());
                    //登录互踢-end
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "登录成功");
                    //设置图片
                    if (StringUtils.isNotBlank(member.getHeadImage())) {
                        member.setHeadImage(confFeign.getFileServerHost() + member.getHeadImage());
                    }
                    hashMap.put("member", PojoToApi.memberToApi(member));
                    hashMap.put("anyHousePass", anyHousePass);
                    //统计---新增登录记录
                    AppMemberLoginRecords a = new AppMemberLoginRecords();
                    a.setMemberId(member.getId());
                    //登录类型 0-小程序登录 1-app登录
                    a.setLoginType(OperationConstant.ONE);
                    a.setLoginDate(new Date());
                    a.setRootOrgId(member.getRootOrgId());
                    a.setOrgPosition(member.getOrgPosition());
                    this.appMemberLoginRecordsFeign.addAppMemberLoginRecords(a);
                }
            }
            String tokenCode = jwtUtil.create(tel, mac_url);
            hashMap.put("token", tokenCode);
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }


    /**
     * 功能描述: 会员--认证成住户 | 新增家人
     *
     * @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 = "/authentication")
    public Map<String, Object> authentication(@RequestBody Map<String, String> map) {

//        HashMap<Object, Object> mapTemp = new HashMap<>();
//        BeanUtil.copyProperties(map, mapTemp);
//        mapTemp.remove("face_image_base64");
        log.warn("============================小程序住户认证申请(/app/member/authentication)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 image_uri = map.get("image_uri");
            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 name = map.get("name");
            String tel = map.get("tel");
            String room_id = map.get("room_id");
            String member_id = map.get("member_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            String create_type = map.get("create_type");
            String record_type = map.get("record_type");
            String face_image_base64 = map.get("face_image_base64");
            Room room;
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            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)) {
                CustInfoVerify custInfoVerify = new CustInfoVerify();
                custInfoVerify.setCustName(name);
                custInfoVerify.setCertNumber(id_card);
                custInfoVerify.setCertType("1");
                boolean verify = custInfoVerifyFeign.verify(custInfoVerify);
//                boolean verify = true;
                if(!verify){
                    hashMap.put("result_msg", "身份证验证失败，请填写正确的身份证信息");
                    return hashMap;
                }
            }
            if (StringUtils.isBlank(image_uri)) {
                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(tel)) {
                hashMap.put("result_msg", "电话号码不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(room_id)) {
                hashMap.put("result_msg", "房间id不能为空");
                return hashMap;
            } else {
                room = this.roomFeign.findRoomById(Long.valueOf(room_id));
                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;
            }

            ResultBean<Boolean> resultBean;
            UserDto userDto = new UserDto();
            //添加家人申请
            if (record_type.equals("1")) {
                MemberAndUser memberAndUser = new MemberAndUser();
                memberAndUser.setMemberId(Long.valueOf(member_id));
                memberAndUser.setRoomId(Long.valueOf(room_id));
                List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
                if (list == null || list.size() == 0) {
                    hashMap.put("result_msg", "用户不是该房屋成员");
                    return hashMap;
                } else {
                    User user = this.userFeign.findUserById(list.get(0).getUserId());
                    //不是业主身份
                    if (user.getType() != 0) {
                        hashMap.put("result_msg", "无权限在该房屋下添加成员");
                        return hashMap;
                    }
                }
            }

            //检测房间下的住户是否已经存在同名
            userDto.setName(name);
            userDto.setRoomId(Long.valueOf(room_id));
            resultBean = this.userFeign.checkByNameAndRoomId(userDto);
            if (resultBean.getData()) {
                hashMap.put("result_msg", "房屋下已经存在名字为" + name + "的住户,请勿重复添加");
                return hashMap;
            }
            UserDto uDto = new UserDto();
            uDto.setIdCard(id_card);
            User userByCondition = this.userFeign.findUserByCondition(uDto);
            if (userByCondition != null) {
                hashMap.put("result_msg", "该身份证号已被名字为" + name + "的住户使用,请更换身份证号再试");
                return hashMap;
            }
            //一个房间下面同一个名字只能一条待审核的申请记录
            ApplyUser applyUser = new ApplyUser();
            //有bug这个地方
            applyUser.setName(name);
            applyUser.setRoomId(Long.valueOf(room_id));
            resultBean = this.applyUserFeign.checkByNameAndRoomId(applyUser);
            if (resultBean.getData()) {
                hashMap.put("result_msg", "名字" + name + "已有一条申请记录处于待审核状态，请勿重复提交，等待物业审核");
                return hashMap;
            } else {
                //上传了人脸
//                MultipartFile multipartFile  = Base64DecodeMultipartFileUtils.base64ToMultipart(Base64DecodeMultipartFileUtils.imageFormatToPng(face_image_base64));
                //图片上传
//                StorePath storePath = fastFileStorageClient.uploadFile(
//                        multipartFile.getInputStream(),multipartFile.getSize(),
//                        FilenameUtils.getExtension(multipartFile.getOriginalFilename()),null);
                String faceUrl = confFeign.getFileServerHost() + image_uri;
//                ResultBean resultBean1 = DataCheck.uploadFace(face_image_base64, applyUser, this.fastFileStorageClient, confFeign);
                ResultBean resultBean1 = faceVerifyFeign.verify(faceUrl);
                if (resultBean1 != null){ //表示检测出来问题，不通过
                    hashMap.put("result_msg", resultBean1.getMsg());
                }
                applyUser.setImageUri(image_uri);
                //图片的md5值
                String md5Hex = DigestUtils.md5Hex(face_code);
                applyUser.setFaceCode(md5Hex);
                applyUser.setType(Integer.valueOf(type));
                applyUser.setIdCard(id_card);
                applyUser.setSex(Integer.valueOf(sex));
                applyUser.setNationality(Integer.valueOf(nationality));
                if (StringUtils.isNotBlank(image_uri)) {
                    applyUser.setImageUri(image_uri);
                    applyUser.setFaceCode(face_code);
                }
                if (StringUtils.isNotBlank(passport_img_uri)) {
                    applyUser.setPassportImgUri(passport_img_uri);
                }
                if (StringUtils.isNotBlank(entry_img_uri)) {
                    applyUser.setEntryImgUri(entry_img_uri);
                }
                applyUser.setTel(tel);
                //根据姓名和手机号先查找该房屋成员是否已经有memberId，若有使用该成员自己的memberId,没有则使用该业主的memberId
                Member member = new Member();
                member.setTel(tel);
                member.setName(name);
                member.setState(2);
                Member isExist = this.memberFeign.getMember(member);
                if(null != isExist&&record_type.equals("1")){//添加家人时该家人若有memberId，则使用该家人自己的memberId
                    applyUser.setMemberId(isExist.getId());
                }else if(null ==isExist && record_type.equals("1")) {//添加家人时该家人没有memberId，使用业主memberId
                    applyUser.setMemberId(Long.valueOf(member_id));
                }else {//业务提交审核
                    applyUser.setMemberId(Long.valueOf(member_id));

                }
                applyUser.setCheckState(OperationConstant.ZERO);

                applyUser.setOrgPosition(room.getOrgPosition());
                applyUser.setEstatePosition(room.getEstatePosition());
                applyUser.setRootOrgId(room.getRootOrgId());

                applyUser.setCreateType(Integer.valueOf(create_type));
                applyUser.setCreateDate(new Date());
                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) {
                    resultBean = this.applyUserFeign.authentication(applyUser);
                    //申请成功
                    if (resultBean.getCode().equals("200") && resultBean.getData()) {
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "认证申请成功，请等待物业审核");
                    } else {
                        hashMap.put("result_msg", "认证申请失败");
                    }
                    //添加家人
                } else if (applyUser.getRecordType() == 1) {
                    ResultBean<Long> userResultBean = this.applyUserFeign.addApplyUserReturnUser(applyUser);
                    //申请成功
                    if (userResultBean.getCode().equals("200") && null != userResultBean.getData()) {
                        //把家人的审核状态改成审核通过
                        Long id = userResultBean.getData();
                        log.warn("添加家人成功返回添加记录的id：{}", id);
                        ApplyUser applyUser1 = new ApplyUser();
                        applyUser1.setId(id);
                        applyUser1.setCheckState(OperationConstant.ONE);
                        ResultBean<Boolean> bean = this.applyUserFeign.updateCheckState(applyUser1);
                        if (bean.getMsg().equals("success")) {
                            hashMap.put("result_code", 1);
                            hashMap.put("result_msg", "提交添加家人申请成功");
                        } else {
                            hashMap.put("result_msg", "提交添加家人申请失败");
                        }
                    } else {
                        hashMap.put("result_msg", "提交添加家人申请失败");
                    }
                } else {
                    hashMap.put("result_msg", "method_type的值不合法：" + record_type);
                }

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

    /**
     * 功能描述: 通过会员id获取授权的设备列表
     *
     * @param map {
     *            member_id     :   会员id,
     *            org_id        :   机构授权org_id，机构id
     *            token         :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/getAuthDeviceByMemberId")
    public Map<String, Object> getAuthDeviceByMemberId(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员通过会员ID获取开门设备列表(/app/member/getAuthDeviceByMemberId)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 org_id = map.get("org_id");
            String token = map.get("token");
//            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
//                return hashMap;
//            }
//            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
//                return hashMap;
//            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            /*MemberDevice memberDevice = new MemberDevice();
            memberDevice.setMemberId(Long.parseLong(member_id));
            List<MemberDevice> memberDeviceList = this.memberDeviceFeign.getListByMemberId(memberDevice);
            hashMap.put("result_code", 1);
            if (memberDeviceList.size() == 0){
                hashMap.put("result_msg", "没有相关数据");
            }else {
                List<Long> deviceIds = new ArrayList<>();
                for (MemberDevice item : memberDeviceList){
                    deviceIds.add(item.getDeviceId());
                }
                List<Device> deviceList = this.deviceFeign.getListByIds(deviceIds);
                List<DeviceApi> collect = new ArrayList<>();
                DeviceApi d;
                for (Device device : deviceList){
                    d = PojoToApi.deviceToApi(device);
                    ResultBean<VideoCallAccount> resultBean = videoCallAccountFeign.getDeviceCallAccount(device.getSerialNumber());
                    if (resultBean.getCode().equals("200") && resultBean.getData() != null) {
                        d.setAccountId(resultBean.getData().getAccountId());
                    }
                    collect.add(d);
                }
                hashMap.put("list", collect);
                hashMap.put("result_msg", "查询数据成功");
            }*/
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                List<Long> userIds = new ArrayList<>();
                for (MemberAndUser mau : list) {
                    userIds.add(mau.getUserId());
                }
                List<User> users = this.userFeign.getListByUserId(userIds);
                List<DeviceApi> collect = new ArrayList<>();
                DeviceApi d;
                for (User user : users) {
                    List<Device> devices = this.deviceFeign.getListByEstateUser(user.getResidentialId(), user.getUnitId());
                    MemberDevice memberDevice = new MemberDevice();
                    memberDevice.setMemberId(Long.parseLong(member_id));
                    List<MemberDevice> memberDeviceList = this.memberDeviceFeign.getListByMemberId(memberDevice);
                    for (Device device : devices) {
                        if (memberDeviceList != null && memberDeviceList.size() > 0) {
                            long count = memberDeviceList.stream().filter(md -> md.getDeviceId().equals(device.getId())).count();
                            if (count > 0) {
                                continue;
                            } else {
                                boolean r = false;
                                for (DeviceApi deviceApi : collect) {
                                    //预防会员关联的多个住户在同一个单元下面
                                    if (deviceApi.getId().equals(device.getId())) {
                                        r = true;
                                    }
                                }
                                if (!r) {
                                    d = PojoToApi.deviceToApi(device);
                                    ResultBean<VideoCallAccount> resultBean = videoCallAccountFeign.getDeviceCallAccount(device.getSerialNumber());
                                    if (resultBean.getCode().equals("200") && resultBean.getData() != null) {
                                        d.setAccountId(resultBean.getData().getAccountId());
                                    }
                                    collect.add(d);
                                }
                            }
                        } else {
                            boolean r = false;
                            for (DeviceApi deviceApi : collect) {
                                //预防会员关联的多个住户在同一个单元下面
                                if (deviceApi.getId().equals(device.getId())) {
                                    r = true;
                                }
                            }
                            if (!r) {
                                d = PojoToApi.deviceToApi(device);
                                ResultBean<VideoCallAccount> resultBean = videoCallAccountFeign.getDeviceCallAccount(device.getSerialNumber());
                                if (resultBean.getCode().equals("200") && resultBean.getData() != null) {
                                    d.setAccountId(resultBean.getData().getAccountId());
                                }
                                collect.add(d);
                            }
                        }
                    }
                }
                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;
    }

    /**
     * 功能描述: 一键开门
     *
     * @param map {
     *            device_id     :   设备id
     *            member_id     :   会员id,
     *            org_id        :   机构授权org_id，机构id
     *            token         :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     */
    @PostMapping(value = "/openDoor")
    public Map<String, Object> openDoor(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员远程开门(/app/member/getAuthDeviceByMemberId)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 org_id = map.get("org_id");
        String token = map.get("token");
        try {
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            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;
            }

            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setMemberId(Long.valueOf(member_id));
            List<ApplyUser> applyUserList = this.applyUserFeign.getApplyUserByCondition(applyUserDto);
            if (applyUserList == null || applyUserList.size() == 0){
                hashMap.put("result_msg", "请先提交认证申请！");
                return hashMap;
            }else{
                ApplyUser applyUser = applyUserList.get(0);
                if (!applyUser.getCheckState().equals(1)){
                    hashMap.put("result_msg", "审核通过才能使用该功能！");
                    return hashMap;
                }
            }

            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                List<Long> userIds = new ArrayList<>();
                for (MemberAndUser mau : list) {
                    userIds.add(mau.getUserId());
                }
                List<User> users = this.userFeign.getListByUserId(userIds);
                List<Device> collect = new ArrayList<>();
                for (User user : users) {
                    List<Device> devices = this.deviceFeign.getListByEstateUser(user.getResidentialId(), user.getUnitId());
                    collect.addAll(devices);
                }
                boolean check = false;
                Long deviceId = Long.valueOf(device_id);
                Device device = null;
//                Long userId = null;
                User u = null;
                for (Device d : collect) {
                    if (d.getId().equals(deviceId)) {
                        device = d;
                        for (User user : users) {
                            if (user.getOrgPosition().startsWith(device.getOrgPosition())) {
                                u = user;
                                check = true;
                                break;
                            }
                        }
                        break;
                    }
                }
                if (!check) {
                    hashMap.put("result_msg", "会员没有开启该设备的权限");
                    return hashMap;
                } else {
                    if(StringUtils.isNotBlank(is_guest)){//访客开门
                        if(is_guest.equals("1")){
                            if(StringUtils.isNotBlank(phone)){
                                device.setUserId(UserFlagConstant.GUEST_FLAG+phone);
                            }else {
                                hashMap.put("result_msg","访客开门手机号码必传");
                                return hashMap;
                            }
                        }else {
                            hashMap.put("result_msg","访客开门is_guest必须是字符串1");
                            return hashMap;
                        }
                    }else{
                        device.setUserId(UserFlagConstant.USER_NUMBER_FLAG + u.getId());
                    }

                    //日志新添加的字段，小区、单元、房间、用户名
                    device.setXqName(u.getResidentialName());
                    device.setDyName(u.getUnitName());
                    String deviceFactory = device.getDeviceFactory();
                    ResultBean<Boolean> resultBean = null;
                    if (deviceFactory.equals(DeviceConstants.DEVICE_FACTORY_QINLIN)) {
                        QLinUserDevice qLinUserDevice = new QLinUserDevice();
                        qLinUserDevice.setUserId(device.getUserId());
                        qLinUserDevice.setDeviceId(device.getSerialNumber());
                        ResultBean<String> qLResultBean = this.qLinFeign.remoteOpenDoor(qLinUserDevice);
                        resultBean = new ResultBean<>(qLResultBean.getCode(), qLResultBean.getMsg());
                    } else {
                        resultBean = this.deviceFeign.openDoor(device);
                    }
                    if (ResultEnum.SUCCESS.getCode().equals(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;
    }

    /**
     * 功能描述:获取会员信息 By 会员id
     *
     * @param map {
     *            member_id        :   会员id,
     *            org_id           :   机构授权org_id机构id
     *            token            :   对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/getMemberByMemberId")
    public Map<String, Object> getMemberByMemberId(@RequestBody Map<String, String> map) {
        log.warn("============================小程序通过会员ID获取会员信息(/app/member/getMemberByMemberId)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            Member member = memberFeign.getMemberByMemberId(Long.valueOf(member_id));
            //获取会员成功
            if (member != null) {
                member.setHeadImage(confFeign.getFileServerHost() + member.getHeadImage());
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "获取会员成功");
                hashMap.put("member", PojoToApi.memberToApi(member));
                //统计---新增登录记录
                AppMemberLoginRecords a = new AppMemberLoginRecords();
                a.setMemberId(member.getId());
                a.setLoginDate(new Date());
                //登录类型 0-小程序登录 1-app登录
                a.setLoginType(OperationConstant.ONE);
                a.setRootOrgId(member.getRootOrgId());
                a.setOrgPosition(member.getOrgPosition());
                this.appMemberLoginRecordsFeign.addAppMemberLoginRecords(a);
            } else {
                hashMap.put("result_msg", "未查询到相关会员");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:会员注册--特殊注册接口
     *
     * @param map {
     *            name         :   姓名,
     *            tel          :   手机号码,
     *            org_id       :   机构授权org_id机构id
     *            token        :   对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/memberRegisterNew")
    public Map<String, Object> memberRegisterNew(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员特殊注册(/app/member/memberRegisterNew)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "注册失败");
        try {
            String name = map.get("name");
            String tel = map.get("tel");
            String org_id = map.get("org_id");
            String token = map.get("token");
            Organization organization = null;
            if (org_id == null) {
                hashMap.put("result_msg", "org_id不能为空");
                return hashMap;
            } else {
                organization = orgFeign.getOrgById(Long.valueOf(org_id));
                if (organization == null) {
                    hashMap.put("result_msg", "org_id没有对应的机构，没有权限");
                    return hashMap;
                }
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(name)) {
                hashMap.put("result_msg", "姓名不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(tel)) {
                hashMap.put("result_msg", "手机号码不能为空");
                return hashMap;
            }
            //根据电话号码查询会员
            Member condition = new Member();
            condition.setOrgId(Long.valueOf(org_id));
            condition.setTel(tel);
            Member member = this.memberFeign.findMemberByTel(condition);
            //号码已经注册
            if (member != null) {
                hashMap.put("result_msg", "手机号码已注册");
                hashMap.put("result_code", -1);
                hashMap.put("member", PojoToApi.memberToApi(member));
                return hashMap;
            } else {//注册新会员
                member = new Member();
                member.setName(name);
                member.setTel(tel);
                //create_type : 会员注册来源，0-小程序注册 1-app注册,
                member.setCreateType(OperationConstant.ONE);
                member.setCreateDate(new Date());
                member.setOrgId(Long.valueOf(org_id));
                member.setRootOrgId(organization.getRootOrgId());
                member.setOrgPosition(organization.getPosition());
                //新增会员--注册
                ResultBean<Member> resultBean = this.memberFeign.memberRegisterNew(member);
                //注册成功
                if (resultBean.getData() != null) {
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "注册成功");
                    hashMap.put("member", PojoToApi.memberToApi(member));
                } else {
                    hashMap.put("result_code", "注册失败");
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:获取公告列表
     *
     * @param map {
     *            member_id         :   会员id,
     *            pageNum       :   分页页数
     *            pageSize      :   分页大小
     *            push_target       :   发布目标渠道  1-app 2-小程序,
     *            org_id            :   机构授权org_id机构id
     *            token             :   对接令牌
     *            }
     * @return
     */
    @PostMapping(value = "/getNotices")
    public Map<String, Object> getNotices(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员获取公告列表(/app/member/getNotices)请求数据==============================");
        log.warn(JsonUtils.objectToJson(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 pageNum = map.get("pageNum");
            String pageSize = map.get("pageSize");
            String push_target = map.get("push_target");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(member_id)) {
                hashMap.put("result_msg", "会员id不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(push_target)) {
                hashMap.put("result_msg", "push_target字段不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageNum)) {
                hashMap.put("result_msg", "分页页码不能为空");
                return hashMap;
            }
            if (StringUtils.isEmpty(pageSize)) {
                hashMap.put("result_msg", "分页大小不能为空");
                return hashMap;
            }
            MemberAndUser memberAndUser = new MemberAndUser();
            memberAndUser.setMemberId(Long.valueOf(member_id));
            List<MemberAndUser> list = this.memberAndUserFeign.getByCondition(memberAndUser);
            if (list == null || list.size() == 0) {
                hashMap.put("result_msg", "没有查询到与会员对应的住户信息");
                return hashMap;
            } else {
                List<Long> userIds = new ArrayList<>();
                for (MemberAndUser mau : list) {
                    userIds.add(mau.getUserId());
                }
                List<User> users = this.userFeign.getListByUserId(userIds);
                if (users != null) {
                    UserDto userDto = new UserDto();
                    userDto.setList(users);
                    userDto.setPushTarget(push_target);
                    userDto.setPage(new Page<>());
                    userDto.getPage().setSize(Integer.parseInt(pageSize));
                    userDto.getPage().setCurrent(Integer.parseInt(pageNum));
                    List<NoticePush> noticePushes = this.noticePushFeign.getListByUser(userDto);
                    hashMap.put("result_code", 1);
                    List<NoticePushApi> noticePushApis = new ArrayList<>();
                    if (noticePushes != null && noticePushes.size() > 0) {
                        for (NoticePush n : noticePushes) {
                            noticePushApis.add(PojoToApi.noticePushToApi(n));
                        }
                    }
                    hashMap.put("list", noticePushApis);
                    if (noticePushes != null && noticePushes.size() == 0) {
                        hashMap.put("result_msg", "没有查询到相关数据");
                    } else {
                        hashMap.put("result_msg", "查询数据成功");
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    @PostMapping(value = "/getRoomFaceInfo")
    public Map<String, Object> getRoomFaceInfo(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员获取房屋信息(/app/member/getRoomFaceInfo)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        RoomFaceApi roomFaceApi = new RoomFaceApi();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询数据失败");
        try {
            String member_id = map.get("member_id");
            String idcard = map.get("idcard");
            String user_id = map.get("user_id");
            String room_id = map.get("room_id");
            String org_id = map.get("org_id");
            String token = map.get("token");
            String phone = map.get("phone");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
//            if (StringUtils.isBlank(member_id)) {
//                hashMap.put("result_msg", "会员id不能为空");
//                return hashMap;
//            }
            if (StringUtils.isBlank(user_id)) {
                hashMap.put("result_msg", "住户id不能为空");
                return hashMap;
            }
//            if (StringUtils.isBlank(idcard)) {
//                hashMap.put("result_msg", "住户身份证号不能为空");
//                return hashMap;
//            }
            if (StringUtils.isBlank(room_id)) {
                hashMap.put("result_msg", "房间id不能为空");
                return hashMap;
            }

            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setRoomId(Long.valueOf(room_id));
            if (StringUtils.isNotBlank(member_id)) {
                applyUserDto.setMemberId(Long.valueOf(member_id));
            }
            if (StringUtils.isNotBlank(idcard)) {
                applyUserDto.setIdCard(idcard);
            }
            if (StringUtils.isNotBlank(phone)) {
                applyUserDto.setTel(phone);
            }
            if (StringUtils.isNotBlank(user_id)) {
                applyUserDto.setUserId(Long.valueOf(user_id));
            }
//            applyUserDto.setCheckState(0);
            //最新一条申请记录
            List<ApplyUser> lastApplyUsers = this.applyUserFeign.getApplyUserByCondition(applyUserDto);
            User user = this.userFeign.findUserById(Long.valueOf(user_id));
            Room room = this.roomFeign.findRoomById(Long.valueOf(room_id));
            if (user != null && room != null) {
                //以申请记录的状态和人脸为主，因为申请记录可能有更改
                if (lastApplyUsers == null || lastApplyUsers.size() == 0) {
                    //无申请或申请无人脸 = 未上传
                    if (StringUtils.isBlank(member_id) || user.getCreateType() == OperationConstant.ONE) {
                        //特殊处理：业主添加家人，直接通过，此情况就以user表的人脸信息为主
                        // 或者是后台添加的，就以住户表user信息为主
                        if (StringUtils.isNotBlank(user.getImageUri())) {
                            //有人脸
                            roomFaceApi.setFaceEnable(user.getFaceEnable());
                            roomFaceApi.setFaceUrl(user.getImageUri());
                            roomFaceApi.setCheckState(1);
                        } else {
                            //无人脸 = 未上传
                            roomFaceApi.setCheckState(0);
                        }
                    } else {
                        //无申请或申请无人脸 = 未上传
                        roomFaceApi.setCheckState(0);
                    }
                } else {
                    //有申请记录
                    ApplyUser applyUser = lastApplyUsers.get(0);
                    if (StringUtils.isNotBlank(user.getImageUri())) {
                        //申请有人脸
                        roomFaceApi.setFaceEnable(user.getFaceEnable());
                        roomFaceApi.setCheckState(1);
                    } else {
                        //申请无人脸 = 未上传
                        roomFaceApi.setCheckState(0);
                    }
                    roomFaceApi.setFaceUrl(applyUser.getImageUri());
//                   roomFaceApi.setCheckState(applyUser.getCheckState());
                    roomFaceApi.setCheckOpinion(applyUser.getCheckOpinion());
                }
                //查询该用户是否已经开通过试用功能
                FaceChargeProjectResidentialUserDto dto = new FaceChargeProjectResidentialUserDto();
                dto.setUserId(Long.valueOf(user_id));
                dto.setTypeItem(11);
                ResultBean<FaceChargeProjectResidentialUser> bean = faceChargeProjectResidentialUserFeign.findFaceChargeProjectResidentialUser(dto);
                if (bean.getData() != null) {
                    roomFaceApi.setOpenTry(true);
                } else {
                    roomFaceApi.setOpenTry(false);
                }
                //查看会员所在小区是否可以激活人脸
                List<Device> deviceList = deviceFeign.getListByXqId(user.getResidentialId());
                if (deviceList != null && deviceList.size() > 0) {
                    for (Device device : deviceList) {
                        if (OperationConstant.ONE == device.getHaveFace()) {
                            roomFaceApi.setCanActiveFace(true);
                            break;
                        } else {
                            roomFaceApi.setCanActiveFace(false);
                            continue;
                        }
                    }
                } else {
                    roomFaceApi.setCanActiveFace(false);
                }
                roomFaceApi.setUserId(user.getId());
                roomFaceApi.setResidentialId(room.getResidentialId());
                roomFaceApi.setResidentialName(room.getResidentialName());
                roomFaceApi.setUnitId(room.getUnitId());
                roomFaceApi.setUnitName(room.getUnitName());
                roomFaceApi.setRoomName(room.getName());
                roomFaceApi.setId(room.getId());
                roomFaceApi.setHouseNumber(room.getHouseNumber());
                roomFaceApi.setFaceBeginDate(user.getFaceBeginDate());
                roomFaceApi.setFaceEndDate(user.getFaceEndDate());

                hashMap.put("roomFace", roomFaceApi);
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "查询数据成功");
            } else {
                hashMap.put("result_msg", "没有相关数据");
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }

        return hashMap;
    }

    /**
     * 功能描述：更换手机号
     *
     * @param map {
     *            password     :   app登录密码
     *            old_tel      :   旧手机号码
     *            new_tel      :   新手机号码
     *            verify_code  :   验证码
     *            org_id       :   机构授权org_id机构id
     *            token        :   对接令牌
     *            }
     * @return map
     */
    @PostMapping(value = "/changeTel")
    public Map<String, Object> changeTel(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员更换手机(/app/member/changeTel)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        //result_code:0-失败  1-成功
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "更换绑定手机失败");
        try {
            String password = map.get("password");
            String old_tel = map.get("old_tel");
            String new_tel = map.get("new_tel");
            String verify_code = map.get("verify_code");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            if (StringUtils.isBlank(password)) {
                hashMap.put("result_msg", "密码不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(old_tel)) {
                hashMap.put("result_msg", "旧手机号不能为空");
                return hashMap;
            }
            if (StringUtils.isBlank(new_tel)) {
                hashMap.put("result_msg", "新手机号不能为空");
                return hashMap;
            }
            Member telMember = new Member();
            telMember.setTel(old_tel);
            telMember.setOrgId(Long.valueOf(org_id));
            Member member = this.memberFeign.findMemberByTel(telMember);
            if (member == null) {
                hashMap.put("result_msg", "旧手机号码尚未绑定用户");
                return hashMap;
            } else {
                password = DigestUtils.md5Hex(PWD_SALT + password);
                if (!member.getPassword().equals(password)) {
                    hashMap.put("result_msg", "密码不正确");
                    return hashMap;
                }
            }
            //获取存在redis上的验证码
            String key = VERIFICATION_CODE + new_tel + org_id;
            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.setOrgId(Long.valueOf(org_id));
            checkMember.setTel(new_tel);
            ResultBean<Boolean> checkTel = memberFeign.checkMemberTel(checkMember);
            //新手机号码已经注册
            if (checkTel.getData()) {
                hashMap.put("result_msg", "绑定失败，新手机号码已绑定另外一个用户 ");
                return hashMap;
            } else {
                member.setTel(new_tel);
                if (this.memberFeign.changeTel(member).getData()) {
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "更换手机绑定成功");
                }
                ;
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述：更新会员信息
     *
     * @param map {
     *            member_id     :   用户id
     *            name          :   姓名
     *            sex           :   性别
     *            head_image_base64    :   头像
     *            birthday      :   生日
     *            id_card       :   身份证号码
     *            org_id        :   机构授权org_id机构id
     *            token         :   对接令牌
     *            }
     * @return map
     */
    @PostMapping(value = "/updateMember")
    public Map<String, Object> updateMember(@RequestBody Map<String, String> map) {
        log.warn("============================小程序会员更新(/app/member/updateMember)请求数据==============================");
        log.warn(JsonUtils.objectToJson(map));
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "修改失败");
        try {
            String member_id = map.get("member_id");
            String name = map.get("name");
            String sex = map.get("sex");
            String head_image_base64 = map.get("head_image_base64");
            String birthday = map.get("birthday");
            String id_card = map.get("id_card");
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (StringUtils.isBlank(name) && StringUtils.isBlank(sex) && StringUtils.isBlank(head_image_base64)
                    && StringUtils.isBlank(birthday) && StringUtils.isBlank(id_card)) {
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "无修改项");
            }
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if (DataCheck.checkToken(hashMap, org_id, token, apiDockingConfFeign)) {
                return hashMap;
            }
            Member member = this.memberFeign.getMemberByMemberId(Long.valueOf(member_id));
            if (member == null) {
                return hashMap;
            } else {
                //名称
                member.setName(name);
                //性别
                member.setSex(Integer.parseInt(sex));
                if (StringUtils.isNotBlank(birthday)) {
                    //生日日期String转换Date
                    try {
                        Date birDay = sdf.parse(birthday);
                        member.setBirthday(birDay);
                    } catch (Exception e) {
                        log.error("时间转换异常", e);
                        hashMap.put("result_msg", "后台程序异常");
                    }
                }
                //身份证
                member.setIdcard(id_card);

                if (StringUtils.isNotBlank(head_image_base64)) {
                    //上传头像
                    DataCheck.uploadHeadImage(head_image_base64, member, this.fastFileStorageClient);
                }
                if (this.memberFeign.updateMember(member).getData()) {
                    member.setHeadImage(confFeign.getFileServerHost() + member.getHeadImage());
                    hashMap.put("result_code", 1);
                    hashMap.put("result_msg", "修改信息成功");
                    hashMap.put("member", PojoToApi.memberToApi(member));
                }
            }
        } catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 判断该会员下是否有家人
     * @param map
     * @return
     */
    @PostMapping(value = "/hasFamily")
    public Map<String, Object> hasFamily(@RequestBody Map<String, String> map) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "查询失败");
        try{
            String memberId = map.get("member_id");
            String residentialId = map.get("residential_id");
            if (StringUtils.isBlank(memberId)) {
                hashMap.put("result_msg", "会员必传");
                return hashMap;
            }
            if (StringUtils.isBlank(residentialId)) {
                hashMap.put("result_msg", "小区必传");
                return hashMap;
            }
            Member member = memberFeign.getMemberByMemberId(Long.valueOf(memberId));
            if(member == null){
                hashMap.put("result_msg", "会员不存在");
                return hashMap;
            }
            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setMemberId(Long.valueOf(memberId));
            applyUserDto.setResidentialId(Long.valueOf(residentialId));
            //查询出该会员在该小区下的所有认证和添加家人申请记录。
            List<ApplyUser> applyUserList = applyUserFeign.getApplyUserByCondition(applyUserDto);
            if(applyUserList != null && applyUserList.size() > 1){
                List<ApplyUser> passApplyUserList = applyUserList.stream().filter(applyUser -> applyUser.getCheckState() == 1).collect(Collectors.toList());
                if(passApplyUserList.size() > 1){
                    hashMap.put("hasFamily", true);
                }else{
                    hashMap.put("hasFamily", false);
                }
                return hashMap;
            }else{
                hashMap.put("hasFamily", false);
                return hashMap;
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
            return hashMap;
        }
    }

    /**
     * 会员注销
     * @param map
     * @return
     */
    @PostMapping(value = "/logout")
    public Map<String, Object> logout(@RequestBody Map<String, String> map) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "注销失败");

        try{
            String memberId = map.get("member_id");
            String residentialId = map.get("residential_id");
            if (StringUtils.isBlank(memberId)) {
                hashMap.put("result_msg", "会员必传");
                return hashMap;
            }
            if (StringUtils.isBlank(residentialId)) {
                hashMap.put("result_msg", "小区必传");
                return hashMap;
            }
            ApplyUserDto applyUserDto = new ApplyUserDto();
            applyUserDto.setMemberId(Long.valueOf(memberId));
            applyUserDto.setResidentialId(Long.valueOf(residentialId));
            //查询出该会员在该小区下的所有认证和添加家人申请记录。
            List<ApplyUser> applyUserList = applyUserFeign.getApplyUserByCondition(applyUserDto);
            if(applyUserList != null && applyUserList.size() > 0){
                List<ApplyUser> passApplyUserList = applyUserList.stream().filter(applyUser -> applyUser.getCheckState() == 1).collect(Collectors.toList());
                if(applyUserList.size() == 1){
                    if(passApplyUserList.size() == 1){
                        //删除applyUser
                        applyUserFeign.deleteApplyUser(applyUserDto);
                        UserDto userDto = new UserDto();
                        ApplyUser applyUser = passApplyUserList.get(0);
                        userDto.setId(applyUser.getUserId());
                        userFeign.deleteUser(userDto);
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "注销成功");
                        return hashMap;
                    }else{
                        //删除applyUser
                        applyUserFeign.deleteApplyUser(applyUserDto);
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "注销成功");
                        return hashMap;
                    }
                }else {
                    if(passApplyUserList.size() > 1){
                        hashMap.put("result_msg", "请先删除该小区下已添加的家人");
                        return hashMap;
                    }else{
                        //删除applyUser
                        applyUserFeign.deleteApplyUser(applyUserDto);
                        UserDto userDto = new UserDto();
                        ApplyUser applyUser = passApplyUserList.get(0);
                        userDto.setId(applyUser.getUserId());
                        userFeign.deleteUser(userDto);
                        hashMap.put("result_code", 1);
                        hashMap.put("result_msg", "注销成功");
                        return hashMap;
                    }
                }
            }else{
                ResultBean<Boolean> deleteResult = memberFeign.delete(Long.valueOf(memberId));
                if(deleteResult.getData()){
                    hashMap.put("result_msg", "注销成功");
                }
                return hashMap;
            }
        }catch (Exception e) {
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
            return hashMap;
        }
    }

    /**
     * 功能描述: base64文件上传
     * @param map {
     *            base_64_str           :   文件的base64字符串
     *            is_need_md5           :   是否需要md5值
     *            org_id                :   机构授权org_id，机构id,
     *            token                 :   对接令牌
     *            }
     * @return ResultBean<hashMap> 返回结果
     *
     */
    /*@RequestMapping(value = "/uploadBase64File")
    public Map<String,Object> uploadBase64File(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "文件上传失败");
        try {
            String org_id = map.get("org_id");
            String token = map.get("token");
            if (DataCheck.checkOrgId(hashMap, org_id, orgFeign)) {
                return hashMap;
            }
            if(DataCheck.checkToken(hashMap, org_id, token,apiDockingConfFeign)){
                return hashMap;
            }
            String is_need_md5 = map.get("is_need_md5");
            if(StringUtils.isBlank(is_need_md5)){
                hashMap.put("result_msg", "is_need_md5不能为空");
                return hashMap;
            }
            String base_64_str = map.get("base_64_str");
            if(StringUtils.isBlank(base_64_str)){
                hashMap.put("result_msg", "base_64_str不能为空");
                return hashMap;
            }
            MultipartFile multipartFile  = Base64DecodeMultipartFileUtils.base64ToMultipart(base_64_str);
            *//*
     * 返回的对象storePath
     *  storePath.fullPath = "group1/M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
     *  storePath.group = "group1"
     *  storePath.path = "M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
     *//*
            StorePath storePath = fastFileStorageClient.uploadFile(
                    multipartFile.getInputStream(),multipartFile.getSize(),
                    FilenameUtils.getExtension(multipartFile.getOriginalFilename()),null);
            if(storePath!=null){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "文件上传成功");
                hashMap.put("uri", storePath.getFullPath());
                hashMap.put("showUri", confFeign.getFileServerHost() + storePath.getFullPath());
                if(Boolean.parseBoolean(is_need_md5)){
                    String md5Hex = DigestUtils.md5Hex(multipartFile.getInputStream());
                    hashMap.put("md5Hex", md5Hex);
                }
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }*/

}
