package com.sptg.estate.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.sptg.common.core.beans.PageBean;
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.entity.DispatchTask;
import com.sptg.common.core.util.CommonUtil;
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.UserDto;
import com.sptg.estate.api.dto.UserInfoDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.MemberDeviceFeign;
import com.sptg.estate.biz.mapper.ApplyUserMapper;
import com.sptg.estate.biz.service.*;
import com.sptg.permissions.api.entity.CustInfoVerify;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.CustInfoVerifyFeign;
import com.sptg.permissions.api.feigns.SysApiLogFeign;
import com.sptg.permissions.api.utils.CustInfoVerifyUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * title: ApplyUserServicelmpl
 * package: com.sptg.estate.biz.security
 * description: 住户申请 服务层实现类
 */
@Service
@AllArgsConstructor
public class ApplyUserServiceImpl extends ServiceImpl<ApplyUserMapper, ApplyUser> implements ApplyUserInterface {

    @Autowired
    private final MemberServiceInterface memberServiceInterface;
    private final ResidentialServiceInterface residentialServiceInterface;
    private final UserServiceInterface userServiceInterface;
    private final MemberAndUserInterface memberAndUserInterface;
    private final RoomServiceInterface roomServiceInterface;
    private final UnitServiceInterface unitServiceInterface;
    private final ConfFeign confFeign;
    private final DeviceFeign deviceFeign;
    private final CustInfoVerifyFeign custInfoVerifyFeign;


    @Override
    public ResultBean<Boolean> checkByNameAndRoomId(ApplyUser applyUser) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //姓名
        wrapper.eq("s_name", applyUser.getName());
        //房间id
        wrapper.eq("l_room_id", applyUser.getRoomId());
        //申请记录审核状态：0-待审核 1-审核通过 2-审核不通过
        wrapper.eq("i_check_state", OperationConstant.ZERO);
        //统计
        int count = this.selectCount(wrapper);
        if (count > 0) {
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, false);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> authentication(ApplyUser applyUser) {
        //添加住户申请记录
        Boolean result = this.insert(applyUser);
        if (result) {
            //更新会员状态
            Member member = new Member();
            member.setId(applyUser.getMemberId());
            //认证状态：{ 0：未认证，1：待审审核，2：已认证 }
            member.setState(OperationConstant.ONE);
            member.setIdcard(applyUser.getIdCard());
            //修改会员状态---待审核
            result = this.memberServiceInterface.updateById(member);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, result);
    }

    @Override
    public Page<ApplyUser> showApplyUserList(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //审核状态
        if (applyUserDto.getCheckState() != null) {
            wrapper.eq("i_check_state", applyUserDto.getCheckState());
        }
        //名字
        if (StringUtils.isNotBlank(applyUserDto.getName())) {
            wrapper.like("s_name", applyUserDto.getName());
        }
        //联系电话
        if (StringUtils.isNotBlank(applyUserDto.getTel())) {
            wrapper.like("s_tel", applyUserDto.getTel());
        }
        //身份证
        if (StringUtils.isNotBlank(applyUserDto.getIdCard())) {
            wrapper.like("s_id_card", applyUserDto.getIdCard());
        }
        //小区
        wrapper.eq(applyUserDto.getResidentialId() != null, "l_residential_id", applyUserDto.getResidentialId());
        //楼栋
        wrapper.eq(applyUserDto.getBuildingId() != null, "l_building_id", applyUserDto.getBuildingId());
        //根据单元ID查询
        if (applyUserDto.getUnitId() != null) {
            wrapper.eq("l_unit_id", applyUserDto.getUnitId());
        }
        //根据楼栋ID查询
        if (applyUserDto.getBuildingId() != null) {
            wrapper.eq("l_building_id", applyUserDto.getBuildingId());
        }
        //根据房间ID查询
        if (applyUserDto.getRoomId() != null) {
            wrapper.eq("l_room_id", applyUserDto.getRoomId());
        }
        //机构
        if (StringUtils.isNotBlank(applyUserDto.getOrgPosition())) {
            wrapper.like("s_org_position", applyUserDto.getOrgPosition());
        }
        //物业
        if (StringUtils.isNotBlank(applyUserDto.getEstatePosition())) {
            wrapper.like("s_estate_position", applyUserDto.getEstatePosition());
        }
        //  排序字段 审核状态
        wrapper.orderBy("i_check_state",true);
        //  排序字段
        if (applyUserDto.getSortField() != null && applyUserDto.getSortOrder() != null) {
            wrapper.orderBy(applyUserDto.getSortField(), applyUserDto.getSortOrder().equals("asc"));
        } else {
            //  排序字段 时间降序
            wrapper.orderBy("t_create_date", false);
        }
        return this.selectPage(applyUserDto.getPage(), wrapper);
    }

