nidapeng
2024-04-19 89610234a2bdc56f60e0998045892ef2672edccc
server/dmvisit_service/src/main/java/com/doumee/service/business/impl/VisitsServiceImpl.java
@@ -1,13 +1,23 @@
package com.doumee.service.business.impl;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.erp.ErpConstants;
import com.doumee.core.erp.ErpTool;
import com.doumee.core.erp.model.openapi.request.VisitListRequest;
import com.doumee.core.erp.model.openapi.request.erp.ApproveAddRequest;
import com.doumee.core.erp.model.openapi.request.erp.UserInfoRequest;
import com.doumee.core.erp.model.openapi.response.VisitEventListResponse;
import com.doumee.core.erp.model.openapi.response.erp.ApproveInfoResponse;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.haikang.model.HKConstants;
import com.doumee.core.haikang.model.HKTools;
import com.doumee.core.haikang.model.param.BaseResponse;
import com.doumee.core.haikang.model.param.request.VisitAppointmentCancelRequest;
import com.doumee.core.haikang.model.param.request.VisitAppointmentOutRequest;
import com.doumee.core.haikang.model.param.request.VisitAppointmentRequest;
import com.doumee.core.haikang.model.param.respose.VisitAppointmentResponse;
import com.doumee.core.haikang.service.HKService;
@@ -17,30 +27,41 @@
import com.doumee.core.utils.DESUtil;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.DeviceRoleMapper;
import com.doumee.dao.business.MemberMapper;
import com.doumee.dao.business.ProblemLogMapper;
import com.doumee.dao.business.VisitsMapper;
import com.doumee.dao.business.model.DeviceRole;
import com.doumee.dao.business.model.Member;
import com.doumee.dao.business.model.ProblemLog;
import com.doumee.dao.business.model.Visits;
import com.doumee.core.wx.wxPlat.WxPlatNotice;
import com.doumee.dao.admin.response.MemberInfoDTO;
import com.doumee.dao.business.*;
import com.doumee.dao.business.join.DeviceJoinMapper;
import com.doumee.dao.business.join.VisitEventJoinMapper;
import com.doumee.dao.business.join.VisitsJoinMapper;
import com.doumee.dao.business.model.*;
import com.doumee.dao.web.reqeust.AuditApproveDTO;
import com.doumee.dao.web.reqeust.ErpVisitDTO;
import com.doumee.dao.web.reqeust.ErpWithVisitDTO;
import com.doumee.dao.web.reqeust.VisitRecordDTO;
import com.doumee.dao.web.response.InternalHomeVO;
import com.doumee.dao.web.response.VisitDetailVO;
import com.doumee.dao.web.response.VisitRecordVO;
import com.doumee.service.business.ApproveService;
import com.doumee.service.business.InterfaceLogService;
import com.doumee.service.business.VisitsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 访客申请信息表Service实现
@@ -51,21 +72,117 @@
public class VisitsServiceImpl implements VisitsService {
    @Autowired
    private RetentionMapper retentionMapper;
    @Autowired
    private VisitsMapper visitsMapper;
    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private ApproveParamMapper approveParamMapper;
    @Autowired
    private DeviceRoleMapper deviceRoleMapper;
    @Autowired
    private ProblemLogMapper problemLogMapper ;
    @Autowired
    private MemberMapper memberMapper ;
    @Autowired
    private VisitsJoinMapper visitsJoinMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private DeviceJoinMapper deviceJoinMapper;
    @Autowired
    private ErpTool erpTool;
    @Autowired
    private WxPlatNotice wxPlatNotice;
    @Autowired
    private InterfaceLogService interfaceLogService;
    @Override
    public Integer create(Visits visits) {
        visitsMapper.insert(visits);
        return visits.getId();
    }
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public void createFKForErp(ErpVisitDTO erpVisitDTO){
            if (Objects.isNull(erpVisitDTO)
                    || StringUtils.isBlank(erpVisitDTO.getName())
                    || StringUtils.isBlank(erpVisitDTO.getPhone())
                    || StringUtils.isBlank(erpVisitDTO.getCompanyName())
                    || Objects.isNull(erpVisitDTO.getIdcardType())
                    || StringUtils.isBlank(erpVisitDTO.getIdcardNo())
                    || Objects.isNull(erpVisitDTO.getStarttime())
                    || Objects.isNull(erpVisitDTO.getEndtime())
                    || StringUtils.isBlank(erpVisitDTO.getFaceImg())
                    || StringUtils.isBlank(erpVisitDTO.getDoors())
                    || Objects.isNull(erpVisitDTO.getReceptMemberId())
                    || Objects.isNull(erpVisitDTO.getErpId())
            ) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,信息填写不正确!");
            }
            if (erpVisitDTO.getEndtime().getTime() <= erpVisitDTO.getStarttime().getTime()) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约结束时间必须大于开始时间!");
            }
            if (Constants.equalsInteger(Constants.ZERO, erpVisitDTO.getIdcardType()) && erpVisitDTO.getIdcardNo().length() != 18
                //&&!IdcardUtil.isValidCard(visits.getIdcardNo())
            ) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,身份证号码有误,请核实后重试!");
            }
            Visits visits = new Visits();
            //根据被访问人ERP主键查询系统内人员主键信息
            Member member = memberMapper.selectOne(new QueryWrapper<Member>().lambda()
                    .eq(Member::getIsdeleted, Constants.ZERO).eq(Member::getType, Constants.memberType.internal)
                    .eq(Member::getErpId, erpVisitDTO.getReceptMemberId()).last("limit 1"));
            if (Objects.isNull(member)) {
                throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "未查询到被访问人信息");
            }
            if (Objects.isNull(member.getCanVisit()) || member.getCanVisit().equals(Constants.ZERO)) {
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "当前被访问人无法被访问");
            }
            BeanUtils.copyProperties(erpVisitDTO, visits);
            //设置内部系统人员主键
            visits.setReceptMemberId(member.getId());
            visits.setSourceType(Constants.ONE);
            List<ErpWithVisitDTO> erpWithVisitDTOList = erpVisitDTO.getErpWithVisitDTOList();
            if (CollectionUtils.isNotEmpty(erpWithVisitDTOList)) {
                List<Visits> visitsList = new ArrayList<>();
                for (ErpWithVisitDTO erpWithVisitDTO : erpWithVisitDTOList) {
                    Visits withVisits = new Visits();
                    BeanUtils.copyProperties(erpWithVisitDTO, withVisits);
                    withVisits.setCompanyName(visits.getCompanyName());
                    withVisits.setReason(visits.getReason());
                    visitsList.add(withVisits);
                }
                visits.setWithUserList(visitsList);
            }
            this.createFk(visits,true);
    }
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    void saveInterfaceLog(Object param, String path, String result, Integer type) {
        InterfaceLog interfaceLog=new InterfaceLog();
        interfaceLog.setType(type);
        interfaceLog.setCreateDate(new Date());
        interfaceLog.setIsdeleted(Constants.ZERO);
        if(param!=null){
            interfaceLog.setRequest(JSONObject.toJSONString(param));
        }
        interfaceLog.setPlat(Constants.ONE);
        interfaceLog.setRepose(result);
        interfaceLog.setName(path);
        interfaceLog.setUrl(path);
        interfaceLogService.create(interfaceLog);
    }
    /**
     * 普通访客申请
@@ -74,56 +191,415 @@
     */
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public Integer createFk(Visits visits) {
    public Integer createFk(Visits visits,Boolean isERP) {
        isValidBaseParam(visits);
        //检查是否必须答题,并且符合答题要求
        ProblemLog problemLog = isValidProblemLog(visits);
        //获取申请的海康访问门禁组信息
        String[] hkIds = getHkDeviceRoles(visits);
        getHkDeviceRoles(visits,isERP);
        //检验拜访人是否合法
        isValideVisitedUser(visits.getReceptMemberId());
        if(Constants.equalsInteger(Constants.ZERO, visits.getIdcardType()) &&!IdcardUtil.isValidCard(visits.getIdcardNo())){
        Member visitMember = isValideVisitedUser(visits.getReceptMemberId());
        if(Constants.equalsInteger(Constants.ZERO, visits.getIdcardType())&&visits.getIdcardNo().length()!=18
            //&&!IdcardUtil.isValidCard(visits.getIdcardNo())
        ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,身份证号码有误,请核实后重试!");
        }
        Date date = new Date();
        //创建时间
        visits.setCreateDate(date);
        //普通访客
        visits.setType(Constants.ONE);
        //随行人员数量
        visits.setMemberNum(CollectionUtils.isNotEmpty(visits.getWithUserList())?visits.getWithUserList().size():0);
        //访客信息(使用身份证号查询是否已存在改普通访客,没有则新增,存在则更新openid等信息),包括随访人员校验和处理
        Member member =dealMemberAndVisits(visits);
        visits.setMemberId(member.getId());
        visits.setVisitType(Integer.valueOf(systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.MDJ_VISIT_REQUIRED).getCode()));
        //初始化访客信息
        initVisitInfo(visits,date);
        //发起ERP审批申请
        String erpid = startSendErpCheck(visits);
        if(StringUtils.isNotBlank(erpid)){
            visits.setErpId(erpid);
        }else{
            throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "对不起,发起拜访审批申请失败!");
        }
        visitsMapper.insert(visits);
        //发起ERP审批申请
        if(visits.getSourceType().equals(Constants.ZERO)){
            String erpId = startSendErpCheck(visits,visitMember);
            if(StringUtils.isNotBlank(erpId)){
                visits.setErpId(erpId);
                visits.setStatus(Constants.VisitStatus.submitCheck);
                visitsMapper.updateById(visits);
            }else{
                throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "对不起,发起拜访审批申请失败!");
            }
            //发送微信公众号通知
            wxPlatNotice.sendVisitAuditTemplateNotice(visits,
                    systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_PLATFORM_PREFIX).getCode(),
                    systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_PLATFORM_AUDIT_VISIT).getCode());
        }else{
            visits.setStatus(Constants.VisitStatus.pass);
            visitsMapper.updateById(visits);
        }
        initWithVisitInfo(visits);
        updateProblemLog(visits,problemLog,member);
        //创建审批记录