    @Override
    public ApplyUser getApplyUserById(Long id) {
        ApplyUser applyUser = this.selectById(id);
        if (applyUser != null) {
            //编辑的记录
            User user = null;
            if (applyUser.getUserId() != null) {
                user = this.userServiceInterface.findUserById(applyUser.getUserId());

            } else {
                //房间下，名字唯一
                UserDto userDto = new UserDto();
                userDto.setName(applyUser.getName());
                userDto.setRoomId(applyUser.getRoomId());
                user = this.userServiceInterface.getUserByNameAndRoomId(applyUser.getName(), applyUser.getRoomId());
            }
            if (user != null) {
                //显示
                applyUser.setUserImageUri(user.getImageUri());
            }
        }
        return applyUser;
    }

    private final VideoCallAccountServiceInterface videoCallAccountServiceInterface;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public ResultBean<Boolean> updateCheckState(ApplyUser condition) {
        Boolean result = false;
        //获取申请记录
        ApplyUser applyUser = this.selectById(condition.getId());
        if (condition.getCheckState().equals(1)){
            //要审核通过的话，必须有时间和身份验证的限制
            boolean timeRange = false;
            try {
                timeRange = CommonUtil.isTimeRange("7:00", "22:00");
            }catch (Exception e){
                return new ResultBean<>(ResultEnum.ERROR);
            }
            Assert.isTrue(timeRange, "请在7:00-22:00时间内进行审核！");
            if(StringUtils.isNotBlank(applyUser.getIdCard()) && StringUtils.isNotBlank(applyUser.getName())){
                CustInfoVerify custInfoVerify = new CustInfoVerify();
                custInfoVerify.setCustName(applyUser.getName());
                custInfoVerify.setCertNumber(applyUser.getIdCard());
                custInfoVerify.setCertType("1");
                boolean verify = custInfoVerifyFeign.verify(custInfoVerify);
                Assert.isTrue(verify, "身份证验证失败，请填写正确的身份证信息");
            }else{
                Assert.isTrue(false, "该住户没有身份证号，无法通过审核！");
            }
        }

        if (applyUser.getCheckState() == OperationConstant.ZERO) {
            //更新记录状态
            condition.setCheckDate(new Date());
            result = this.updateById(condition);
            //更新会员状态--认证类型的记录才需要修改
            Member member = new Member();
            member.setId(applyUser.getMemberId());
            //当操作是审核通过操作
            if (result && condition.getCheckState() == 1) {
                //认证状态：{ 0：未认证，1：待审核，2：已认证 }
                member.setState(OperationConstant.TWO);
                User oldUser = null;
                //编辑类型
                if (applyUser.getUserId() != null) {
                    //做这样的区分是为了查询速度更快
                    oldUser = this.userServiceInterface.selectById(applyUser.getUserId());
                }
                User user;
                //存在住户信息
                if (oldUser != null) {
                    boolean isUpdate = false;
                    user = new User();
                    user.setFaceEnable(oldUser.getFaceEnable());
                    user.setId(oldUser.getId());
                    //替换身份
                    if (applyUser.getType() != null && !applyUser.getType().equals(oldUser.getType())) {
                        user.setType(applyUser.getType());
                        isUpdate = true;
                    }
                    //替换手机
                    if (StringUtils.isNotBlank(applyUser.getTel()) && !applyUser.getTel().equals(oldUser.getTel())) {
                        user.setTel(applyUser.getTel());
                        isUpdate = true;
                    }
                    //替换身份证
                    if (StringUtils.isNotBlank(applyUser.getIdCard()) && !applyUser.getIdCard().equals(oldUser.getIdCard())) {
                        user.setIdCard(applyUser.getIdCard());
                        isUpdate = true;
                    }
                    //人脸替换
                    if (StringUtils.isNotBlank(applyUser.getImageUri())) {
                        user.setImageUri(applyUser.getImageUri());
                        user.setCreateFaceImageType(applyUser.getCreateType());
                        user.setFaceCode(applyUser.getFaceCode());
                        if (oldUser.getCheckState() == null || oldUser.getCheckState() != 1) {
                            user.setCheckState(1);
                        }
                        if (oldUser.getFaceEnable() == null || oldUser.getFaceEnable() == -1) {
                            user.setFaceEnable(0);
                        }
                        isUpdate = true;
                    }
                    //房间
                    if (applyUser.getRoomId() != null && !applyUser.getRoomId().equals(oldUser.getRoomId())) {
                        user.setRoomId(applyUser.getRoomId());
                        isUpdate = true;
                    }
                    //性别
                    if (applyUser.getSex() != null && !applyUser.getSex().equals(oldUser.getSex())) {
                        user.setSex(applyUser.getSex());
                        isUpdate = true;
                    }
                    //国籍
                    if (applyUser.getNationality() != null && !applyUser.getNationality().equals(oldUser.getNationality())) {
                        user.setNationality(applyUser.getNationality());
                        isUpdate = true;
                    }
                    //护照
                    if (StringUtils.isNotBlank(applyUser.getPassportImgUri()) && !applyUser.getPassportImgUri().equals(oldUser.getPassportImgUri())) {
                        user.setPassportImgUri(applyUser.getPassportImgUri());
                        isUpdate = true;
                    }
                    //护照
                    if (StringUtils.isNotBlank(applyUser.getEntryImgUri()) && !applyUser.getEntryImgUri().equals(oldUser.getEntryImgUri())) {
                        user.setEntryImgUri(applyUser.getEntryImgUri());
                        isUpdate = true;
                    }
                    if (isUpdate) {
                        //更新之前user信息
                        result = this.userServiceInterface.updateById(user);
                    }
                } else {
                    //申请记录转User
                    user = this.applyUserToUser(applyUser);
                    Date beginDate = new Date();
                    Calendar cd = Calendar.getInstance();
                    cd.setTime(beginDate);
                    cd.add(Calendar.YEAR, 20);
                    Date endDate = cd.getTime();
                    user.setFaceBeginDate(beginDate);
                    user.setFaceEndDate(endDate);
                    //往user增加faceEnable并设置为0
//                    user.setFaceEnable(OperationConstant.ZERO);
                    //新增一个user
                    result = this.userServiceInterface.insert(user);
                    condition.setUserId(user.getId());
                    result = this.updateById(condition);
                    //新增人数
                    Residential residential = this.residentialServiceInterface.findResidentialById(user.getResidentialId());
                    //小区住户数量加+1
                    residential.setUserNumber(residential.getUserNumber() + 1);
                    this.residentialServiceInterface.updateById(residential);

                    Unit unit = this.unitServiceInterface.findUnitById(user.getUnitId());
                    //单元住户数量加+1
                    unit.setUserNumber(unit.getUserNumber() + 1);
                    this.unitServiceInterface.updateById(unit);

                    Room room = this.roomServiceInterface.findRoomById(user.getRoomId());
                    //房间住户加+1
                    room.setUserNumber(room.getUserNumber() + 1);
                    this.roomServiceInterface.updateById(room);

                }
                // 申请的记录类型 0--认证类型 1--新增类型 2--编辑类型(通过user编辑生成的) 3--编辑类型(通过applyUser编辑生成)
                if (result && applyUser.getRecordType() == 0) {
                    MemberAndUser memberAndUser = new MemberAndUser();
                    memberAndUser.setMemberId(applyUser.getMemberId());
                    memberAndUser.setUserId(user.getId());
                    memberAndUser.setRoomId(applyUser.getRoomId());
                    //保存member和user的关系
                    memberAndUserInterface.insert(memberAndUser);
                    //  生成视频对讲账号
                    VideoCallAccount account = new VideoCallAccount();
                    account.setMember(member);
                    List<User> userList = new ArrayList<>();
                    userList.add(user);
                    account.setUserList(userList);
                    this.videoCallAccountServiceInterface.createAccountByUser(account);
                }
                //---------------------------------------------------------------------------
                //下发人脸
                if (oldUser != null) {
                    if (user.getFaceEnable() == OperationConstant.TWO) {
                        // 人脸已禁用
                    } else {
                        pushFace(user, OperationConstant.TWO);
                    }
                } else {
                    pushFace(user, OperationConstant.ONE);
                }
            } else {//审核不通过
                //认证状态：{ 0：未认证，1：待审审核，2：已认证 }
                member.setState(OperationConstant.ZERO);
            }
            //申请的记录类型 0--认证类型 1--新增类型 2--编辑类型
            if (applyUser.getRecordType() == null || applyUser.getRecordType() == 0) {
                //认证类型的记录须修改会员的状态
                result = this.memberServiceInterface.updateById(member);
            }
        }

        return new ResultBean<>(ResultEnum.SUCCESS, result);
    }

    private void pushFace(User user, Integer operType) {

        if (StringUtils.isNotBlank(user.getImageUri())) {

            Map<String, String> logMap = new HashMap<>();
            //小区
            if (!StringUtils.isEmpty(user.getResidentialName())) {
                logMap.put("xqName", user.getResidentialName());
            } else {
                logMap.put("xqName", null);
            }
            //单元
            if (!StringUtils.isEmpty(user.getUnitName())) {
                logMap.put("unitName", user.getUnitName());
            } else {
                logMap.put("unitName", null);
            }
            //房间
            if (!StringUtils.isEmpty(user.getRoomName())) {
                logMap.put("roomName", user.getRoomName());
            } else {
                logMap.put("roomName", null);
            }
            //用户名
            if (!StringUtils.isEmpty(user.getName())) {
                logMap.put("userName", user.getName());
            } else {
                logMap.put("userName", null);
            }

            String imgHost = this.confFeign.getFileServerHost();
            List<Map<String, Object>> userFaceList = new ArrayList<>(1);
            Map<String, Object> map = new HashMap<>(3);
            map.put("imgMd5", user.getFaceCode());
            map.put("imgSrc", imgHost + user.getImageUri());
            userFaceList.add(map);
            //  下发人脸-到通用设备
            UserInfoDto dto = new UserInfoDto();
            dto.setId(UserFlagConstant.USER_NUMBER_FLAG + user.getId());
            dto.setFaceCodeList(userFaceList);
            dto.setBeginDate(user.getFaceBeginDate());
            dto.setEndDate(user.getFaceEndDate());
            DispatchTask task = new DispatchTask();
            task.setUnitId(user.getUnitId());
            task.setXqId(user.getResidentialId());
            task.setData(dto);
            this.deviceFeign.pushUserFaceToUniversalDevices(task, operType, logMap);
        }
    }