//        createApprove(visits,visitMember);
        return visits.getId();
    }
    /**
     * 创建审批记录
     * @param visits
     * @param visitMember
     */
    public void createApprove(Visits visits,Member visitMember){
        List<Integer> approveIds = new ArrayList<>();
        ApproveParam approveParam = null;//this.getApproveIds(1,visitMember,approveIds);
        //创建待审批记录
        //获取审批配置主键
        Integer firstApproveId = this.checkFirstAudit();
        //内部人员创建 且创建人与被访问人相同
        if(!Objects.isNull(visits.getCreateMemberId())//内部人员发布
                &&visits.getCreateMemberId().equals(visitMember.getId())//创建人员与被访问人员是否是同一人
                &&!Objects.isNull(firstApproveId)//审批配置第一级为 被访问人审批
        ){
            approveParam = this.getApproveIds(2,visitMember,approveIds);
            Approve approve = new Approve();
            approve.setCreateDate(new Date());
            approve.setIsdeleted(Constants.ZERO);
            approve.setCheckInfo("自动审批");
            approve.setTemplatId(firstApproveId);
            approve.setIsEndCheck(Constants.ZERO);
            approve.setType(Constants.ZERO);
            approve.setLevel(Constants.ONE);
            approve.setVisitId(visits.getId());
            approveMapper.insert(approve);
            if(!CollectionUtils.isNotEmpty(approveIds)){
                approve.setIsEndCheck(Constants.ONE);
                visits.setStatus(Constants.TWO);
                visitsMapper.updateById(visits);
                //存储抄送记录
                this.saveCopyFor(visits.getId());
            }
        }else{
            approveParam = this.getApproveIds(null,visitMember,approveIds);
            if(!CollectionUtils.isNotEmpty(approveIds)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"无有效的审批配置,请联系管理员");
            }
        }
        if(!Objects.isNull(approveIds)){
            //创建下一级审批记录
            this.saveAuditRecord(visits.getId(),approveIds,approveParam);
        }
    }
    /**
     * 审批 审批记录 或签 审批通过进入下一步  会签 检测是否是最后一条待审批
     * @param auditApproveDTO
     */
    @Override
    public void auditApprove(AuditApproveDTO auditApproveDTO){
        Approve approve = approveMapper.selectById(auditApproveDTO.getId());
        if(Objects.isNull(approve)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(approve.getStatus().equals(Constants.approveStatus.wait)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"审批记录已处理!");
        }
        Visits visits = visitsMapper.selectById(approve.getVisitId());
        if(Objects.isNull(visits)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!auditApproveDTO.getMemberId().equals(approve.getChekorId())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"人员信息匹配错误!");
        }
        //被访人
        Member visitMember = memberMapper.selectById(visits.getReceptMemberId());
        List<Integer> approveIds = new ArrayList<>();
        ApproveParam approveParam = this.getApproveIds(approve.getLevel()+1,visitMember,approveIds);
        approve.setStatus(auditApproveDTO.getStatus());
        approve.setEditDate(new Date());
        approve.setChekorId(auditApproveDTO.getMemberId());
        approve.setCheckInfo(auditApproveDTO.getCheckInfo());
        approveMapper.updateById(approve);
        if(auditApproveDTO.getStatus().equals(Constants.approveStatus.pass)){
            if(approve.getApproveType().equals(Constants.ONE)){
                //会签 查询是否是最后一条记录 如果是最后一条记录 则生成下级审批记录 如果是最后一级,则进行审批确认
                if(approveMapper.selectCount(new QueryWrapper<Approve>().lambda()
                        .eq(Approve::getVisitId,visits.getId())
                        .eq(Approve::getLevel,approve.getLevel())
                        .ne(Approve::getId,approve.getId())
                )<=Constants.ZERO){
                    //当前审批级别 最后一条待审批记录
                    if(!CollectionUtils.isNotEmpty(approveIds)){
                        //没有下级审批流则 修改访客记录主键
                        visits.setStatus(auditApproveDTO.getStatus());
                        visits.setCheckDate(new Date());
                        visits.setCheckorId(auditApproveDTO.getMemberId());
                        visitsMapper.updateById(visits);
                    }else{
                        this.saveAuditRecord(visits.getId(),approveIds,approveParam);
                    }
                }
            }else{
                //或签
                approveMapper.update(null,new UpdateWrapper<Approve>().lambda()
                        .set(Approve::getStatus,Constants.approveStatus.otherDeal)
                        .set(Approve::getEditDate,new Date())
                        .set(Approve::getCheorId,auditApproveDTO.getMemberId())
                        .eq(Approve::getVisitId,visits.getId())
                        .eq(Approve::getStatus,Constants.approveStatus.wait)
                        .ne(Approve::getId,approve.getId())
                        .eq(Approve::getLevel,approve.getLevel())
                );
                if(!CollectionUtils.isNotEmpty(approveIds)){
                    //没有下级审批流则 修改访客记录主键
                    visits.setStatus(auditApproveDTO.getStatus());
                    visits.setCheckDate(new Date());
                    visits.setCheckorId(auditApproveDTO.getMemberId());
                    visitsMapper.updateById(visits);
                }else{
                    this.saveAuditRecord(visits.getId(),approveIds,approveParam);
                }
            }
        }else if(auditApproveDTO.getStatus().equals(Constants.approveStatus.unPass)){
            visits.setStatus(auditApproveDTO.getStatus());
            visits.setCheckDate(new Date());
            visits.setCheckorId(auditApproveDTO.getMemberId());
            visitsMapper.updateById(visits);
            approveMapper.update(null,new UpdateWrapper<Approve>().lambda()
                    .set(Approve::getStatus,Constants.approveStatus.otherDeal)
                    .set(Approve::getEditDate,new Date())
                    .set(Approve::getCheorId,auditApproveDTO.getMemberId())
                    .eq(Approve::getVisitId,visits.getId())
                    .eq(Approve::getStatus,Constants.approveStatus.wait)
                    .ne(Approve::getId,approve.getId())
                    .eq(Approve::getLevel,approve.getLevel())
            );
        }else{
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"审批状态错误!");
        }
    }
    /**
     * 存储抄送记录
     * @param visitId
     */
    public void  saveCopyFor(Integer visitId){
        ApproveParam approveParam = approveParamMapper.selectOne(new QueryWrapper<ApproveParam>().lambda()
                .eq(ApproveParam::getIsdeleted,Constants.ZERO)
                .eq(ApproveParam::getType,Constants.ONE)
                .eq(ApproveParam::getLevel,Constants.ONE)
                .last("limit 1"));
        if(Objects.isNull(approveParam)){
            return;
        }
        if(StringUtils.isNotBlank(approveParam.getObjIds())){
            String [] ids = approveParam.getObjIds().split(",");
            List<Approve> approveList = new ArrayList<>();
            for (String id:ids) {
                Approve approve = new Approve();
                approve.setCreateDate(new Date());
                approve.setIsdeleted(Constants.ZERO);
                approve.setCheckInfo("抄送记录");
                approve.setTemplatId(approveParam.getId());
                approve.setChekorId(Integer.valueOf(id));
                approve.setType(Constants.ONE);
                approve.setVisitId(visitId);
                approveList.add(approve);
            }
            approveMapper.insertBatchSomeColumn(approveList);
        }
    }
    /**
     * 存储下级审批记录
     * @param visitId
     * @param ids
     * @param approveParam
     */
    public void  saveAuditRecord(Integer visitId,List<Integer> ids,ApproveParam approveParam){
        if(CollectionUtils.isNotEmpty(ids)) {
            List<Approve> approveList = new ArrayList<>();
            for (Integer id:ids) {
                Approve approve = new Approve();
                approve.setCreateDate(new Date());
                approve.setIsdeleted(Constants.ZERO);
                approve.setStatus(Constants.ZERO);
                approve.setCheckInfo("抄送记录");
                approve.setTemplatId(approveParam.getId());
                approve.setLevel(approveParam.getLevel());
                approve.setApproveType(approveParam.getApproveType());
                approve.setChekorId(id);
                approve.setType(Constants.ONE);
                approve.setVisitId(visitId);
                approveList.add(approve);
            }
            approveMapper.insertBatchSomeColumn(approveList);
        }
    }
    /**
     * 判断一级审批人是否是创建人
     * @return
     */
    public Integer checkFirstAudit(){
        ApproveParam approveParam = approveParamMapper.selectOne(new QueryWrapper<ApproveParam>().lambda()
                .eq(ApproveParam::getIsdeleted,Constants.ZERO)
                .eq(ApproveParam::getType,Constants.ZERO)
                .eq(ApproveParam::getLevel,Constants.ONE)
                .eq(ApproveParam::getMemberType,Constants.ZERO)
                .last("limit 1"));
         return  Objects.isNull(approveParam)?null:approveParam.getId();
    }
    /**
     * 创建审批人员信息 若返回待审批人员主键列表为空,则无审批人员 抛出对应异常
     * @param level   处理级别
     * @param visitMember 被访人
     */
    public ApproveParam getApproveIds(Integer level,Member visitMember,List<Integer> ids){
        //查询审批配置项
        List<ApproveParam> allParam = approveParamMapper.selectList(new QueryWrapper<ApproveParam>().lambda()
                .eq(ApproveParam::getIsdeleted,Constants.ZERO)
                .eq(ApproveParam::getType,Constants.ZERO)
                .ge(!Objects.isNull(level),ApproveParam::getLevel,level)
                .orderByAsc(ApproveParam::getLevel));
        ApproveParam approveParam = new ApproveParam();
        //发送审批/抄送记录的用户主键集合
        ids.clear();
        if(!CollectionUtils.isNotEmpty(allParam)){
            if(Objects.isNull(level)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"未配置访客审批流,请联系管理员");
            }
        }else{
             approveParam = allParam.get(0);
            if(approveParam.getMemberType().equals(Constants.ZERO)){
                //被访人审批
                //添加审批人
                ids.add(visitMember.getId());
            }else if(approveParam.getMemberType().equals(Constants.ONE)){
                //指定人员审批
                String [] objIds = approveParam.getObjIds().split(",");
                for (String id:objIds) {
                    //添加审批人
                    ids.add(Integer.valueOf(id));
                }
            }else if(approveParam.getMemberType().equals(Constants.TWO)){
                //部门主管审批
                //审批部门
                Company auditCompany = this.getAuditCompanyHead(visitMember.getCompanyId(),approveParam.getObjLevel());
                if(Objects.isNull(auditCompany)){
                    //审批部门为空 自动流转下一级审批配置
                    level = level + 1;
                    return this.getApproveIds(level,visitMember,ids);
                }else{
                    //查询部门负责人
                    Member headMember = memberMapper.selectById(auditCompany.getHeadId());
                    if(Objects.isNull(headMember)){
                        //未查询到部门负责人
                        if(approveParam.getNoleaderOpt().equals(Constants.ONE)&&!Objects.isNull(auditCompany.getParentId())){
                            //由上级主管代替审核
                            auditCompany = companyMapper.selectOne(new QueryWrapper<Company>().lambda().eq(Company::getId,auditCompany.getParentId()));
                            if(Objects.isNull(auditCompany)){
                                //审批部门为空 自动流转下一级审批配置
                                level = level + 1;
                                this.getApproveIds(level,visitMember,ids);
                            }else{
                                headMember = memberMapper.selectById(auditCompany.getHeadId());
                                if(Objects.isNull(headMember)){
                                    //查询部门负责人 为空 自动流转下一级审批配置
                                    level = level + 1;
                                    return this.getApproveIds(level,visitMember,ids);
                                }else{
                                    //添加审批人
                                    ids.add(headMember.getId());
                                }
                            }
                        }else{
                            level = level + 1;
                            return this.getApproveIds(level,visitMember,ids);
                        }
                    }else{
                        //添加审批人
                        ids.add(headMember.getId());
                    }
                }
            }
        }
        return approveParam;
    }
    /**
     * 根据配置查询上级数据
     * @param companyId 直接部门
     * @param objLevel  查询级别
     */
    public Company getAuditCompanyHead(Integer companyId,Integer objLevel){
        Integer queryLevel = Constants.ONE;
        Integer nextCompanyId = companyId;
        Company auditCompany = new Company();
        while(queryLevel.equals(objLevel)){
            auditCompany = companyMapper.selectById(nextCompanyId);
            if(Objects.isNull(auditCompany)){
                return null;
            }
            nextCompanyId = auditCompany.getParentId();
        }
        return auditCompany;
    }
    /**
     * 校验必填项数据是否合法
     * @param visits
     */
    private void isValidBaseParam(Visits visits) {
        if(visits.getStarttime() == null
                || visits.getEndtime() == null
        if(visits.getEndtime() == null
                || visits.getStarttime() == null
                ||  StringUtils.isBlank(visits.getReason())
                ||  StringUtils.isBlank( visits.getName())
                ||  StringUtils.isBlank( visits.getPhone())
                ||  StringUtils.isBlank( visits.getCompanyName())
                ||  visits.getIdcardType() == null
                ||  StringUtils.isBlank( visits.getFaceImg() )
//                ||  StringUtils.isBlank( visits.getFaceImg() )
                ||  StringUtils.isBlank( visits.getIdcardNo() )
                || visits.getReceptMemberId() == null){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,信息填写不正确!");
        }
        if(visits.getStarttime().getTime() < System.currentTimeMillis()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约开始时间必须大于当前时间!");//
        if(visits.getEndtime().getTime() < System.currentTimeMillis()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约结束时间必须大于当前时间!");//
        }
        if(visits.getEndtime().getTime() <= visits.getStarttime().getTime()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约结束时间必须大于开始时间!");//
        }
        if(visits.getSourceType().equals(Constants.ZERO)){
            String code = systemDictDataBiz.queryByCode(Constants.VISIT_CONFIG,Constants.VALIDATE_VISIT).getCode();
            int codenum =0;
            try {
                codenum = Integer.parseInt(code);
            }catch (Exception e){
            }
            if(StringUtils.isNotBlank(code)&&!StringUtils.equals(code,"0")){
//                Integer betweenDays = Math.toIntExact(cn.hutool.core.date.DateUtil.between(visits.getEndtime(), visits.getStarttime(), DateUnit.DAY));
                int betweenDays = DateUtil.daysBetweenDates11(visits.getEndtime(), visits.getStarttime())+1;
                if( betweenDays > codenum){
                    throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约总天数不能超过["+code+"天]!");
                }
            }
        }
    }
    private void isValidWithVisitParam(Visits visits,  List<Member> addList,  List<Member> updateList) {
@@ -135,9 +611,9 @@
                ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,信息填写不正确!");
        }
        if(visits.getStarttime().getTime() < System.currentTimeMillis()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约开始时间必须大于当前时间!");//
        }
//        if(visits.getStarttime().getTime() < System.currentTimeMillis()){
//            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约开始时间必须大于当前时间!");//
//        }
        if(visits.getEndtime().getTime() <= visits.getStarttime().getTime()){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,预约结束时间必须大于开始时间!");//
        }
@@ -165,16 +641,27 @@
    }
    private void initWithVisitInfo(Visits visits) {
        if(visits.getWithUserList()!=null && visits.getLwWithUserList().size()>0){
        if(CollectionUtils.isNotEmpty(visits.getWithUserList())){
            for(Visits v :visits.getWithUserList()){
                v.setBirthday(Constants.getBirthdyByCardNo(v.getIdcardNo()));
                v.setParentId(visits.getId());
                v.setStarttime(visits.getStarttime());
                v.setEndtime(visits.getEndtime());
                v.setIsdeleted(Constants.ZERO);
                v.setCreateDate(visits.getCreateDate());
                v.setSex(Constants.getSexByCardNo(v.getIdcardNo()));
                v.setIdcardDecode(Constants.getTuominStr(v.getIdcardNo()));//脱敏身份证号
                v.setIdcardNo(DESUtil.encrypt(Constants.EDS_PWD, v.getIdcardNo()));//身份证号加密
                v.setErpId(visits.getErpId());
                v.setReceptMemberId(visits.getReceptMemberId());
                v.setMemberNum(Constants.ZERO);
                v.setHkStatus(Constants.ZERO);
                v.setStatus(Constants.ZERO);
                v.setReason(visits.getReason());
                v.setDoors(visits.getDoors());
                v.setType(visits.getType());
                v.setVisitType(visits.getVisitType());
                v.setStatus(visits.getStatus());
                v.setSourceType(visits.getSourceType());
            }
            //批量插入数据
            visitsMapper.insertBatchSomeColumn(visits.getWithUserList());
@@ -185,15 +672,66 @@
        visits.setHkStatus(Constants.ZERO);//未同步
        visits.setBirthday(Constants.getBirthdyByCardNo(visits.getIdcardNo()));
        visits.setStatus(Constants.ZERO);//待审批
        visits.setSex(Constants.getSexByCardNo(visits.getIdcardNo()));
        visits.setIdcardDecode(Constants.getTuominStr(visits.getIdcardNo()));//脱敏身份证号
        visits.setIdcardNo(DESUtil.encrypt(Constants.EDS_PWD, visits.getIdcardNo()));//身份证号加密
        //身份证号存储密文
        visits.setIdcardDecode(Constants.getTuominStr(visits.getIdcardNo()));//脱敏手机号
        visits.setIsdeleted(Constants.ZERO);
        visits.setCreateDate(date);
    }
    private String startSendErpCheck(Visits visits) {
    private String startSendErpCheck(Visits visits,Member visitMember) {
        ApproveAddRequest param = new ApproveAddRequest();
        List<Visits> withUserVisitsList = visits.getWithUserList();
        List<UserInfoRequest> withUserList = new ArrayList<>();
        UserInfoRequest mainUser = new UserInfoRequest();
        mainUser.setName(visits.getName());
        mainUser.setIdNo(DESUtil.decrypt(Constants.EDS_PWD, visits.getIdcardNo()));
        mainUser.setSex(visits.getSex());
        mainUser.setPhone(visits.getPhone());
        mainUser.setFaceImg(visits.getFaceImg());
        mainUser.setHealthImg(visits.getImgurl());
        withUserList.add(mainUser);
        if(CollectionUtils.isNotEmpty(withUserVisitsList)){
            for (Visits v:withUserVisitsList) {
                UserInfoRequest userInfoRequest = new UserInfoRequest();
                userInfoRequest.setName(v.getName());
                userInfoRequest.setIdNo(v.getIdcardNo());
                userInfoRequest.setSex(v.getSex());
                userInfoRequest.setPhone(v.getPhone());
                userInfoRequest.setFaceImg(v.getFaceImg());
                userInfoRequest.setHealthImg(v.getImgurl());
                withUserList.add(userInfoRequest);
            }
        }
        param.setWithUserList(withUserList);
        param.setId(visits.getId());
        param.setBeVisitedUserId(visitMember.getErpId());
        param.setVisitorWorkUint(visits.getCompanyName());
        param.setPurpose(visits.getReason());
        param.setStartTime(DateUtil.DateToStr(visits.getStarttime(),"yyyy-MM-dd HH:mm:ss"));
        param.setEndTime(DateUtil.DateToStr(visits.getEndtime(),"yyyy-MM-dd HH:mm:ss"));
        param.setBeVisitedOrgId(visitMember.getErpOrgId());
        if(StringUtils.isNotBlank(visits.getCarNos())){
            param.setCarNo(Arrays.asList(visits.getCarNos().split(",")));
        }
        if(StringUtils.isNotBlank(visits.getDoors())){
             List<DeviceRole> deviceRoleList = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda().in(DeviceRole::getId,Arrays.asList(visits.getDoors().split(","))));
             if(CollectionUtils.isNotEmpty(deviceRoleList)){
                 param.setRoleIds(deviceRoleList.stream().map(m->m.getId()).collect(Collectors.toList()));
                 param.setRoleNames(deviceRoleList.stream().map(m->m.getName()).collect(Collectors.toList()));
             }
        }
        ApproveInfoResponse response   = erpTool.submitApprove(ErpConstants.approveUrl,param);
        if(!Objects.isNull(response)){
            return visits.getId().toString();
        }
        return  null;
    }
    private String visitAppiontment(Visits visits) {
        VisitAppointmentRequest param = new VisitAppointmentRequest();
@@ -233,57 +771,106 @@
        //随访人员信息处理
        if(visits.getWithUserList()!= null && visits.getWithUserList().size()>0){
            for(Visits model:visits.getWithUserList()){
                model.setBirthday(Constants.getBirthdyByCardNo(model.getIdcardNo()));
                model.setStarttime(visits.getStarttime());
                model.setEndtime(visits.getEndtime());
                //校验随访人员填报数据合法性
                isValidWithVisitParam(model,addList,editList);
                model.setCreateDate(visits.getCreateDate());
                getMemberListParam(model.getIdcardNo(),visits,addList,editList);
                Member visitsMember = getMemberListParam(model.getIdcardNo(),model,addList,editList);
                model.setMemberId(visitsMember.getId());
            }
        }
//        if(CollectionUtils.isNotEmpty(addList)){
//            memberMapper.insertBatchSomeColumn(addList);
//        }
//        if(CollectionUtils.isNotEmpty(editList)){
//            editList.forEach(i->{
//                memberMapper.updateById(i);
//            });
//
//        }
        return  m;
    }
    private Member getMemberListParam(String cardno, Visits visits, List<Member> addList, List<Member> editList) {
        if(!Constants.checkCarNo(visits.getCarNos())){
        if(StringUtils.isNotBlank(visits.getCarNos())
                &&Objects.isNull(Constants.getVehiclePlateNo(visits.getCarNos()))
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,车牌号【"+visits.getCarNos()+"】不合法,请核实后重试~");
        }
        if(Constants.equalsInteger(Constants.ZERO, visits.getIdcardType())&&cardno.length()!=18
            //&&!IdcardUtil.isValidCard(cardno)
        ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,身份证【"+cardno+"】号码有误,请核实后重试!");
        }
        Member member = memberMapper.selectOne(new QueryWrapper<Member>().lambda()
                .eq(Member::getType,Constants.memberType.visitor)
                .eq(Member::getIdcardType,visits.getIdcardType())
                .eq(Member::getIdcardNo,visits.getIdcardNo()).last("limit 1" )
                .eq(Member::getIdcardNo,DESUtil.encrypt(Constants.EDS_PWD, cardno)).last("limit 1" )
        );
        if(member == null){
            member = new Member();
            //如果用户不存在,则新增
            member.setCreateDate(visits.getCreateDate());
            member.setIsdeleted(Constants.ZERO);
            member.setIdcardNo(visits.getIdcardNo());
            member.setBirthday(Constants.getBirthdyByCardNo(cardno));
            member.setIdcardDecode(visits.getIdcardDecode());
            member.setIdcardNo(DESUtil.encrypt(Constants.EDS_PWD, cardno));//身份证号加密
            member.setIdcardDecode(Constants.getTuominStr(cardno));//脱敏手机号
            member.setFaceImg(visits.getFaceImg());
            member.setSex(Constants.getSexByCardNo(cardno));
            member.setImgurl(StringUtils.isNotBlank(visits.getImgurl())?visits.getImgurl():null);
            member.setIdcardType(visits.getIdcardType());
            member.setName(visits.getName());
            member.setPhone(visits.getPhone());
            member.setOpenid(visits.getOpenid());
            member.setType(Constants.memberType.visitor);
            member.setStatus(Constants.ZERO);
            member.setSex(visits.getSex());
            // 新增访客记录
            addList.add(member);
            member.setSex(Constants.getSexByCardNo(cardno));
            member.setHkStatus(Constants.ZERO);
            member.setErpStatus(Constants.ZERO);
            member.setVisitCompanyName(visits.getCompanyName());
            memberMapper.insert(member);
            // 新增访客
//            addList.add(member);
        }else{
            if(!Constants.equalsInteger(Constants.ZERO,member.getStatus() )){
                //如果用户状态异常,则提示
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该身份证号被禁止访问申请,如有疑问,请联系您的拜访人进行核实");
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,身份证号【"+cardno+"】被禁止访问申请,如有疑问,请联系您的拜访人进行核实");
            }
            //核查预约用户是否存在未签离的预约记录
            isExsitNoOutVisisRecord(member);
//            isExsitNoOutVisisRecord(member);
            member.setFaceImg(visits.getFaceImg());
            member.setImgurl(StringUtils.isNotBlank(visits.getImgurl())?visits.getImgurl():null);
            member.setEditDate(visits.getCreateDate());
            member.setIsdeleted(Constants.ZERO);
            member.setIdcardNo(visits.getIdcardNo());
            member.setIdcardDecode(visits.getIdcardDecode());
            member.setSex(Constants.getSexByCardNo(cardno));
            member.setIdcardNo(DESUtil.encrypt(Constants.EDS_PWD, cardno));//身份证号加密
            member.setIdcardDecode(Constants.getTuominStr(cardno));//脱敏身份证号
            member.setName(visits.getName());
            member.setPhone(visits.getPhone());
            member.setOpenid(visits.getOpenid());
            member.setSex(visits.getSex());
            // 更新访客信息,
            editList.add(member);
            member.setSex(Constants.getSexByCardNo(cardno));
            member.setHkStatus(Constants.ZERO);
            member.setErpStatus(Constants.ZERO);
            member.setVisitCompanyName(visits.getCompanyName());
            memberMapper.updateById(member);
        }
        //根据手机号和身份证号码查询 当前预约的时间是否与其他预约记录有冲突
        if (visitsMapper.selectCount(new QueryWrapper<Visits>().lambda()
                        .notIn(Visits::getStatus,Constants.VisitStatus.cancel,Constants.VisitStatus.noPass,Constants.VisitStatus.xfFail,Constants.VisitStatus.signout,Constants.VisitStatus.invalid)
                .eq(Visits::getIdcardDecode, Constants.getTuominStr(cardno))
                .and(ms -> ms.eq(Visits::getPhone, visits.getPhone())
                        .or().eq(Visits::getIdcardDecode, Constants.getTuominStr(cardno)))
                .and(ms -> ms.apply(" visits.STARTTIME <= '" + DateUtil.DateToStr(visits.getStarttime(),"yyyy-MM-dd HH:mm:ss") + "' and visits.ENDTIME >= '" + DateUtil.DateToStr(visits.getStarttime(),"yyyy-MM-dd HH:mm:ss") + "' ")
                        .or().apply(" visits.STARTTIME <= '" + DateUtil.DateToStr(visits.getEndtime(),"yyyy-MM-dd HH:mm:ss") + "' and visits.ENDTIME >= '" + DateUtil.DateToStr(visits.getEndtime(),"yyyy-MM-dd HH:mm:ss") + "' ")
                )) > Constants.ZERO) {
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,手机号【"+member.getPhone()+"】或身份证【"+ member.getIdcardDecode() +"】存在预约时间冲突,无法申请哦!");
        }
        return  member;
    }
@@ -301,6 +888,9 @@
        if(v !=null){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,手机号【"+member.getPhone()+"】存在未签离预约申请,不能重复申请哦!");
        }
    }
    private List<Member> isValideWithUsers(List<Visits> withUserList) {
@@ -323,6 +913,7 @@
    private void updateProblemLog(Visits visits, ProblemLog problemLog,Member member) {
        if(problemLog!=null){
            problemLog.setEditDate(visits.getCreateDate());
            problemLog.setStatus(Constants.ONE);
            problemLog.setName(visits.getName());
            problemLog.setUserId(member.getId());
            problemLog.setPhone(member.getPhone());
@@ -337,7 +928,7 @@
     */
    private Member isValideVisitedUser(Integer receptMemberId) {
        Member member = memberMapper.selectById(receptMemberId);
        if(member == null || Constants.equalsInteger(Constants.ZERO,member.getIsdeleted())){
        if(member == null || !Constants.equalsInteger(Constants.ZERO,member.getIsdeleted())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,该拜访人暂时不能接受您的拜访申请!");
        }
        if(!Constants.equalsInteger(member.getStatus(), Constants.ZERO)){
@@ -346,12 +937,15 @@
        if(!Constants.equalsInteger(Constants.ONE, member.getCanVisit())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,该拜访人暂时不能接受您的拜访申请~");
        }
        if(StringUtils.isBlank(member.getHkId())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,该拜访人未下发暂时不能接受您的拜访申请~");
        }
        return  member;
    }
    private ProblemLog isValidProblemLog(Visits visits) {
        String required = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.PROBLEM_VISIT_REQUIRED).getCode();
        if(StringUtils.equals(required,Constants.ONE+"")){
        if(StringUtils.equals(required,Constants.ONE+"")&&visits.getSourceType()==Constants.ZERO){
            //如果必须答题,查找答题记录
            if(visits.getUserAnswerId() == null){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请先按要求进行安全知识答题!");
@@ -360,7 +954,7 @@
            if(log == null){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请先按要求进行安全知识答题.");
            }
            if(log.getLogId() !=null){
            if(log.getLogId() !=null&&log.getStatus().equals(Constants.ZERO)){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请先按要求进行安全知识答题~");
            }
            return  log;
@@ -373,15 +967,25 @@
     * @param visits
     * @return
     */
    private String[] getHkDeviceRoles(Visits visits) {
    private String[] getHkDeviceRoles(Visits visits,Boolean isERP) {
        String mustSelectDoors = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.SELECT_DOORS_VISIT_REQUIRED).getCode();
        if(isERP){
            mustSelectDoors = Constants.ONE+"";
        }
        List<DeviceRole> roles = null;
        if(StringUtils.equals(mustSelectDoors,Constants.ZERO+"")){
            roles = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda()
                    .eq(DeviceRole::getIsDefault,Constants.ZERO)
                    .eq(DeviceRole::getIsdeleted,Constants.ZERO)
                    .eq(DeviceRole::getType,Constants.DeviceRoleType.fk));
            if(roles.size() ==0){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,暂不存在可访问的访客门禁,无法进行申请操作!");
            }
        }else{
            //如果必须选择门禁,但未选择
            if(StringUtils.isBlank(visits.getDoors())){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请选择访问门禁!");
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请选择有效访问门禁!");
            }
            //校验门禁组信息是否正确
            String[] dIds = visits.getDoors().split(",");
            roles = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda()
                    .eq(DeviceRole::getIsdeleted,Constants.ZERO)
@@ -389,17 +993,6 @@
                    .in(DeviceRole::getId, Arrays.asList(dIds)));
            if(roles == null || roles.size()==0 || roles.size() != dIds.length){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请选择有效访问门禁!");
            }
        }else{
            //如果设置不选择门禁,则提供默认门禁组信息
            String[] dIds = visits.getDoors().split(",");
            roles = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda()
                    .eq(DeviceRole::getIsdeleted,Constants.ZERO)
                    .eq(DeviceRole::getIsDefault,Constants.ZERO)
                    .eq(DeviceRole::getType,Constants.DeviceRoleType.fk));
            if(roles.size() ==0){
                throw  new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,暂不存在可访问的访客门禁,无法进行申请操作!");
            }
        }
        String[] ids =new String[roles.size()];
@@ -445,7 +1038,40 @@
    @Override
    public Visits findById(Integer id) {
        return visitsMapper.selectById(id);
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Visits.class);
        queryWrapper.selectAs(Member::getName,Visits::getReceptMemberName);
        queryWrapper.selectAs(Company::getName,Visits::getReceptMemberDepartment);
        queryWrapper.leftJoin(Member.class,Member::getId,Visits::getReceptMemberId);
        queryWrapper.leftJoin(Company.class,Company::getErpId,Member::getErpOrgId);
        queryWrapper.eq(Visits::getId,id);
        Visits result = visitsJoinMapper.selectJoinOne(Visits.class,queryWrapper);
        if(result!=null){
            if(StringUtils.isNotBlank(result.getDoors())){
                String[] doorList=result.getDoors().split(",");
                MPJLambdaWrapper<DeviceRole> deviceQuery = new MPJLambdaWrapper<>();
                deviceQuery.in(DeviceRole::getId,doorList);
                List<DeviceRole> deviceRoleList= deviceRoleMapper.selectList(deviceQuery);
                result.setDeviceRoleList(deviceRoleList);
            }
        }
        MPJLambdaWrapper<Visits> visitQuery = new MPJLambdaWrapper<>();
        visitQuery.selectAll(Visits.class);
        visitQuery.eq(Visits::getParentId,result.getId());
        visitQuery.isNotNull(Visits::getParentId);
        visitQuery.eq(Visits::getIsdeleted,Constants.ZERO);
        List<Visits> visitsList = visitsJoinMapper.selectList(visitQuery);
        Visits v = new Visits();
        BeanUtils.copyProperties(result,v);
        visitsList.add(0,v);
        result.setWithUserList(visitsList);
        result.setPrefixUrl(systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_RESOURCE_PATH).getCode() +
                systemDictDataBiz.queryByCode(Constants.FTP,Constants.MEMBER_IMG).getCode());
        return result;
    }
    @Override
@@ -463,147 +1089,32 @@
    @Override
    public PageData<Visits> findPage(PageWrap<Visits> pageWrap) {
        IPage<Visits> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<Visits> queryWrapper = new QueryWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(Visits::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.lambda().eq(Visits::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.lambda().ge(Visits::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.lambda().le(Visits::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.lambda().eq(Visits::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.lambda().ge(Visits::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.lambda().le(Visits::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.lambda().eq(Visits::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getRemark() != null) {
            queryWrapper.lambda().eq(Visits::getRemark, pageWrap.getModel().getRemark());
        }
        if (pageWrap.getModel().getMemberId() != null) {
            queryWrapper.lambda().eq(Visits::getMemberId, pageWrap.getModel().getMemberId());
        }
        if (pageWrap.getModel().getCompanyId() != null) {
            queryWrapper.lambda().eq(Visits::getCompanyId, pageWrap.getModel().getCompanyId());
        }
        if (pageWrap.getModel().getFaceImg() != null) {
            queryWrapper.lambda().eq(Visits::getFaceImg, pageWrap.getModel().getFaceImg());
        }
        if (pageWrap.getModel().getImgurl() != null) {
            queryWrapper.lambda().eq(Visits::getImgurl, pageWrap.getModel().getImgurl());
        }
        if (pageWrap.getModel().getType() != null) {
            queryWrapper.lambda().eq(Visits::getType, pageWrap.getModel().getType());
        }
        if (pageWrap.getModel().getName() != null) {
            queryWrapper.lambda().eq(Visits::getName, pageWrap.getModel().getName());
        }
        if (pageWrap.getModel().getBirthday() != null) {
            queryWrapper.lambda().ge(Visits::getBirthday, Utils.Date.getStart(pageWrap.getModel().getBirthday()));
            queryWrapper.lambda().le(Visits::getBirthday, Utils.Date.getEnd(pageWrap.getModel().getBirthday()));
        }
        if (pageWrap.getModel().getPhone() != null) {
            queryWrapper.lambda().eq(Visits::getPhone, pageWrap.getModel().getPhone());
        }
        if (pageWrap.getModel().getCompanyName() != null) {
            queryWrapper.lambda().eq(Visits::getCompanyName, pageWrap.getModel().getCompanyName());
        }
        if (pageWrap.getModel().getIdcardNo() != null) {
            queryWrapper.lambda().eq(Visits::getIdcardNo, pageWrap.getModel().getIdcardNo());
        }
        if (pageWrap.getModel().getCode() != null) {
            queryWrapper.lambda().eq(Visits::getCode, pageWrap.getModel().getCode());
        }
        if (pageWrap.getModel().getClasses() != null) {
            queryWrapper.lambda().eq(Visits::getClasses, pageWrap.getModel().getClasses());
        }
        if (pageWrap.getModel().getMemberNum() != null) {
            queryWrapper.lambda().eq(Visits::getMemberNum, pageWrap.getModel().getMemberNum());
        }
        if (pageWrap.getModel().getStarttime() != null) {
            queryWrapper.lambda().ge(Visits::getStarttime, Utils.Date.getStart(pageWrap.getModel().getStarttime()));
            queryWrapper.lambda().le(Visits::getStarttime, Utils.Date.getEnd(pageWrap.getModel().getStarttime()));
        }
        if (pageWrap.getModel().getEndtime() != null) {
            queryWrapper.lambda().ge(Visits::getEndtime, Utils.Date.getStart(pageWrap.getModel().getEndtime()));
            queryWrapper.lambda().le(Visits::getEndtime, Utils.Date.getEnd(pageWrap.getModel().getEndtime()));
        }
        if (pageWrap.getModel().getReason() != null) {
            queryWrapper.lambda().eq(Visits::getReason, pageWrap.getModel().getReason());
        }
        if (pageWrap.getModel().getDoorSelect() != null) {
            queryWrapper.lambda().eq(Visits::getDoorSelect, pageWrap.getModel().getDoorSelect());
        }
        if (pageWrap.getModel().getDoors() != null) {
            queryWrapper.lambda().eq(Visits::getDoors, pageWrap.getModel().getDoors());
        }
        if (pageWrap.getModel().getReceptMemberId() != null) {
            queryWrapper.lambda().eq(Visits::getReceptMemberId, pageWrap.getModel().getReceptMemberId());
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.lambda().eq(Visits::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getCheckorId() != null) {
            queryWrapper.lambda().eq(Visits::getCheckorId, pageWrap.getModel().getCheckorId());
        }
        if (pageWrap.getModel().getCheckDate() != null) {
            queryWrapper.lambda().ge(Visits::getCheckDate, Utils.Date.getStart(pageWrap.getModel().getCheckDate()));
            queryWrapper.lambda().le(Visits::getCheckDate, Utils.Date.getEnd(pageWrap.getModel().getCheckDate()));
        }
        if (pageWrap.getModel().getCheckInfo() != null) {
            queryWrapper.lambda().eq(Visits::getCheckInfo, pageWrap.getModel().getCheckInfo());
        }
        if (pageWrap.getModel().getEndCheckorId() != null) {
            queryWrapper.lambda().eq(Visits::getEndCheckorId, pageWrap.getModel().getEndCheckorId());
        }
        if (pageWrap.getModel().getEndCheckDate() != null) {
            queryWrapper.lambda().ge(Visits::getEndCheckDate, Utils.Date.getStart(pageWrap.getModel().getEndCheckDate()));
            queryWrapper.lambda().le(Visits::getEndCheckDate, Utils.Date.getEnd(pageWrap.getModel().getEndCheckDate()));
        }
        if (pageWrap.getModel().getEndCheckInfo() != null) {
            queryWrapper.lambda().eq(Visits::getEndCheckInfo, pageWrap.getModel().getEndCheckInfo());
        }
        if (pageWrap.getModel().getIdcardType() != null) {
            queryWrapper.lambda().eq(Visits::getIdcardType, pageWrap.getModel().getIdcardType());
        }
        if (pageWrap.getModel().getCarNos() != null) {
            queryWrapper.lambda().eq(Visits::getCarNos, pageWrap.getModel().getCarNos());
        }
        if (pageWrap.getModel().getParentId() != null) {
            queryWrapper.lambda().eq(Visits::getParentId, pageWrap.getModel().getParentId());
        }
        if (pageWrap.getModel().getUserAnswerId() != null) {
            queryWrapper.lambda().eq(Visits::getUserAnswerId, pageWrap.getModel().getUserAnswerId());
        }
        if (pageWrap.getModel().getHkId() != null) {
            queryWrapper.lambda().eq(Visits::getHkId, pageWrap.getModel().getHkId());
        }
        if (pageWrap.getModel().getHkStatus() != null) {
            queryWrapper.lambda().eq(Visits::getHkStatus, pageWrap.getModel().getHkStatus());
        }
        if (pageWrap.getModel().getHkDate() != null) {
            queryWrapper.lambda().ge(Visits::getHkDate, Utils.Date.getStart(pageWrap.getModel().getHkDate()));
            queryWrapper.lambda().le(Visits::getHkDate, Utils.Date.getEnd(pageWrap.getModel().getHkDate()));
        }
        if (pageWrap.getModel().getErpId() != null) {
            queryWrapper.lambda().eq(Visits::getErpId, pageWrap.getModel().getErpId());
        }
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Visits.class);
        queryWrapper.select("  ( select count(distinct(v.CAR_NOS)) from visits v where v.PARENT_ID = t.ID and v.CAR_NOS is not null  and v.CAR_NOS != ''  and v.CAR_NOS != t.CAR_NOS ) as carNum  ");
        queryWrapper.selectAs(Member::getName,Visits::getReceptMemberName);
        queryWrapper.selectAs(Company::getName,Visits::getReceptMemberDepartment);
        queryWrapper.leftJoin(Member.class,Member::getId,Visits::getReceptMemberId);
        queryWrapper.leftJoin(Company.class,Company::getId,Member::getCompanyId);
        queryWrapper.eq(Visits::getIsdeleted,Constants.ZERO);
        queryWrapper.eq(Objects.nonNull(pageWrap.getModel().getType()),Visits::getType,pageWrap.getModel().getType());
        queryWrapper.and(StringUtils.isNotBlank(pageWrap.getModel().getName()),ms->ms.like(Visits::getName,pageWrap.getModel().getName())
                .or().like(Visits::getPhone,pageWrap.getModel().getName()))
                .eq(StringUtils.isNotBlank(pageWrap.getModel().getIdcardNo()),Visits::getIdcardNo,DESUtil.encrypt(Constants.EDS_PWD, pageWrap.getModel().getIdcardNo()))
                .eq(StringUtils.isNotBlank(pageWrap.getModel().getCompanyName()),Visits::getCompanyName,pageWrap.getModel().getCompanyName())
                .eq(Objects.nonNull(pageWrap.getModel().getStatus()),Visits::getStatus,pageWrap.getModel().getStatus());
        queryWrapper.isNull(Visits::getParentId);
        queryWrapper.orderByDesc(Visits::getCreateDate);
        IPage<Visits> result = visitsJoinMapper.selectJoinPage(page, Visits.class,queryWrapper);
        for (Visits visits:result.getRecords()) {
            if(StringUtils.isNotBlank(visits.getCarNos())){
                visits.setCarNum(visits.getCarNum() + Constants.ONE);
            }
        }
        return PageData.from(visitsMapper.selectPage(page, queryWrapper));
        return PageData.from(result);
    }
    @Override
@@ -611,4 +1122,179 @@
        QueryWrapper<Visits> wrapper = new QueryWrapper<>(visits);
        return visitsMapper.selectCount(wrapper);
    }
    @Override
    public PageData<Visits> retentionPage(PageWrap<Visits> pageWrap) {
        String code= systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.TIMEOUT_WARNING).getCode();
        IPage<Visits> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Visits.class);
        queryWrapper.selectAs(Member::getName,Visits::getReceptMemberName);
        queryWrapper.select("TIMESTAMPDIFF( MINUTE, NOW(), t.OUT_DATE) AS timeOut");
        queryWrapper.selectAs(Member::getType,Visits::getMemberType);
        queryWrapper.selectAs(Company::getName,Visits::getReceptMemberDepartment);
        queryWrapper.leftJoin(Member.class,Member::getId,Visits::getReceptMemberId);
        queryWrapper.leftJoin(Company.class,Company::getId,Member::getCompanyId);
        queryWrapper.leftJoin(" member m on m.id= t.MEMBER_ID");
        queryWrapper.eq(Objects.nonNull(pageWrap.getModel().getLevelStatus()),Visits::getStatus,Constants.VisitStatus.signin);
        queryWrapper.apply(Objects.nonNull(pageWrap.getModel().getLevelStatus())," TIMESTAMPDIFF( MINUTE, NOW(), t.OUT_DATE) <= "+code+"  ");
        queryWrapper.ne("m.type ",Constants.TWO);
        queryWrapper.eq(Visits::getIsdeleted,Constants.ZERO);
        queryWrapper.eq(Objects.nonNull(pageWrap.getModel().getType()),Visits::getType,pageWrap.getModel().getType());
        queryWrapper.and(StringUtils.isNotBlank(pageWrap.getModel().getName()),ms->ms.like(Visits::getPhone,pageWrap.getModel().getName())
                .or().like(Visits::getName,pageWrap.getModel().getName()));
        queryWrapper.eq(StringUtils.isNotBlank(pageWrap.getModel().getIdcardNo()),Visits::getIdcardNo,StringUtils.isNotBlank(pageWrap.getModel().getIdcardNo()));
        queryWrapper.eq(StringUtils.isNotBlank(pageWrap.getModel().getCompanyName()),Visits::getCompanyName,pageWrap.getModel().getCompanyName());
        queryWrapper.orderByDesc(Visits::getEditDate);
        IPage<Visits> result = visitsJoinMapper.selectJoinPage(page, Visits.class,queryWrapper);
        if(result!=null&&result.getRecords()!=null){
            result.getRecords().stream().forEach(s ->{
                if(s.getStatus().equals(Constants.VisitStatus.signin)){
                    if(s.getTimeOut()<=Integer.valueOf(code)&&s.getTimeOut()>=0){
                        s.setOutStatus(Constants.TWO);
                    }else if(s.getTimeOut()>Constants.ZERO){
                        s.setOutStatus(Constants.ZERO);
                    }else{
                        s.setOutStatus(Constants.ONE);
                    }
                }
            });
        }
        return PageData.from(result);
    }
    @Override
    public VisitDetailVO getVisitDetail(Integer id){
        Visits visits = visitsMapper.selectById(id);
        if(Objects.isNull(visits)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        Member member = memberMapper.selectById(visits.getReceptMemberId());
        if(Objects.isNull(member)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到被访员工信息");
        }
        VisitDetailVO visitDetailVO = new VisitDetailVO();
        visitDetailVO.setStatus(visits.getStatus());
        visitDetailVO.setCarNos(visits.getCarNos());
        visitDetailVO.setPhone(visits.getPhone());
        visitDetailVO.setVisitUserName(member.getName());
        visitDetailVO.setVisitReason(visits.getReason());
        visitDetailVO.setQrcode(visits.getQrcode());
        visitDetailVO.setVisitTime(DateUtil.DateToStr(visits.getStarttime(),"yyyy-MM-dd HH:mm") + " 至 " + DateUtil.DateToStr(visits.getEndtime(),"yyyy-MM-dd HH:mm") );
        //被访人员部门
        Company company = companyMapper.selectById(member.getCompanyId());
        if(!Objects.isNull(company)){
            visitDetailVO.setVisitUserCompany(company.getName());
        }
        visitDetailVO.setName(visits.getName());
            visitDetailVO.setCompanyName(visits.getCompanyName());
            visitDetailVO.setFaceImg(visits.getFaceImg());
            visitDetailVO.setImgUrl(visits.getImgurl());
            visitDetailVO.setIdCardDecode(visits.getIdcardDecode());
            visitDetailVO.setPrefix(systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_RESOURCE_PATH).getCode() +
                    systemDictDataBiz.queryByCode(Constants.FTP,Constants.MEMBER_IMG).getCode());
        if(StringUtils.isNotBlank(visits.getDoors())){
            List<DeviceRole> deviceRoleList = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda()
                            .select(DeviceRole::getName)
                            .eq(DeviceRole::getIsdeleted,Constants.ZERO)
                    .in(DeviceRole::getId,visits.getDoors().split(",")));
            if(CollectionUtils.isNotEmpty(deviceRoleList)){
                visitDetailVO.setDoorGroupName(
                        deviceRoleList.stream().map(m->m.getName()).collect(Collectors.toList())
                );
            }
        }
        visitDetailVO.setWithVisitsList(
                visitsMapper.selectList(new QueryWrapper<Visits>().lambda()
                .select(Visits::getName,Visits::getPhone,Visits::getQrcode,Visits::getFaceImg,Visits::getImgurl,Visits::getIdcardDecode,Visits::getStatus)
                .eq(Visits::getParentId,id)));
        return visitDetailVO;
    }
    @Override
    public PageData<VisitRecordVO> taskCenter(PageWrap<VisitRecordDTO> param) {
        VisitRecordDTO visitRecordDTO = param.getModel();
        IPage<Visits> page = new Page<>(param.getPage(), param.getCapacity());
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(visitRecordDTO);
        queryWrapper.selectAs(Visits::getId,VisitRecordVO::getId);
        queryWrapper.selectAs(Visits::getName,VisitRecordVO::getName);
        queryWrapper.selectAs(Visits::getStarttime,VisitRecordVO::getStartTime);
        queryWrapper.selectAs(Visits::getEndtime,VisitRecordVO::getEndTime);
        queryWrapper.selectAs(Visits::getReason,VisitRecordVO::getReason);
        queryWrapper.selectAs(Visits::getMemberNum,VisitRecordVO::getInNum);
        queryWrapper.selectAs(Visits::getCreateDate,VisitRecordVO::getCreateDate);
        queryWrapper.leftJoin(Approve.class,Approve::getId,Visits::getId);
        if(!Objects.isNull(visitRecordDTO)){
            queryWrapper.like(StringUtils.isNotBlank(visitRecordDTO.getName()),Visits::getName,visitRecordDTO.getName());
            queryWrapper.le(!Objects.isNull(visitRecordDTO.getCreateTimeS()),Visits::getCreateDate,visitRecordDTO.getCreateTimeS());
            queryWrapper.ge(!Objects.isNull(visitRecordDTO.getCreateTimeE()),Visits::getCreateDate,visitRecordDTO.getCreateTimeE());
            queryWrapper.eq(!Objects.isNull(visitRecordDTO.getType()),Visits::getType,visitRecordDTO.getType());
            if(!Objects.isNull(visitRecordDTO.getState())&&visitRecordDTO.getState()<Constants.TWO){
                queryWrapper.eq(Approve::getStatus,visitRecordDTO.getState());
                queryWrapper.eq(Approve::getChekorId,visitRecordDTO.getMemberId());
            }else if(!Objects.isNull(visitRecordDTO.getState())&&visitRecordDTO.getState()==Constants.TWO){
                queryWrapper.eq(Visits::getMemberId,visitRecordDTO.getMemberId());
            }
        }
        queryWrapper.orderByDesc(Visits::getCreateDate);
        IPage<VisitRecordVO> result = visitsJoinMapper.selectJoinPage(page, VisitRecordVO.class,queryWrapper);
        return PageData.from(result);
    }
    @Override
    public void  visitLevel(Integer visitId){
        Visits visits = visitsMapper.selectById(visitId);
        if(Objects.isNull(visits)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!visits.getStatus().equals(Constants.VisitStatus.signin)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"访客记录状态错误,请刷新重试");
        }
        VisitAppointmentOutRequest request = new VisitAppointmentOutRequest();
        request.setOrderId(visits.getHkId());
        //调用海康强制签离
        BaseResponse response =  HKService.outVisitAppiontment(request);
        visitsMapper.update(null,new UpdateWrapper<Visits>().lambda().set(Visits::getStatus,Constants.VisitStatus.signout)
                .eq(Visits::getId,visitId));
        //产出在场人员信息
        retentionMapper.delete(new UpdateWrapper<Retention>().lambda()
                .eq(Retention::getType,Constants.memberType.visitor)
                .eq(Retention::getMemberId,visits.getMemberId()));
    }
    @Override
    public void  visitCancel(Integer visitId){
        Visits visits = visitsMapper.selectById(visitId);
        if(Objects.isNull(visits)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!visits.getStatus().equals(Constants.VisitStatus.xfSuccess)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"访客记录状态错误,请刷新重试");
        }
        VisitAppointmentOutRequest request = new VisitAppointmentOutRequest();
        request.setOrderId(visits.getHkId());
        //调用海康强制签离
        BaseResponse response =  HKService.outVisitAppiontment(request);
        visitsMapper.update(null,new UpdateWrapper<Visits>().lambda().set(Visits::getStatus,Constants.VisitStatus.signout)
                .eq(Visits::getId,visitId));
        //产出在场人员信息
        retentionMapper.delete(new UpdateWrapper<Retention>().lambda()
                .eq(Retention::getType,Constants.memberType.visitor)
                .eq(Retention::getMemberId,visits.getMemberId()));
    }
}