    @Override
    public List<ApplyUser> getAllApplyUserByMemberId(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //排序字段--待审核的排在最前面
        wrapper.orderBy("t_create_date", false);
        //会员id
        wrapper.eq("l_member_id", applyUserDto.getMemberId());
        //审核状态
        if (applyUserDto.getCheckStates() != null) {
            wrapper.in("i_check_state", applyUserDto.getCheckStates());
        }
        return this.selectList(wrapper);
    }

    @Override
    public Page<ApplyUser> pagingByMemberId(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //排序字段--待审核的排在最前面
        wrapper.orderBy("t_create_date", false);
        //会员id
        wrapper.eq("l_member_id", applyUserDto.getMemberId());
        if (applyUserDto.getCheckStates() != null) {
            wrapper.in("i_check_state", applyUserDto.getCheckStates());
        }
        if(applyUserDto.getRoomId() != null){
            wrapper.eq("l_room_id",applyUserDto.getRoomId());
        }
        return this.selectPage(applyUserDto.getPage(), wrapper);
    }

    @Override
    public Page<ApplyUser> pagingByRoomId(ApplyUserDto applyUserDto) {
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        wrapper.orderBy("t_create_date", false);
        wrapper.eq("l_room_id", applyUserDto.getRoomId());
        //审核状态
        if (applyUserDto.getCheckStates() != null) {
            wrapper.in("i_check_state", applyUserDto.getCheckStates());
        }
        return this.selectPage(applyUserDto.getPage(), wrapper);
    }

    @Override
    public Map<String, Object> applyUserCountForCheckState(ApplyUserDto applyUserDto) {
        if (applyUserDto == null) {
            return null;
        }
        EntityWrapper<ApplyUser> wrapper = new EntityWrapper<ApplyUser>();
        //待审核,审核通过,审核不通过的数量
        String sqlSelect = "sum(case  when i_check_state=0 then 1 ELSE 0 end) waitCheckCount," +
                "sum(case  when i_check_state=1 then 1 ELSE 0 end) passCheckCount," +
                "sum(case  when i_check_state=2 then 1 ELSE 0 end) noPassCheckCount";
        wrapper.setSqlSelect(sqlSelect);
        //机构位置
        String orgPosition = applyUserDto.getOrgPosition();
        //根据机构
        if (StringUtils.isNotBlank(orgPosition)) {
            wrapper.like("s_org_position", orgPosition, SqlLike.RIGHT);
        }
        return this.selectMap(wrapper);
    }

    @Override
    public Long getApplyUserCount(ApplyUserDto applyUserDto) {
        if (applyUserDto == null) {
            return null;
        }
        EntityWrapper<ApplyUser> wrapper = new EntityWrapper<ApplyUser>();
        //统计数量
        String sqlSelect = "count(1)";
        wrapper.setSqlSelect(sqlSelect);
        //审核状态
        Integer checkState = applyUserDto.getCheckState();
        if (checkState != null) {
            wrapper.eq("i_check_state", checkState);
        }
        //机构位置
        String orgPosition = applyUserDto.getOrgPosition();
        //根据机构
        if (StringUtils.isNotBlank(orgPosition)) {
            wrapper.like("s_org_position", orgPosition, SqlLike.RIGHT);
        }
        return (Long) this.selectObj(wrapper);
    }

    @Override
    public int getApplyUserCountByState(ApplyUserDto applyUserDto) {
        EntityWrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //统计数量
        String sqlSelect = "count(distinct l_member_id)";
        wrapper.setSqlSelect(sqlSelect);
        //审核状态
        wrapper.eq("i_check_state", applyUserDto.getCheckState());
        //小区
        wrapper.eq("l_residential_id", applyUserDto.getResidentialId());
        return this.selectCount(wrapper);
    }

    @Override
    public ResultBean<Page> getApplyUserPage(PageBean<ApplyUser, ApplyUserDto> pageBean) {
        ApplyUserDto dto = pageBean.getDto();
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //单元
        Long unitId = dto.getUnitId();
        if (null != unitId) {
            wrapper.eq("l_unit_id", unitId);
        }
        //房间
        Long roomId = dto.getRoomId();
        if (null != roomId) {
            wrapper.eq("l_room_id", roomId);
        }
        //姓名
        String name = dto.getName();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("s_name", name, SqlLike.DEFAULT);
        }
        //联系方式
        String tel = dto.getTel();
        if (StringUtils.isNotBlank(tel)) {
            wrapper.like("s_tel", tel, SqlLike.DEFAULT);
        }
        //审核状态
        wrapper.eq("i_check_state", dto.getCheckState());
        //小区
        wrapper.eq("l_residential_id", dto.getResidentialId());
        wrapper.orderBy("t_create_date", false);
        Page<ApplyUser> page = this.selectPage(pageBean, wrapper);
        String serverHost = this.confFeign.getFileServerHost();
        page.getRecords().forEach(user -> user.setImageUri(serverHost + user.getImageUri()));
        return new ResultBean<>(ResultEnum.SUCCESS, page);
    }

    @Override
    public List<ApplyUser> getAllApplyUserByRoomId(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //排序字段--待审核的排在最前面
        wrapper.orderBy("t_create_date", false);
        //房间id
        wrapper.eq("l_room_id", applyUserDto.getRoomId());
        //审核状态
        if (applyUserDto.getCheckStates() != null) {
            wrapper.in("i_check_state", applyUserDto.getCheckStates());
        }
        return this.selectList(wrapper);
    }

    @Override
    public List<ApplyUser> getApplyUserByCondition(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        if (applyUserDto.getUserId() != null) {
            wrapper.eq("l_user_id", applyUserDto.getUserId());
        }
        if (applyUserDto.getMemberId() != null) {
            wrapper.eq("l_member_id", applyUserDto.getMemberId());
        }
        if (StringUtils.isNotBlank(applyUserDto.getName())) {
            wrapper.eq("s_name", applyUserDto.getName());
        }
        if (applyUserDto.getRoomId() != null) {
            wrapper.eq("l_room_id", applyUserDto.getRoomId());
        }
        if (StringUtils.isNotBlank(applyUserDto.getRoomName())) {
            wrapper.eq("s_room_name", applyUserDto.getRoomName());
        }
        if (StringUtils.isNotBlank(applyUserDto.getOrgPosition())) {
            wrapper.like("s_org_position", applyUserDto.getOrgPosition(), SqlLike.RIGHT);
        }
        //审核状态
        if (applyUserDto.getCheckStates() != null) {
            wrapper.in("i_check_state", applyUserDto.getCheckStates());
        }
        if (applyUserDto.getCheckState() != null) {
            wrapper.eq("i_check_state", applyUserDto.getCheckState());
        }

        if (StringUtils.isNotBlank(applyUserDto.getCheckOpinion())) {
            wrapper.eq("s_check_opinion", applyUserDto.getCheckOpinion());
        }
        if (applyUserDto.getType() != null) {
            wrapper.eq("i_type", applyUserDto.getType());
        }
        if (StringUtils.isNotBlank(applyUserDto.getIdCard())) {
            wrapper.eq("s_id_card", applyUserDto.getIdCard());
        }
        if (StringUtils.isNotBlank(applyUserDto.getTel())) {
            wrapper.eq("s_tel", applyUserDto.getTel());
        }
        if (applyUserDto.getResidentialId() != null) {
            wrapper.eq("l_residential_id", applyUserDto.getResidentialId());
        }
        //  排序字段 时间降序
        wrapper.orderBy("t_create_date", false);
        return this.selectList(wrapper);
    }

    private User applyUserToUser(ApplyUser applyUser) {
        User user = new User();
//        user.setId(IdWorker.getId());
        user.setName(applyUser.getName());
        user.setStatus(OperationConstant.ZERO);
        if (StringUtils.isNotBlank(applyUser.getImageUri())) {
            user.setImageUri(applyUser.getImageUri());
            user.setCheckState(1);
            user.setFaceCode(applyUser.getFaceCode());
            user.setFaceEnable(OperationConstant.ONE); //未激活
        } else {
            user.setCheckState(OperationConstant.MINUS_ONE); //未上传人脸
            user.setFaceEnable(OperationConstant.MINUS_ONE); //未上传人脸
        }
        user.setOrgPosition(applyUser.getOrgPosition());
        user.setRootOrgId(applyUser.getRootOrgId());
        user.setSex(applyUser.getSex());
        user.setNationality(applyUser.getNationality());
        if (StringUtils.isNotBlank(applyUser.getPassportImgUri())) {
            user.setPassportImgUri(applyUser.getPassportImgUri());
        }
        if (StringUtils.isNotBlank(applyUser.getEntryImgUri())) {
            user.setEntryImgUri(applyUser.getEntryImgUri());
        }
        user.setType(applyUser.getType());
        user.setIdCard(applyUser.getIdCard());
        user.setTel(applyUser.getTel());
        user.setBuildingName(applyUser.getBuildingName());
        user.setBuildingId(applyUser.getBuildingId());
        user.setRoomId(applyUser.getRoomId());
        user.setRoomName(applyUser.getRoomName());
        user.setUnitId(applyUser.getUnitId());
        user.setUnitName(applyUser.getUnitName());
        user.setResidentialId(applyUser.getResidentialId());
        user.setResidentialName(applyUser.getResidentialName());
        user.setCreateType(applyUser.getCreateType());
        user.setCreateFaceImageType(applyUser.getCreateType());
        user.setCreateDate(new Date());
//        user.setCheckState(OperationConstant.ONE);
        user.setCheckOpinion(applyUser.getCheckOpinion());
        //获取小区信息---拿省市区
        Residential residential = this.residentialServiceInterface.findResidentialById(applyUser.getResidentialId());
        user.setRegionProvince(residential.getRegionProvince());
        user.setRegionCity(residential.getRegionCity());
        user.setRegionArea(residential.getRegionArea());
        user.setIsMember(OperationConstant.ZERO);
        return user;
    }

    /**
     * 添加申请用户返回申请用户对象
     *
     * @param applyUser
     * @return
     */
    @Override
    public Long addApplyUserReturnUser(ApplyUser applyUser) {
        return this.baseMapper.insertApplyUser(applyUser);
    }

    @Override
    public ResultBean<Page<ApplyUser>> getAuthRoomByMemberId(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //memberId
        wrapper.eq(applyUserDto.getMemberId() != null, "l_member_id", applyUserDto.getMemberId());
        //审核状态
        wrapper.eq(applyUserDto.getCheckState() != null, "i_check_state", applyUserDto.getCheckState());
        //  排序字段 审核状态,时间排序
        wrapper.orderBy("t_create_date", false);
        return new ResultBean<>(ResultEnum.SUCCESS, this.selectPage(applyUserDto.getPage(), wrapper));
    }

    @Override
    public ResultBean<Boolean> addApplyUsers(List<ApplyUser> applyUserList) {
        return new ResultBean<>(ResultEnum.SUCCESS, this.insertBatch(applyUserList));
    }

    @Override
    public boolean deleteApplyUser(ApplyUserDto applyUserDto) {
        //构建查询条件
        Wrapper<ApplyUser> wrapper = new EntityWrapper<>();
        //memberId
        wrapper.eq(applyUserDto.getMemberId() != null, "l_member_id", applyUserDto.getMemberId());
        //residentialId
        wrapper.eq(applyUserDto.getResidentialId() != null, "l_residential_id", applyUserDto.getResidentialId());
        //userId
        wrapper.eq(applyUserDto.getUserId() != null, "l_user_id", applyUserDto.getUserId());
        //审核状态
        wrapper.eq(applyUserDto.getCheckState() != null, "i_check_state", applyUserDto.getCheckState());
        Integer delete = this.baseMapper.delete(wrapper);
        return delete > 0;
    }
}
