package com.yuchen.saas.park.service.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkunion.park.service.common.cache.CacheNames;
import com.thinkunion.park.service.common.pojo.HikIscResponse;
import com.thinkunion.park.service.common.utils.HikIscRequestUtil;
import com.yuchen.saas.device.api.vo.NetImportResVo;
import com.yuchen.saas.integration.feign.api.feign.CommonHikClient;
import com.yuchen.saas.integration.feign.api.util.HikApiUtil;
import com.yuchen.saas.manage.user.api.entity.User;
import com.yuchen.saas.manage.user.api.feign.IUserClient;
import com.yuchen.saas.message.api.dto.PmgBatMessageDto;
import com.yuchen.saas.message.api.feign.message.MessageFeignServer;
import com.yuchen.saas.park.api.dto.approve.PeopleApproveQueryDto;
import com.yuchen.saas.park.api.dto.approve.ResponseDataTypeDto;
import com.yuchen.saas.park.api.dto.elevator.DeviceDTO;
import com.yuchen.saas.park.api.dto.elevator.FloorDTO;
import com.yuchen.saas.park.api.dto.elevator.GroupDTO;
import com.yuchen.saas.park.api.dto.elevator.PermissionDTO;
import com.yuchen.saas.park.api.dto.people.PmgBatParkPeopleQryDto;
import com.yuchen.saas.park.api.dto.property.PropertyHousesDto;
import com.yuchen.saas.park.api.entity.approve.PeopleApprove;
import com.yuchen.saas.park.api.entity.approve.SaasGenericConfig;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorManageLocationEntity;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorPermissionElevatorGroup;
import com.yuchen.saas.park.api.entity.elevator.SaasParkElevatorPerson;
import com.yuchen.saas.park.api.entity.park.*;
import com.yuchen.saas.park.api.entity.park.people.SaasParkPropertyPeopleInfo;
import com.yuchen.saas.park.api.entity.property.PropertyBuildingsLevel;
import com.yuchen.saas.park.api.entity.property.PropertyCustomerArchives;
import com.yuchen.saas.park.api.enums.ServiceSourceEnum;
import com.yuchen.saas.park.api.enums.approve.ApproveConfigGroupEnum;
import com.yuchen.saas.park.api.enums.property.CreateTypeEnum;
import com.yuchen.saas.park.api.feign.client.MqttApiClient;
import com.yuchen.saas.park.api.param.PmgBatParkPeoplePageParam;
import com.yuchen.saas.park.api.vo.park.OldHikIscPersonVO;
import com.yuchen.saas.park.api.vo.park.PmgBatParkPeopleGroupPageVo;
import com.yuchen.saas.park.api.vo.park.PmgBatParkPeopleVo;
import com.yuchen.saas.park.api.vo.people.PmgBatParkPeopleExcelVo;
import com.yuchen.saas.park.api.vo.people.PmgBatParkPeoplePolyVo;
import com.yuchen.saas.park.service.config.AsyncParkConfig;
import com.yuchen.saas.park.service.mapper.PmgBatParkPeopleMapper;
import com.yuchen.saas.park.service.mapper.elevator.SaasParkElevatorManageLocationMapper;
import com.yuchen.saas.park.service.service.IPmgBatPersonSysconfigService;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.PmgBatParkPeopleService;
import com.yuchen.saas.park.service.service.PmgBatPeopleTypeService;
import com.yuchen.saas.park.service.service.approve.ISaasGenericConfigService;
import com.yuchen.saas.park.service.service.approve.PeopleApproveService;
import com.yuchen.saas.park.service.service.elevator.ISaasParkElevatorManageLocationService;
import com.yuchen.saas.park.service.service.elevator.ISaasParkElevatorPermissionElevatorGroupService;
import com.yuchen.saas.park.service.service.elevator.ISaasParkElevatorPersonService;
import com.yuchen.saas.park.service.service.people.ISaasParkPropertyPeopleInfoService;
import com.yuchen.saas.park.service.service.people.impl.SaasParkPropertyPeopleInfoServiceImpl;
import com.yuchen.saas.park.service.service.property.IPeoplePropertyRelationService;
import com.yuchen.saas.park.service.service.property.IPropertyCustomerArchivesService;
import com.yuchen.saas.park.service.service.property.PropertyBuildingsLevelService;
import com.yuchen.saas.park.service.util.PicToBase64Utils;
import com.yuchen.saas.visitor.api.feign.HikIscPeoplePrivilegeFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.pulsar.shade.org.apache.commons.lang3.StringEscapeUtils;
import org.nest.springwrap.core.excel.util.ExcelUtil;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.redis.cache.NestRedis;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.nest.springwrap.core.tool.utils.CollectionUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.nest.springwrap.core.tool.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import static com.alibaba.nacos.client.utils.EnvUtil.LOGGER;


/**
 * @author 刘通
 * @date 2020/12/8 10:16
 */

@Slf4j
@Service
public class PmgBatParkPeopleServiceImpl extends BaseServiceImpl<PmgBatParkPeopleMapper, PmgBatParkPeople> implements PmgBatParkPeopleService {

    /**
     * 注入海康远程调用
     */
    @Resource
    private CommonHikClient commonHikClient;

    /**
     * 注入园区
     */
    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;


    @Resource
    private ISaasParkElevatorManageLocationService iSaasParkElevatorManageLocationService;

    @Resource
    private SaasParkElevatorManageLocationMapper saasParkElevatorManageLocationMapper;


    @Resource
    private ISaasParkElevatorPermissionElevatorGroupService saasParkElevatorPermissionElevatorGroupService;


    @Resource
    private IPmgBatPersonSysconfigService iPmgBatPersonSysconfigService;


    @Resource
    private ISaasParkElevatorPersonService iSaasParkElevatorPersonService;

    /**
     * 注入人员类型操作接口
     */
    @Resource
    private PmgBatPeopleTypeService peopleTypeService;

    @Resource
    private MqttApiClient mqttXzClient;

    @Resource(name = AsyncParkConfig.EXECUTOR_BEAN_NAME)
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 人员类型
     */
    @Resource
    private PmgBatPeopleTypeService pmgBatPeopleTypeService;

    @Resource
    private HikIscPeoplePrivilegeFeignClient hikIscPeoplePrivilegeFeignClient;

    @Resource
    private ISaasGenericConfigService saasGenericConfigService;

    @Resource
    private PeopleApproveService peopleApproveService;


    @Resource
    private MessageFeignServer messageFeignServer;
    @Resource
    private IUserClient iUserClient;

    @Resource
    private IPropertyCustomerArchivesService iPropertyCustomerArchivesService;

    @Resource
    private IPeoplePropertyRelationService peoplePropertyRelationService;

    @Resource
    private PropertyBuildingsLevelService propertyBuildingsLevelService;

    @Resource
    private ISaasParkPropertyPeopleInfoService saasParkPropertyPeopleInfoService;

    @Override
    public IPage<PmgBatParkPeopleVo> getPage(PmgBatParkPeople pmgBatParkPeople, Query query) {
        LambdaQueryWrapper<PmgBatParkPeople> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(pmgBatParkPeople.getParkId() != null, PmgBatParkPeople::getParkId, pmgBatParkPeople.getParkId());
        wrapper.eq(pmgBatParkPeople.getPeopleType() != null, PmgBatParkPeople::getPeopleType, pmgBatParkPeople.getPeopleType());
        wrapper.eq(!Func.isEmpty(pmgBatParkPeople.getCompany()), PmgBatParkPeople::getCompany, pmgBatParkPeople.getCompany());
        wrapper.eq(!Func.isEmpty(pmgBatParkPeople.getOwnerType()), PmgBatParkPeople::getIsCompany, pmgBatParkPeople.getOwnerType());
        wrapper.like(!Func.isEmpty(pmgBatParkPeople.getName()), PmgBatParkPeople::getName, pmgBatParkPeople.getName());
        wrapper.like(!Func.isEmpty(pmgBatParkPeople.getPhone()), PmgBatParkPeople::getPhone, pmgBatParkPeople.getPhone());
        wrapper.orderByDesc(PmgBatParkPeople::getCreateTime);
        IPage<PmgBatParkPeople> page = page(Condition.getPage(query), wrapper);
        List<PmgBatParkPeople> records = page.getRecords();
        IPage<PmgBatParkPeopleVo> pageResult = new Page<>();
        BeanUtil.copyProperties(page, pageResult);
        // 查询人员列表
        Map<Long, String> collect = null;
        List<PmgBatPeopleType> listPeopleType = pmgBatPeopleTypeService.list();
        if (listPeopleType != null && listPeopleType.size() > 0) {
            collect = listPeopleType.stream().collect(Collectors.toMap(PmgBatPeopleType::getId, PmgBatPeopleType::getName));
        }
        if (records != null && records.size() > 0) {
            List<PmgBatParkPeopleVo> voList = new ArrayList<>(records.size());
            for (PmgBatParkPeople record : records) {
                PmgBatParkPeopleVo pmgBatParkPeopleVo = new PmgBatParkPeopleVo();
                voList.add(pmgBatParkPeopleVo);
                BeanUtil.copyProperties(record, pmgBatParkPeopleVo);
                // 设置人员类型名称
                if (collect != null && record.getPeopleType() != null) {
                    pmgBatParkPeopleVo.setPeopleTypeName(collect.get(record.getPeopleType()));
                }
            }
            pageResult.setRecords(voList);
        }
        return pageResult;
    }

    @Override
    public IPage<PmgBatParkPeopleGroupPageVo> pageByGroup(PmgBatParkPeoplePageParam pmgBatParkPeoplePageParam) {
        if (1 == pmgBatParkPeoplePageParam.getType()) {
            //查询类型 1添加人员
            return buildPeopleByInsert(pmgBatParkPeoplePageParam);
        } else {
            //查询类型 2关联人员
            return buildPeopleByJoin(pmgBatParkPeoplePageParam);
        }
    }

    private IPage<PmgBatParkPeopleGroupPageVo> buildPeopleByInsert(PmgBatParkPeoplePageParam pmgBatParkPeoplePageParam) {
        LambdaQueryWrapper<PmgBatParkPeople> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Objects.nonNull(pmgBatParkPeoplePageParam.getParkId()), PmgBatParkPeople::getParkId, pmgBatParkPeoplePageParam.getParkId());
        wrapper.eq(PmgBatParkPeople::getServiceSource, ServiceSourceEnum.OLD_ISC.getCode());
        wrapper.eq(!Func.isEmpty(pmgBatParkPeoplePageParam.getCompany()), PmgBatParkPeople::getCompany, pmgBatParkPeoplePageParam.getCompany());
        wrapper.like(!Func.isEmpty(pmgBatParkPeoplePageParam.getName()), PmgBatParkPeople::getName, pmgBatParkPeoplePageParam.getName());
        wrapper.orderByDesc(PmgBatParkPeople::getId);
        IPage<PmgBatParkPeople> page = page(Condition.getPage(pmgBatParkPeoplePageParam), wrapper);
        IPage<PmgBatParkPeopleGroupPageVo> pageResult = new Page<>();
        BeanUtil.copyProperties(page, pageResult);
        List<PmgBatParkPeople> list = page.getRecords();
        if (CollectionUtil.isEmpty(list)) {
            return pageResult;
        }

        //查询是否有关联关系存在
        List<Long> ids = list.stream().map(a -> a.getId()).collect(Collectors.toList());
        R<Set<Long>> result = hikIscPeoplePrivilegeFeignClient.groupList(pmgBatParkPeoplePageParam.getPrivilegeId(), ids);
        if (!result.isSuccess() || CollectionUtil.isEmpty(result.getData())) {
            pageResult.setRecords(com.thinkunion.park.service.common.utils.BeanUtil.copyList(list, PmgBatParkPeopleGroupPageVo.class));
            return pageResult;
        }

        List<PmgBatParkPeopleGroupPageVo> voList = new ArrayList<>();
        for (PmgBatParkPeople item : list) {
            PmgBatParkPeopleGroupPageVo vo = new PmgBatParkPeopleGroupPageVo();
            BeanUtils.copyProperties(item, vo);
            if (result.getData().contains(item.getId())) {
                vo.setPrivilegeId(pmgBatParkPeoplePageParam.getPrivilegeId());
            }
            voList.add(vo);
        }
        pageResult.setRecords(voList);
        return pageResult;
    }

    private IPage<PmgBatParkPeopleGroupPageVo> buildPeopleByJoin(PmgBatParkPeoplePageParam pmgBatParkPeoplePageParam) {
        //
        IPage<PmgBatParkPeopleGroupPageVo> iPage = new Page<>(pmgBatParkPeoplePageParam.getCurrent(), pmgBatParkPeoplePageParam.getSize());
        return baseMapper.listGroupParkPeople(iPage, pmgBatParkPeoplePageParam);
    }


    /**
     * 获取默认的组织架构信息
     *
     * @return 人员组织列表数据
     */
    @Override
    public List<Map<String, Object>> peopleOrganizeList(String regionIndexCode) {
        List<Map<String, Object>> result = new ArrayList<>();
        int pageNo = 1;
        //确保能够查询全部的组织结构(hik只提供了分页查询)
        while (true) {
            //查询hik组织架构
            Map<String, Object> orgGetMap = new HashMap<>();
            Map<String, Object> orgBody = new HashMap<>();
            orgBody.put("pageNo", pageNo);
            orgBody.put("pageSize", 1000);
            orgGetMap.put("requestApi", HikApiUtil.POST_ORG_LIST);//获取组织列表
            if (StrUtil.isNotBlank(regionIndexCode)) {
                orgGetMap.put("requestApi", HikApiUtil.POST_ORG_CHILD);//根据父组织编号获取下级组织列表
                orgBody.put("parentOrgIndexCode", regionIndexCode);
            }
            orgGetMap.put("body", orgBody);
            LOGGER.info("orgGetMap==>" + orgGetMap);
            R<Map<String, Object>> entranceRespMap = commonHikClient.commonHikMethod(orgGetMap);
            if (entranceRespMap.getData() != null && entranceRespMap.getCode() == 0) {
                // 确保调用接口返回值正确,才继续
                if (entranceRespMap.getData().get("list") == null || entranceRespMap.getData().get("total") == null) {
                    break;
                }
                List<Map<String, Object>> list = (List<Map<String, Object>>) entranceRespMap.getData().get("list");
                if (list.size() == 0) {
                    break;
                }
                result.addAll(list);
                Integer currentTotal = (Integer) entranceRespMap.getData().get("total");
                if (result.size() >= currentTotal) {
                    break;
                }
                pageNo++;//当前页加1
            } else {
                break;
            }
        }
        // 将平级的list转换才成有层级结构的list(树形结构)
        return listToTree(result, "orgIndexCode", "parentOrgIndexCode");
    }

    @Override
    @Async
    public void syncPeopleInfo(Long parkId) {
        String redisKey = CacheNames.SYNC_OLD_ISC_PEOPLE + parkId;
        // 判断redis是否存在，存在即在有效期，不用执行代码
        if (nestRedis.exists(redisKey)) {
            return;
        }
        // 根据园区ID获取园区信息
        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(parkId);
        if (Objects.isNull(parkInfo)) {
            return;
        }
        // 声明要操作的集合对象
        List<PmgBatParkPeople> updateParkPeople = new ArrayList<>();
        // 声明总的海康人员信息列表
        List<OldHikIscPersonVO> personList = new ArrayList<>();
        // 声明海康调用工具类（旧ISC）
        HikIscRequestUtil hikIscRequestUtil = new HikIscRequestUtil("192.168.10.4:10443", "25139732", "iuhpKEe0uudpk7nBNCO8");
        // 循环查询海康人员信息
        Integer pageNo = 1;
        while (true) {
            JSONObject bodyJson = new JSONObject();
            bodyJson.put("pageNo", pageNo);
            bodyJson.put("pageSize", 500);
            HikIscResponse response = hikIscRequestUtil.getDataInfo(bodyJson, "/api/resource/v2/person/personList");
            if (!response.getCode().equals("0")) {
                break;
            }
            JSONObject resultJson = JSON.parseObject(JSON.toJSONString(response.getData()));
            List<OldHikIscPersonVO> persons = JSONObject.parseArray(resultJson.getString("list"), OldHikIscPersonVO.class);
            if (persons.size() > 0) {
                personList.addAll(persons);
            } else {
                break;
            }
            pageNo++;
        }
        // 得到所有人员ID
        List<String> personIdList = personList.stream().map(OldHikIscPersonVO::getPersonId).collect(Collectors.toList());
        // 删除系统中不存在的人员信息
        LambdaQueryWrapper<PmgBatParkPeople> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PmgBatParkPeople::getParkId, parkInfo.getId());
        queryWrapper.eq(PmgBatParkPeople::getServiceSource, 2);
        queryWrapper.notIn(PmgBatParkPeople::getPersonId, personIdList);
        remove(queryWrapper);
        // 查询系统中所有的人员信息
        queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PmgBatParkPeople::getParkId, parkInfo.getId());
        queryWrapper.eq(PmgBatParkPeople::getServiceSource, 2);
        List<PmgBatParkPeople> parkPeopleList = list(queryWrapper);
        // 人员list转map
        Map<String, PmgBatParkPeople> parkPeopleMap = parkPeopleList.stream().collect(Collectors.toMap(PmgBatParkPeople::getPersonId, people -> people));
        // 循环比对
        for (OldHikIscPersonVO personVO : personList) {
            String personID = personVO.getPersonId();
            // 先声明一个空的对象
            PmgBatParkPeople hikIscPeople = new PmgBatParkPeople();
            if (personID.length() > 0 && parkPeopleMap.containsKey(personID)) {
                hikIscPeople = parkPeopleMap.get(personID);
            }
            hikIscPeople.setServiceSource(2);
            hikIscPeople.setPersonId(personVO.getPersonId());
            hikIscPeople.setName(personVO.getPersonName());
            hikIscPeople.setSex(personVO.getGender().toString());
            hikIscPeople.setPhone(personVO.getPhoneNo());
            hikIscPeople.setIdCard(personVO.getCertificateNo());
            // 扩充字段
            hikIscPeople.setTenantId(parkInfo.getTenantId());
            hikIscPeople.setParkId(parkInfo.getId());
            hikIscPeople.setCreateUser(parkInfo.getCreateUser());
            hikIscPeople.setCreateDept(parkInfo.getCreateDept());
            updateParkPeople.add(hikIscPeople);
        }
        // 更新我们数据库
        saveOrUpdateBatch(updateParkPeople);
        // 执行结束后，再redis中进行标记有效期 5分钟
        nestRedis.setEx(redisKey, parkId, 300L);
    }

    @Override
    public PmgBatParkPeople getByPhone(String phone) {
        // 查询所有该手机号的人员信息
        LambdaQueryWrapper<PmgBatParkPeople> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PmgBatParkPeople::getPhone, phone);
        queryWrapper.orderByDesc(PmgBatParkPeople::getServiceSource);
        List<PmgBatParkPeople> list = list(queryWrapper);
        if (list.size() < 1) {
            // 如果没有查到则返回一个空对象
            return null;
        } else {
            // 如果查到了，就返回第一个
            return list.get(0);
        }
    }


    /**
     * 对象List转为Tree树形结构
     *
     * @param entityList      传进来的泛型List
     * @param parentFieldName 父级字段名称
     * @return
     */
    private List<Map<String, Object>> listToTree(List<Map<String, Object>> entityList, String idFieldName, String parentFieldName) {
        //返回的map Tree树形结构
        List<Map<String, Object>> treeMap = new ArrayList<>();
        //将传进的参数entityList转为MapList
        List<Map<String, Object>> listMap = entityList;//JSON.parseObject(JSON.toJSONString(entityList), List.class);
        //声明一个map用来存listMap中的对象，key为对象id，value为对象本身
        Map<String, Map<String, Object>> entityMap = new Hashtable<>();
        //循环listMap把map对象put到entityMap中去
        listMap.forEach(map -> entityMap.put(map.get(idFieldName).toString(), map));
        //循环listMap进行Tree树形结构组装
        listMap.forEach(map -> {
            //获取map的pid
            Object pid = map.get(parentFieldName);
            if (pid == null) { //判断pid是否为空，为空说明是最顶级，直接add到返回的treeMap中去
                treeMap.add(map);
            } else { //如果pid不为空
                //根据当前map的pid获取上级 parentMap
                Map<String, Object> parentMap = entityMap.get(pid);
                if (parentMap == null) { //如果parentMap为空，则说明当前map没有父级，当前map就是顶级
                    treeMap.add(map);
                } else {    //如果parentMap不为空，则当前map为parentMap的子级
                    //取出parentMap的所有子级的List集合
                    List<Map<String, Object>> children = (List<Map<String, Object>>) parentMap.get("children");
                    if (children == null) {  //判断子级集合是否为空，为空则新创建List
                        children = new ArrayList<>();
                        parentMap.put("children", children);
                    }
                    //把当前map对象add到parentMap的子级List中去
                    children.add(map);
                }
            }
        });
        return treeMap;
    }

    public Page<PmgBatParkPeoplePolyVo> findParkPeople(PmgBatParkPeopleQryDto pmgBatParkPeopleQryDto) {
        //
        Page<PmgBatParkPeoplePolyVo> page = new Page<>(pmgBatParkPeopleQryDto.getCurrent(), pmgBatParkPeopleQryDto.getSize());
        return baseMapper.findParkPeople(page, pmgBatParkPeopleQryDto);
    }

    public Page<PmgBatParkPeople> findParkPeopleNew(PmgBatParkPeopleQryDto pmgBatParkPeopleQryDto) {
        //
        Page<PmgBatParkPeople> page = new Page<>(pmgBatParkPeopleQryDto.getCurrent(), pmgBatParkPeopleQryDto.getSize());
        return baseMapper.findParkPeopleNew(page, pmgBatParkPeopleQryDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R savePeople(PmgBatParkPeople pmgBatParkPeople) {
        // 参数检测.必填项:姓名 所属园区 照片 身份证 所属组织
        if (StrUtil.isBlank(pmgBatParkPeople.getName())) {
            return R.error("姓名不能为空");
        }
        Long parkId = pmgBatParkPeople.getParkId();
        if (parkId == null) {
            return R.error("所属园区不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getImgsrc())) {
            return R.error("人脸相片不能为空");
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getIdCard())) {
            return R.error("身份证不能为空");
        }
        */
        if (pmgBatParkPeople.getPeopleType() == null) {
            return R.error("人员类型不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getOrgIndexCode())) {
            return R.error("所属组织不能为空");
        }
        */
        PmgBatParkPeople oldPeople = null;
        if (pmgBatParkPeople.getId() != null) {
            oldPeople = this.getById(pmgBatParkPeople.getId());
        }
        // 补充人员信息
        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(parkId);
        if (parkInfo == null) {
            throw new RuntimeException("当前园区不存在");
        }
        if (pmgBatParkPeople.getCreateUser() == null) {
            pmgBatParkPeople.setCreateUser(parkInfo.getCreateUser());
        }
        if (pmgBatParkPeople.getCreateDept() == null) {
            pmgBatParkPeople.setCreateDept(parkInfo.getCreateDept());
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getTenantId()) || "000000".equals(pmgBatParkPeople.getTenantId())) {
            pmgBatParkPeople.setTenantId(parkInfo.getTenantId());
        }
        // 强制设置为新ISC
        pmgBatParkPeople.setServiceSource(1);
        PropertyCustomerArchives dto = new PropertyCustomerArchives();
        BeanUtil.copyProperties(pmgBatParkPeople, dto);
        if (Func.isNotEmpty(pmgBatParkPeople.getIsCompany())) {
            if (pmgBatParkPeople.getIsCompany() == 1) {
                dto.setCustomerType(1);
            } else {
                dto.setCustomerType(2);
            }
        } else {
            dto.setCustomerType(2);
        }
        dto.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
        dto.setCreatePeopleId(AuthUtil.getUserId());
        dto.setCustomerCategory(pmgBatParkPeople.getPeopleType().intValue());
        dto.setCustomerName(pmgBatParkPeople.getName());
        dto.setIdType(Func.isNotEmpty(pmgBatParkPeople.getIdType()) ? Integer.valueOf(pmgBatParkPeople.getIdType()) : null);
        dto.setIdNo(pmgBatParkPeople.getIdCard());
        dto.setFacePhoto(pmgBatParkPeople.getImgsrc());
        dto.setLinkPhoneOne(pmgBatParkPeople.getPhone());
        if (Func.isNotEmpty(pmgBatParkPeople.getOrgType())) {
            dto.setOrganType(pmgBatParkPeople.getOrgType().toString());
        }
        if (Func.isNotEmpty(pmgBatParkPeople.getCompanyTrade())) {
            dto.setOrganIndustry(pmgBatParkPeople.getCompanyTrade().toString());
        }
        LambdaQueryWrapper<PropertyCustomerArchives> queryCust = Wrappers.lambdaQuery();
        queryCust.eq(PropertyCustomerArchives::getIdNo, pmgBatParkPeople.getIdCard());
        queryCust.last(" limit 1");
        PropertyCustomerArchives cust = iPropertyCustomerArchivesService.getOne(queryCust, false);
        // 先保存人员信息
        if (pmgBatParkPeople.getId() == null) {
            //表明是新增人员
            //先判断,身份证号是否重复 ,重复直接变成修改
//            LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
//            query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
//            query.eq(PmgBatParkPeople::getServiceSource, 1);
//            query.last(" limit 1");
//            PmgBatParkPeople one = this.getOne(query, false);

            //if (one == null) {
            // 再保存人员信息
            if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                    PmgBatParkPeople toSave = new PmgBatParkPeople();
                    BeanUtil.copyProperties(pmgBatParkPeople, toSave);
                    BeanUtil.copyProperties(house, toSave);
                    toSave.setPeopleType(pmgBatParkPeople.getPeopleType());
                    this.save(toSave);
                }
            } else {
                this.save(pmgBatParkPeople);

            }
            if (cust == null) {
                iPropertyCustomerArchivesService.save(dto);
            } else {
                dto.setId(cust.getId());
            }

            return R.success("操作成功");
            //} else {
            //pmgBatParkPeople.setId(one.getId());
//                if (cust == null) {
//                    iPropertyCustomerArchivesService.save(dto);
//                } else {
//                    dto.setId(cust.getId());
//                }
            //}

        }
        // 修改人员isc数据(新增/修改均会进里边)
        if (pmgBatParkPeople.getId() != null) {
//            if (oldPeople != null) {
//                // 表明是修改,修改之前判断身份证是否修改,修改的话需要判断是否重复
//                if (!pmgBatParkPeople.getIdCard().equals(oldPeople.getIdCard())) {
//                    LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
//                    query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
//                    query.ne(PmgBatParkPeople::getServiceSource, 2);
//                    int count = this.count(query);
//                    if (count > 0) {
//                        return R.error("身份证号重复");
//                    }
//                }
//            }
            //
            String peopleKey = "people:save:" + pmgBatParkPeople.getIdCard();
            try {
                Boolean exists = nestRedis.exists(peopleKey);
                if (exists) {
                    return R.error("人员信息已提交,请勿频繁提交");
                }
                nestRedis.setEx(peopleKey, Thread.currentThread().getId(), 10L);
                // 人员及照片接口更新 & 人脸下发
//                return this.peopleSynchronization(pmgBatParkPeople);
                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        PmgBatParkPeople toSave = new PmgBatParkPeople();
                        BeanUtil.copyProperties(pmgBatParkPeople, toSave);
                        BeanUtil.copyProperties(house, toSave);
                        toSave.setPeopleType(pmgBatParkPeople.getPeopleType());
                        this.updateById(toSave);
                    }
                } else {
                    this.updateById(pmgBatParkPeople);

                }
                if (cust == null) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    iPropertyCustomerArchivesService.updateById(dto);
                }
                return R.success("操作成功");

            } catch (RuntimeException e) {
                String message = e.getMessage();
                // 海康错误提示转变
                if (message.contains("Field[certificateNo] Already Exists")) {
                    throw new RuntimeException("HIK,身份证号重复");
                }
                if (message.contains("Please Change Picture,Picture Min Size Is Limit 10KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                if (message.contains("Please Change Picture,Picture Max Size Is Limit 200KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                throw new RuntimeException(message);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                Long threadId = nestRedis.get(peopleKey);
                long id = Thread.currentThread().getId();
                if (threadId != null && threadId == id) {
                    nestRedis.del(peopleKey);
                }
            }
        }
        return R.error("操作失败");
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public R savePeopleNew(PmgBatParkPeople pmgBatParkPeople) {
        // 参数检测.必填项:姓名 所属园区 照片 身份证 所属组织
        if (StrUtil.isBlank(pmgBatParkPeople.getName())) {
            return R.error("姓名不能为空");
        }
        Long parkId = pmgBatParkPeople.getParkId();
        if (parkId == null) {
            return R.error("所属园区不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getImgsrc())) {
            return R.error("人脸相片不能为空");
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getIdCard())) {
            return R.error("身份证不能为空");
        }
        */
        if (pmgBatParkPeople.getPeopleType() == null) {
            return R.error("人员类型不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getOrgIndexCode())) {
            return R.error("所属组织不能为空");
        }
        */
        PmgBatParkPeople oldPeople = null;
        if (pmgBatParkPeople.getId() != null) {
            oldPeople = this.getById(pmgBatParkPeople.getId());
        }
        // 补充人员信息
        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(parkId);
        if (parkInfo == null) {
            throw new RuntimeException("当前园区不存在");
        }
        if (pmgBatParkPeople.getCreateUser() == null) {
            pmgBatParkPeople.setCreateUser(parkInfo.getCreateUser());
        }
        if (pmgBatParkPeople.getCreateDept() == null) {
            pmgBatParkPeople.setCreateDept(parkInfo.getCreateDept());
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getTenantId()) || "000000".equals(pmgBatParkPeople.getTenantId())) {
            pmgBatParkPeople.setTenantId(parkInfo.getTenantId());
        }
        // 强制设置为新ISC
        //pmgBatParkPeople.setServiceSource(1);
        PropertyCustomerArchives dto = new PropertyCustomerArchives();
        BeanUtil.copyProperties(pmgBatParkPeople, dto);
        if (Func.isNotEmpty(pmgBatParkPeople.getIsCompany())) {
            if (pmgBatParkPeople.getIsCompany() == 1) {
                dto.setCustomerType(1);
            } else {
                dto.setCustomerType(2);
            }
        } else {
            dto.setCustomerType(2);
        }
        dto.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
        dto.setCreatePeopleId(AuthUtil.getUserId());
        dto.setCustomerCategory(pmgBatParkPeople.getPeopleType().intValue());
        dto.setCustomerName(pmgBatParkPeople.getName());
        dto.setIdType(Func.isNotEmpty(pmgBatParkPeople.getIdType()) ? Integer.valueOf(pmgBatParkPeople.getIdType()) : null);
        dto.setIdNo(pmgBatParkPeople.getIdCard());
        dto.setFacePhoto(pmgBatParkPeople.getImgsrc());
        dto.setLinkPhoneOne(pmgBatParkPeople.getPhone());
        if (Func.isNotEmpty(pmgBatParkPeople.getOrgType())) {
            dto.setOrganType(pmgBatParkPeople.getOrgType().toString());
        }
        if (Func.isNotEmpty(pmgBatParkPeople.getCompanyTrade())) {
            dto.setOrganIndustry(pmgBatParkPeople.getCompanyTrade().toString());
        }
        LambdaQueryWrapper<PropertyCustomerArchives> queryCust = Wrappers.lambdaQuery();
        queryCust.eq(PropertyCustomerArchives::getIdNo, pmgBatParkPeople.getIdCard());
        queryCust.last(" limit 1");
        PropertyCustomerArchives cust = iPropertyCustomerArchivesService.getOne(queryCust, false);
        // 先保存人员信息
        if (pmgBatParkPeople.getId() == null) {
            //表明是新增人员
            //先判断,身份证号是否重复 ,重复直接变成修改
            LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
            query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
            query.eq(PmgBatParkPeople::getServiceSource, 1);
            query.last(" limit 1");
            PmgBatParkPeople one = this.getOne(query, false);

            if (one == null) {
                this.save(pmgBatParkPeople);
                LambdaQueryWrapper<PmgBatParkPeople> query2 = Wrappers.lambdaQuery();
                query2.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
                //query.eq(PmgBatParkPeople::getServiceSource, 1);
                query2.last(" limit 1");
                PmgBatParkPeople newPeople = this.getOne(query2, false);
                // 再保存人员信息
                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                if (cust == null) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    dto.setId(cust.getId());
                }

                return R.success("操作成功");
            } else {

                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(one.getId());
                        relation.setPeopleType(one.getPeopleType());
                        relation.setPeopleSubType(one.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                pmgBatParkPeople.setId(one.getId());
                if (cust == null) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    dto.setId(cust.getId());
                }
            }

        }
        // 修改人员isc数据(新增/修改均会进里边)
        if (pmgBatParkPeople.getId() != null) {
            if (oldPeople != null) {
                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                // 表明是修改,修改之前判断身份证是否修改,修改的话需要判断是否重复
                if (!pmgBatParkPeople.getIdCard().equals(oldPeople.getIdCard())) {
                    LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
                    query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
                    query.ne(PmgBatParkPeople::getServiceSource, 2);
                    int count = this.count(query);
                    if (count > 0) {
                        return R.error("身份证号重复");
                    }
                }
            }
            //
            String peopleKey = "people:save:" + pmgBatParkPeople.getIdCard();
            try {
                Boolean exists = nestRedis.exists(peopleKey);
                if (exists) {
                    return R.error("人员信息已提交,请勿频繁提交");
                }
                nestRedis.setEx(peopleKey, Thread.currentThread().getId(), 10L);
                // 人员及照片接口更新 & 人脸下发
//                return this.peopleSynchronization(pmgBatParkPeople);

                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                        PmgBatParkPeople toSave = new PmgBatParkPeople();
                        BeanUtil.copyProperties(pmgBatParkPeople, toSave);
                        BeanUtil.copyProperties(house, toSave);
                        this.updateById(toSave);
                    }
                } else {
                    this.updateById(pmgBatParkPeople);

                }
                if (cust == null && Func.isEmpty(dto.getId())) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    iPropertyCustomerArchivesService.updateById(dto);
                }
                return R.success("操作成功");

            } catch (RuntimeException e) {
                String message = e.getMessage();
                // 海康错误提示转变
                if (message.contains("Field[certificateNo] Already Exists")) {
                    throw new RuntimeException("HIK,身份证号重复");
                }
                if (message.contains("Please Change Picture,Picture Min Size Is Limit 10KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                if (message.contains("Please Change Picture,Picture Max Size Is Limit 200KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                throw new RuntimeException(message);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                Long threadId = nestRedis.get(peopleKey);
                long id = Thread.currentThread().getId();
                if (threadId != null && threadId == id) {
                    nestRedis.del(peopleKey);
                }
            }
        }
        return R.error("操作失败");
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public R savePeopleNewHouse(PmgBatParkPeople pmgBatParkPeople) {
        // 参数检测.必填项:姓名 所属园区 照片 身份证 所属组织
        if (StrUtil.isBlank(pmgBatParkPeople.getName())) {
            return R.error("姓名不能为空");
        }
        Long parkId = pmgBatParkPeople.getParkId();
        if (parkId == null) {
            return R.error("所属园区不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getImgsrc())) {
            return R.error("人脸相片不能为空");
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getIdCard())) {
            return R.error("身份证不能为空");
        }
        */
        if (pmgBatParkPeople.getPeopleType() == null) {
            return R.error("人员类型不能为空");
        }
        /*
        if (StrUtil.isBlank(pmgBatParkPeople.getOrgIndexCode())) {
            return R.error("所属组织不能为空");
        }
        */
        PmgBatParkPeople oldPeople = null;
        if (pmgBatParkPeople.getId() != null) {
            oldPeople = this.getById(pmgBatParkPeople.getId());
        }
        // 补充人员信息
        PmgBatParkInfo parkInfo = pmgBatParkInfoService.getById(parkId);
        if (parkInfo == null) {
            throw new RuntimeException("当前园区不存在");
        }
        if (pmgBatParkPeople.getCreateUser() == null) {
            pmgBatParkPeople.setCreateUser(parkInfo.getCreateUser());
        }
        if (pmgBatParkPeople.getCreateDept() == null) {
            pmgBatParkPeople.setCreateDept(parkInfo.getCreateDept());
        }
        if (StrUtil.isBlank(pmgBatParkPeople.getTenantId()) || "000000".equals(pmgBatParkPeople.getTenantId())) {
            pmgBatParkPeople.setTenantId(parkInfo.getTenantId());
        }
        // 强制设置为新ISC
        //pmgBatParkPeople.setServiceSource(1);
        PropertyCustomerArchives dto = new PropertyCustomerArchives();
        BeanUtil.copyProperties(pmgBatParkPeople, dto);
        if (Func.isNotEmpty(pmgBatParkPeople.getIsCompany())) {
            if (pmgBatParkPeople.getIsCompany() == 1) {
                dto.setCustomerType(1);
            } else {
                dto.setCustomerType(2);
            }
        } else {
            dto.setCustomerType(2);
        }
        dto.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
        dto.setCreatePeopleId(AuthUtil.getUserId());
        dto.setCustomerCategory(pmgBatParkPeople.getPeopleType().intValue());
        dto.setCustomerName(pmgBatParkPeople.getName());
        dto.setIdType(Func.isNotEmpty(pmgBatParkPeople.getIdType()) ? Integer.valueOf(pmgBatParkPeople.getIdType()) : null);
        dto.setIdNo(pmgBatParkPeople.getIdCard());
        dto.setFacePhoto(pmgBatParkPeople.getImgsrc());
        dto.setLinkPhoneOne(pmgBatParkPeople.getPhone());
        if (Func.isNotEmpty(pmgBatParkPeople.getOrgType())) {
            dto.setOrganType(pmgBatParkPeople.getOrgType().toString());
        }
        if (Func.isNotEmpty(pmgBatParkPeople.getCompanyTrade())) {
            dto.setOrganIndustry(pmgBatParkPeople.getCompanyTrade().toString());
        }
        LambdaQueryWrapper<PropertyCustomerArchives> queryCust = Wrappers.lambdaQuery();
        queryCust.eq(PropertyCustomerArchives::getIdNo, pmgBatParkPeople.getIdCard());
        queryCust.last(" limit 1");
        PropertyCustomerArchives cust = iPropertyCustomerArchivesService.getOne(queryCust, false);
        // 先保存人员信息
        if (pmgBatParkPeople.getId() == null) {
            //表明是新增人员
            //先判断,身份证号是否重复 ,重复直接变成修改
            LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
            query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
            query.eq(PmgBatParkPeople::getServiceSource, 1);
            query.last(" limit 1");
            PmgBatParkPeople one = this.getOne(query, false);

            if (one == null) {
                this.save(pmgBatParkPeople);
                LambdaQueryWrapper<PmgBatParkPeople> query2 = Wrappers.lambdaQuery();
                query2.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
                //query.eq(PmgBatParkPeople::getServiceSource, 1);
                query2.last(" limit 1");
                PmgBatParkPeople newPeople = this.getOne(query2, false);
                // 再保存人员信息
                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                if (cust == null) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    dto.setId(cust.getId());
                }

                return R.success("操作成功");
            } else {

                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(one.getId());
                        relation.setPeopleType(one.getPeopleType());
                        relation.setPeopleSubType(one.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                pmgBatParkPeople.setId(one.getId());
                if (cust == null) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    dto.setId(cust.getId());
                }
            }

        }
        // 修改人员isc数据(新增/修改均会进里边)
        if (pmgBatParkPeople.getId() != null) {
            if (oldPeople != null) {
                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        //PmgBatParkPeople toSave = new PmgBatParkPeople();
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                    }
                }
                // 表明是修改,修改之前判断身份证是否修改,修改的话需要判断是否重复
                if (!pmgBatParkPeople.getIdCard().equals(oldPeople.getIdCard())) {
                    LambdaQueryWrapper<PmgBatParkPeople> query = Wrappers.lambdaQuery();
                    query.eq(PmgBatParkPeople::getIdCard, pmgBatParkPeople.getIdCard());
                    query.ne(PmgBatParkPeople::getServiceSource, 2);
                    int count = this.count(query);
                    if (count > 0) {
                        return R.error("身份证号重复");
                    }
                }
            }
            //
            String peopleKey = "people:save:" + pmgBatParkPeople.getIdCard();
            try {
                Boolean exists = nestRedis.exists(peopleKey);
                if (exists) {
                    return R.error("人员信息已提交,请勿频繁提交");
                }
                nestRedis.setEx(peopleKey, Thread.currentThread().getId(), 10L);
                // 人员及照片接口更新 & 人脸下发
//                return this.peopleSynchronization(pmgBatParkPeople);

                if (Func.isNotEmpty(pmgBatParkPeople.getHousesList())) {
                    for (PropertyHousesDto house : pmgBatParkPeople.getHousesList()) {
                        PeoplePropertyRelation relation = new PeoplePropertyRelation();

                        BeanUtil.copyProperties(house, relation);
                        relation.setPeopleId(pmgBatParkPeople.getId());
                        relation.setPeopleType(pmgBatParkPeople.getPeopleType());
                        relation.setPeopleSubType(pmgBatParkPeople.getPeopleSubType());

                        peoplePropertyRelationService.save(relation);
                        PmgBatParkPeople toSave = new PmgBatParkPeople();
                        BeanUtil.copyProperties(pmgBatParkPeople, toSave);
                        BeanUtil.copyProperties(house, toSave);
                        this.updateById(toSave);
                    }
                } else {
                    this.updateById(pmgBatParkPeople);

                }
                if (cust == null && Func.isEmpty(dto.getId())) {
                    iPropertyCustomerArchivesService.save(dto);
                } else {
                    iPropertyCustomerArchivesService.updateById(dto);
                }
                return R.success("操作成功");

            } catch (RuntimeException e) {
                String message = e.getMessage();
                // 海康错误提示转变
                if (message.contains("Field[certificateNo] Already Exists")) {
                    throw new RuntimeException("HIK,身份证号重复");
                }
                if (message.contains("Please Change Picture,Picture Min Size Is Limit 10KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                if (message.contains("Please Change Picture,Picture Max Size Is Limit 200KB")) {
                    throw new RuntimeException("HIK,相片不能小于10K");
                }
                throw new RuntimeException(message);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                Long threadId = nestRedis.get(peopleKey);
                long id = Thread.currentThread().getId();
                if (threadId != null && threadId == id) {
                    nestRedis.del(peopleKey);
                }
            }
        }
        return R.error("操作失败");
    }

    /**
     * 进行isc人员基础信息&人脸信息的添加,并获得返回值,保存到本地库
     *
     * @param pmgBatParkPeople
     * @return
     */
    private R peopleSynchronization(PmgBatParkPeople pmgBatParkPeople) {
        PmgBatParkPeople byId = this.getById(pmgBatParkPeople.getId());
        if (byId == null) {
            return R.error("操作对象不存在");
        }
        // 人员照片接口
        boolean personIdByIdCard = this.getPersonIdByIdCard(pmgBatParkPeople);
        if (Func.isEmpty(pmgBatParkPeople.getPersonId()) && !personIdByIdCard) {
            // 新增的时候提前编译图片,
            PmgBatParkPeople finalPmgBatParkPeople1 = pmgBatParkPeople;
            CompletableFuture.supplyAsync(() -> this.getImgStr(finalPmgBatParkPeople1), taskExecutor);
            // 新增人员 faceId personId 新增
            pmgBatParkPeople = handleAddIscPeople(pmgBatParkPeople);
            // 新增的时候: 添加,人员绑定卡片 // 异步
            this.cardBinds(pmgBatParkPeople);
        } else {
            // 修改: 人员基础信息,包括分组 // 异步
            this.handleUpdateIscPeople(pmgBatParkPeople);
            // 修改: 人脸信息 faceId
            pmgBatParkPeople = handleIscPeopleFace(pmgBatParkPeople);//慢
            // 查询当前人员是否存在卡片
            boolean cardExist = this.cardExist(pmgBatParkPeople);
            if (!cardExist) {
                // 如果当前人员不存在卡片,进行 : 人员绑定卡片
                this.cardBinds(pmgBatParkPeople);
            }
        }
        // 新增/修改: indexCode //异步
        pmgBatParkPeople = handleIscFace(pmgBatParkPeople);//慢
        // 删除图片缓存
        nestRedis.del("/park/people/img/" + pmgBatParkPeople.getId());
        // 熙重设备数据下发
        //integratedClient.addPerson(pmgBatParkPeople);
        PmgBatParkPeople finalPmgBatParkPeople = pmgBatParkPeople;
        CompletableFuture.supplyAsync(() -> {
            //熙重设备数据下发
            return mqttXzClient.addPerson(finalPmgBatParkPeople);
        }, taskExecutor);

        // 更新本地(保存海康返回信息)
        this.updateById(pmgBatParkPeople);
        return R.success("操作成功");
    }

    @Resource
    private NestRedis nestRedis;

    private ReentrantLock imgLock = new ReentrantLock();

    private String getImgStr(PmgBatParkPeople parkPeople) {
        String key = "/park/people/img/" + parkPeople.getId();
        String imgStr = nestRedis.get(key);
        if (StrUtil.isBlank(imgStr)) {
            imgLock.lock();
            imgStr = nestRedis.get(key);
            if (StrUtil.isBlank(imgStr)) {
                log.info("编译图片 开始 getImgStr");
                imgStr = PicToBase64Utils.imgChangeStrLimitSize(parkPeople.getImgsrc());
                nestRedis.setEx(key, imgStr, 10L);
                log.info("编译图片 结束 getImgStr");
            }
            imgLock.unlock();
        }
        return imgStr;
    }

    private boolean getPersonIdByIdCard(PmgBatParkPeople pmgBatParkPeople) {
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 封装api
        requestMap.put("requestApi", "/api/resource/v1/person/condition/personInfo");
        // 组装人员信息
        Map<String, Object> body = new HashMap<>();
        body.put("paramName", "certificateNo");
        String[] param = {pmgBatParkPeople.getIdCard()};
        body.put("paramValue", param);
        requestMap.put("body", body);
        R<Map<String, Object>> objectR = commonHikClient.commonHikMethod(requestMap);
        if (objectR.getCode() == 0) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) objectR.getData().get("list");
            if (list != null && list.size() > 0) {
                Map<String, Object> stringObjectMap = list.get(0);
                String personId = (String) stringObjectMap.get("personId");
                List<Map<String, Object>> personPhoto = (List<Map<String, Object>>) stringObjectMap.get("personPhoto");
                if (personPhoto != null && personPhoto.size() > 0) {//添加判断,因为hik中faceId可能不存在
                    Map<String, Object> map = personPhoto.get(0);
                    String personPhotoIndexCode = (String) map.get("personPhotoIndexCode");
                    pmgBatParkPeople.setPersonId(personId);
                    pmgBatParkPeople.setFaceId(personPhotoIndexCode);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R delPeople(String ids) {
        if (StrUtil.isNotBlank(ids)) {
            List<Long> longs = Func.toLongList(ids);
            List<PmgBatParkPeople> pmgBatParkPeople = this.listByIds(longs);
            for (PmgBatParkPeople pmgBatParkPerson : pmgBatParkPeople) {
                /*
                try {
                    // 人员卡片退卡
                    Future<Boolean> cardDeletion = this.cardDeletion(pmgBatParkPerson);
                    // 人脸信息删除
                    Future<Boolean> handleIscFaceDel = this.handleIscFaceDel(pmgBatParkPerson);
                    // 人员基础信息删除
                    Future<Boolean> handleIscPeopleDel = this.handleIscPeopleDel(pmgBatParkPerson);
                    // 熙重设备数据删除
                    CompletableFuture delPerson = CompletableFuture.supplyAsync(() -> {
                        //熙重设备数据下发
                        return mqttXzClient.delPerson(pmgBatParkPerson);
                    }, taskExecutor);
                    // 阻塞
                    cardDeletion.get();
                    handleIscFaceDel.get();
                    handleIscPeopleDel.get();
                    delPerson.get();
                } catch (Exception e) {
                    // 发生异常
                    throw new RuntimeException(e.getMessage());
                }
                */
                // 删除本地库中数据
                this.removeById(pmgBatParkPerson.getId());
            }
        }
        return R.success("删除成功");
    }

    /**
     * 将人员信息同步至ISC
     *
     * @param parkPeople
     * @return
     */
    private PmgBatParkPeople handleAddIscPeople(PmgBatParkPeople parkPeople) {
        log.info("人员信息同步 开始 handleAddIscPeople");
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 封装api
        requestMap.put("requestApi", HikApiUtil.POST_PEOPLE_INFO);
        // 组装人员信息
        Map<String, Object> people = new HashMap<>();
        people.put("personName", parkPeople.getName());//名称
        if (StringUtils.isBlank(parkPeople.getSex())) {//性别
            people.put("gender", "0");
        } else {
            people.put("gender", parkPeople.getSex().equals("1") ? "1" : "2");
        }
        people.put("orgIndexCode", parkPeople.getOrgIndexCode());//人员组织
        if (Func.isNotEmpty(parkPeople.getIdCard())) {
            people.put("certificateType", "111");
            people.put("certificateNo", parkPeople.getIdCard());//身份证号
        }
        people.put("phoneNo", parkPeople.getPhone());//手机号
        if (Func.isNotEmpty(parkPeople.getImgsrc())) {
            // 图片base64编码
            List<Map<String, Object>> faces = new ArrayList<Map<String, Object>>();
            Map<String, Object> addMap = new HashMap<>(1);
            addMap.put("faceData", this.getImgStr(parkPeople));//人脸图片base64
            faces.add(addMap);
            people.put("faces", faces);//人脸图片
        }
        requestMap.put("body", people);
        LOGGER.info("handleAddIscPeople==>" + requestMap);
        R<Map<String, String>> handleAddIscPeopleResult = commonHikClient.commonHikMethod(requestMap);
        if (handleAddIscPeopleResult != null) {
            LOGGER.info("handleAddIscPeopleResult==>" + handleAddIscPeopleResult);
            if (handleAddIscPeopleResult.getCode() == 0 && handleAddIscPeopleResult.getData() != null) {
                Map<String, String> map = handleAddIscPeopleResult.getData();
                // 将人员和人脸信息保存进对象
                parkPeople.setFaceId(map.get("faceId"));
                parkPeople.setPersonId(map.get("personId"));
            }
            if (handleAddIscPeopleResult.getCode() != 0) {
                throw new RuntimeException("HIK添加人员信息失败: " + handleAddIscPeopleResult.getMessage());
            }
        }
        log.info("人员信息同步 结束 handleAddIscPeople");
        return parkPeople;
    }

    /**
     * 修改人员基本信息 同步至ISC
     *
     * @param parkPeople
     * @return
     */
    @Async(AsyncParkConfig.EXECUTOR_BEAN_NAME)
    public Future<PmgBatParkPeople> handleUpdateIscPeople(PmgBatParkPeople parkPeople) {
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 封装api
        requestMap.put("requestApi", HikApiUtil.PERSON_SINGLE_UPDATE);
        // 组装人员信息
        Map<String, Object> people = new HashMap<>();
        people.put("personId", parkPeople.getPersonId());
        people.put("personName", parkPeople.getName());
        //people.put("orgIndexCode", orgIndexCode);
        people.put("orgIndexCode", parkPeople.getOrgIndexCode());
        if (StringUtils.isBlank(parkPeople.getSex())) {
            people.put("gender", "0");
        } else {
            people.put("gender", parkPeople.getSex().equals("1") ? "1" : "2");
        }
        if (Func.isNotEmpty(parkPeople.getIdCard())) {
            people.put("certificateType", "111");
            people.put("certificateNo", parkPeople.getIdCard());
        }
        people.put("phoneNo", parkPeople.getPhone());
        requestMap.put("body", people);
        LOGGER.info("handleUpdateIscPeople==>" + requestMap);
        R<Map<String, String>> handleUpdateIscPeopleResult = commonHikClient.commonHikMethod(requestMap);
        LOGGER.info("handleUpdateIscPeopleResult==>" + handleUpdateIscPeopleResult);
        if (handleUpdateIscPeopleResult.getCode() != 0) {
            throw new RuntimeException("HIK修改人员基本信息失败: " + handleUpdateIscPeopleResult.getMessage());
        }
        return new AsyncResult<>(parkPeople);
    }

    /**
     * 处理ISC人脸信息: faceId 修改
     *
     * @param parkPeople 人员信息
     * @return
     */
    private PmgBatParkPeople handleIscPeopleFace(PmgBatParkPeople parkPeople) {
        if (Func.isEmpty(parkPeople.getImgsrc())) {
            return parkPeople;
        }
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 组装人脸信息
        Map<String, Object> face = new HashMap<>();
        if (Func.isNotEmpty(parkPeople.getFaceId())) {
            ////查询人脸图片uri是否改变
            PmgBatParkPeople byId = this.getById(parkPeople.getId());
            if (byId != null && byId.getImgsrc().equals(parkPeople.getImgsrc())) {
                return parkPeople;
            }
            face.put("faceData", this.getImgStr(parkPeople));
            face.put("faceId", parkPeople.getFaceId());
            // 根据人脸Id修改人脸
            requestMap.put("requestApi", HikApiUtil.FACE_SINGLE_UPDATE);
        } else {
            // 添加人脸信息
            face.put("faceData", this.getImgStr(parkPeople));
            face.put("personId", parkPeople.getPersonId());
            requestMap.put("requestApi", HikApiUtil.FACE_SINGLE_ADD);
        }
        requestMap.put("body", face);
        LOGGER.info("handleIscFace==>" + requestMap);
        R<Map<String, String>> handleIscFaceResult = commonHikClient.commonHikMethod(requestMap);
        LOGGER.info("handleIscFaceResult==>" + handleIscFaceResult);
        if (handleIscFaceResult.getCode() == 0 && handleIscFaceResult.getData() != null) {
            Map<String, String> map = handleIscFaceResult.getData();
            // 将人员和人脸信息保存进对象
            parkPeople.setFaceId(map.get("faceId"));
        }
        if (handleIscFaceResult.getCode() != 0) {
            throw new RuntimeException("HIK修改人脸失败: " + handleIscFaceResult.getMessage());
        }
        return parkPeople;
    }

    /**
     * 处理ISC人员删除
     *
     * @param parkPeople 人员信息
     * @return
     */
    @Async(AsyncParkConfig.EXECUTOR_BEAN_NAME)
    public Future<Boolean> handleIscPeopleDel(PmgBatParkPeople parkPeople) throws RuntimeException {
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>();
        // 请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestMap.put("requestApi", HikApiUtil.PERSON_BATCH_DELETE);
        String[] personIds = {parkPeople.getPersonId()};
        requestBody.put("personIds", personIds);
        requestMap.put("body", requestBody);
        R<Object> objectR = commonHikClient.commonHikMethod(requestMap);
        if (objectR.getCode() != 0) {
            throw new RuntimeException("HIK人员基本信息删除失败: " + objectR.getMessage());
        }
        return new AsyncResult<>(true);
    }

    /**
     * 处理ISC人脸删除
     *
     * @param parkPeople 人员信息
     * @return
     */
    @Async(AsyncParkConfig.EXECUTOR_BEAN_NAME)
    public Future<Boolean> handleIscFaceDel(PmgBatParkPeople parkPeople) throws RuntimeException {
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>();
        // 请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestMap.put("requestApi", HikApiUtil.DEL_FACE);
        requestBody.put("indexCodes", new String[]{parkPeople.getIndexCode()});
        PmgBatPeopleType peopleType = peopleTypeService.getById(parkPeople.getPeopleType());
        requestBody.put("faceGroupIndexCode", peopleType.getCode());
        requestMap.put("body", requestBody);
        R<Object> objectR = commonHikClient.commonHikMethod(requestMap);
        if (objectR.getCode() != 0) {
            throw new RuntimeException("HIK人员人脸信息删除失败: " + objectR.getMessage());
        }
        return new AsyncResult<>(true);
    }


    /**
     * 单个添加人脸
     * 处理ISC人脸信息管理-添加人脸到人脸分组或者修改 indexCode 修改
     *
     * @param parkPeople 人员信息
     * @return
     */
    private PmgBatParkPeople handleIscFace(PmgBatParkPeople parkPeople) {
        log.info("人脸信息同步 开始 handleIscFace");
        // 组装调用数据
        Map<String, Object> requestMap = new HashMap<>(2);
        // 请求参数
        Map<String, Object> requestBody = new HashMap<>();
        if (Func.isEmpty(parkPeople.getIndexCode())) {
            // 如果人脸标识为空，就新增
            requestMap.put("requestApi", HikApiUtil.ADD_FACE);
            // 根据类型查询人脸分组信息
            PmgBatPeopleType peopleType = peopleTypeService.getById(parkPeople.getPeopleType());
            if (peopleType == null) {
                throw new RuntimeException("人员类型不存在");
            }
            requestBody.put("faceGroupIndexCode", peopleType.getCode());
            Map<String, Object> faceInfoBody = new HashMap<>();
            faceInfoBody.put("name", parkPeople.getName());
            if (StringUtils.isBlank(parkPeople.getSex())) {
                faceInfoBody.put("sex", "UNKNOWN");
            } else {
                faceInfoBody.put("sex", parkPeople.getSex().equals("1") ? "1" : "2");
            }
            if (Func.isNotEmpty(parkPeople.getIdCard())) {
                faceInfoBody.put("certificateType", "111");
                faceInfoBody.put("certificateNum", parkPeople.getIdCard());
            }
            Map<String, Object> facePicBody = new HashMap<>();
            facePicBody.put("faceBinaryData", this.getImgStr(parkPeople));
            requestBody.put("faceInfo", faceInfoBody);
            requestBody.put("facePic", facePicBody);
            requestMap.put("body", requestBody);
            R<Map<String, Object>> result = commonHikClient.commonHikMethod(requestMap);
            if (result.getCode() == 0 && result.getData() != null) {
                Map<String, Object> map = result.getData();
                // 将人脸的唯一标识保存进对象
                parkPeople.setIndexCode(map.get("indexCode").toString());
            }
            if (result.getCode() != 0) {
                throw new RuntimeException("HIK单个添加人脸失败: " + result.getMessage());
            }
        } else {
            // 如果人脸标识不为空，则修改
            requestMap.put("requestApi", HikApiUtil.UPDATE_FACE);
            requestBody.put("indexCode", parkPeople.getIndexCode());
            Map<String, Object> faceInfobody = new HashMap<>();
            faceInfobody.put("name", parkPeople.getName());
            if (StringUtils.isBlank(parkPeople.getSex())) {
                faceInfobody.put("sex", "UNKNOWN");
            } else {
                faceInfobody.put("sex", parkPeople.getSex().equals("1") ? "1" : "2");
            }
            if (Func.isNotEmpty(parkPeople.getIdCard())) {
                faceInfobody.put("certificateType", "111");
                faceInfobody.put("certificateNum", parkPeople.getIdCard());
            }
            requestBody.put("faceInfo", faceInfobody);

            Map<String, Object> facePicBody = new HashMap<>();
            facePicBody.put("faceBinaryData", this.getImgStr(parkPeople));
            requestBody.put("facePic", facePicBody);

            requestMap.put("body", requestBody);
            commonHikClient.commonHikMethod(requestMap);

        }
        log.info("人脸信息同步 结束 handleIscFace");
        return parkPeople;
    }


    /**
     * 查询是否存在指定卡片
     *
     * @param parkPeople
     * @return
     */
    private boolean cardExist(PmgBatParkPeople parkPeople) {
        Map<String, Object> requestMap = new HashMap<>(2);
        Map<String, Object> requestBody = new HashMap<>();
        requestMap.put("requestApi", HikApiUtil.CARD_INFO);
        // 卡号
        requestBody.put("cardNo", parkPeople.getIdCard());
        requestMap.put("body", requestBody);
        R<Map<String, Object>> objectR = commonHikClient.commonHikMethod(requestMap);
        if (objectR.getCode() == 0 && !objectR.getData().isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 为人员绑定卡片
     *
     * @return
     */
    @Async(AsyncParkConfig.EXECUTOR_BEAN_NAME)
    public Future<Boolean> cardBinds(PmgBatParkPeople parkPeople) {
        Map<String, Object> requestMap = new HashMap<>(2);
        Map<String, Object> requestBody = new HashMap<>();
        requestMap.put("requestApi", HikApiUtil.CARD_BINDS);
        List<Map<String, Object>> cardList = new ArrayList<>();
        Map<String, Object> peopleMap = new HashMap<>();
        // 卡号
        peopleMap.put("cardNo", parkPeople.getIdCard());
        // 人员唯一标示
        peopleMap.put("personId", parkPeople.getPersonId());
        // 人员所属组织
        peopleMap.put("orgIndexCode", parkPeople.getOrgIndexCode());
        cardList.add(peopleMap);
        requestBody.put("cardList", cardList);
        requestMap.put("body", requestBody);
        R<Map<String, Object>> objectR = commonHikClient.commonHikMethod(requestMap);
        if (objectR.getCode() != 0) {
            throw new RuntimeException("HIK,绑定卡片失败: " + objectR.getMessage());
        }
        return new AsyncResult<>(true);
    }

    /**
     * 为人员退卡
     *
     * @param parkPeople 人员
     * @return
     */

    @Async(AsyncParkConfig.EXECUTOR_BEAN_NAME)
    public Future<Boolean> cardDeletion(PmgBatParkPeople parkPeople) {
        Map<String, Object> requestMap = new HashMap<>(2);
        Map<String, Object> requestBody = new HashMap<>();
        requestMap.put("requestApi", HikApiUtil.CARD_DELETION);
        requestBody.put("cardNumber", parkPeople.getIdCard());
        requestBody.put("personId", parkPeople.getPersonId());
        requestMap.put("body", requestBody);
        R<Map<String, Object>> objectR = commonHikClient.commonHikMethod(requestMap);
        return new AsyncResult<>(true);
    }

    public boolean updatePeople(PmgBatParkPeople pmgBatParkPeople) {
        //this.verifySaveFeeMode(pmgBatParkPeople);
        this.assembleSaveDto(pmgBatParkPeople);
        return this.saveOrUpdate(pmgBatParkPeople);

    }


    private void assembleSaveDto(PmgBatParkPeople pmgBatParkPeople) {
        if (Func.isEmpty(pmgBatParkPeople.getId())) {
            pmgBatParkPeople.setCreateTime(new Date());
        }
    }

    public Page<PmgBatParkPeople> selectPage(PmgBatParkPeopleQryDto qryDto) {
        Page<PmgBatParkPeople> page = new Page<>(qryDto.getCurrent(), qryDto.getSize());
        LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
//        if (!AuthUtil.isAdministrator()) {
//            qw.eq(PmgBatParkPeople::getCustomerManageId, AuthUtil.getUser().getCustomerManageId());
//        } else {
//            // 超管
//            qw.eq(Func.isNotEmpty(qryDto.getCustomerManageId()), PmgBatParkPeople::getCustomerManageId, qryDto.getCustomerManageId());
//        }
        qw.eq(Func.isNotEmpty(qryDto.getSex()), PmgBatParkPeople::getSex, qryDto.getSex());
        qw.eq(Func.isNotEmpty(qryDto.getBuildingId()), PmgBatParkPeople::getBuildingId, qryDto.getBuildingId());
        qw.eq(Func.isNotEmpty(qryDto.getBuildingUnitId()), PmgBatParkPeople::getBuildingUnitId, qryDto.getBuildingUnitId());
        qw.like(Func.isNotEmpty(qryDto.getIdCard()), PmgBatParkPeople::getIdCard, qryDto.getIdCard());
        qw.eq(Func.isNotEmpty(qryDto.getFloorId()), PmgBatParkPeople::getFloorId, qryDto.getFloorId());
        qw.eq(Func.isNotEmpty(qryDto.getRoomId()), PmgBatParkPeople::getRoomId, qryDto.getRoomId());
        qw.like(Func.isNotEmpty(qryDto.getPhone()), PmgBatParkPeople::getPhone, qryDto.getPhone());
        qw.like(Func.isNotEmpty(qryDto.getName()), PmgBatParkPeople::getName, qryDto.getName());
        qw.eq(Func.isNotEmpty(qryDto.getParkId()), PmgBatParkPeople::getParkId, qryDto.getParkId());
        qw.eq(Func.isNotEmpty(qryDto.getPeopleType()), PmgBatParkPeople::getPeopleType, qryDto.getPeopleType());
        qw.eq(Func.isNotEmpty(qryDto.getIsBuildingManager()), PmgBatParkPeople::getIsBuildingManager, qryDto.getIsBuildingManager());
        qw.eq(Func.isNotEmpty(qryDto.getIsBuildingEngineer()), PmgBatParkPeople::getIsBuildingEngineer, qryDto.getIsBuildingEngineer());
        qw.eq(Func.isNotEmpty(qryDto.getBindStatus()), PmgBatParkPeople::getBindStatus, qryDto.getBindStatus());
        qw.eq(Func.isNotEmpty(qryDto.getBindAccount()), PmgBatParkPeople::getBindAccount, qryDto.getBindAccount());
        qw.eq(Func.isNotEmpty(qryDto.getIdType()), PmgBatParkPeople::getIdType, qryDto.getIdType());

        qw.orderByDesc(PmgBatParkPeople::getCreateTime);
        return this.page(page, qw);
    }

    @Override
    public void exportExcel(PmgBatParkPeopleQryDto qryDto, HttpServletResponse response) {
        qryDto.setCurrent(-1);
        qryDto.setSize(-1);
        List<PmgBatParkPeople> list = this.selectPage(qryDto).getRecords();
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm");
        List<PmgBatParkPeopleExcelVo> excelVoList = cn.hutool.core.bean.BeanUtil.copyToList(list, PmgBatParkPeopleExcelVo.class);
        ExcelUtil.export(response, "人员信息" + dateStr, "人员信息", excelVoList, PmgBatParkPeopleExcelVo.class);

    }

    @Override
    public NetImportResVo importExcel(MultipartFile file) {
        if (!(file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls"))) {
            throw new ServiceException("请选择正确的excel文件");
        }
        NetImportResVo vo = new NetImportResVo();
        vo.setImportSize(0);
        vo.setFailSize(0);
        vo.setSuccessSize(0);
        List<String> msg = new ArrayList<>();
        vo.setMsg(msg);
        try {
            EasyExcel.read(file.getInputStream(), PmgBatParkPeopleExcelVo.class, new ReadListener() {

                @Override
                public void onException(Exception exception, AnalysisContext context) throws Exception {
                    log.error("导出异常", exception);
                    log.info("context", context);
                    vo.setFailSize(vo.getFailSize() + 1);
                    Integer rowIndex = context.readRowHolder().getRowIndex() - 1;
                    vo.getMsg().add(String.format("第%s条导入失败,失败原因:%s;", rowIndex, exception.getMessage()));
                }

                @Override
                public void invokeHead(Map headMap, AnalysisContext context) {
                    log.info("context", context);
                    log.info("headMap", headMap);
                }

                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {
                    vo.setImportSize(vo.getImportSize() + 1);
                    PmgBatParkPeopleExcelVo importVo = (PmgBatParkPeopleExcelVo) o;
                    saveImport(importVo);
                }

                @Override
                public void extra(CellExtra extra, AnalysisContext context) {
                    log.info("extra", context);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    log.info("analysisContext", analysisContext);
                }

                @Override
                public boolean hasNext(AnalysisContext context) {
                    return true;
                }
            }).sheet().doRead();
        } catch (IOException e) {
            log.info("导入异常", e);
        }

        return vo;
    }

    public void saveImport(PmgBatParkPeopleExcelVo importVo) {
        PmgBatParkPeople pmgBatParkPeople = new PmgBatParkPeople();
        BeanUtils.copyProperties(importVo, pmgBatParkPeople);
        this.saveOrUpdate(pmgBatParkPeople);
    }

    /**
     * @param pmgBatParkPeopleQryDto
     * @description: 房产认证
     * @return: boolean
     * @author: 洪铭铭
     * @time: 2024/5/24 16:09
     */
    @Override
    public R propertyAuth(PmgBatParkPeopleQryDto pmgBatParkPeopleQryDto) {
        ResponseDataTypeDto responseDataTypeDto = new ResponseDataTypeDto();

        LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getRoomId()), PmgBatParkPeople::getRoomId, pmgBatParkPeopleQryDto.getRoomId());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getPeopleType()), PmgBatParkPeople::getPeopleType, pmgBatParkPeopleQryDto.getPeopleType());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getName()), PmgBatParkPeople::getName, pmgBatParkPeopleQryDto.getName());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getPhone()), PmgBatParkPeople::getPhone, pmgBatParkPeopleQryDto.getPhone());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getIdCard()), PmgBatParkPeople::getIdCard, pmgBatParkPeopleQryDto.getIdCard());
        List<PmgBatParkPeople> list = this.list(qw);

        if (Func.isNotEmpty(list) && list.size() > 0) {
            //姓名 电话 身份照证 有存在
            PmgBatParkPeople pmgBatParkPeople = list.get(0);
            if (Func.isNotEmpty(pmgBatParkPeople.getPeopleType()) && pmgBatParkPeople.getPeopleType().intValue() == ApproveConfigGroupEnum.OWNER_APPROVE.getValue()) {
                //业主审核
                SaasGenericConfig config = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.OWNER_APPROVE.getDesc());
                if (StringUtil.equals(config.getConfigGroupValue(), "2")) {
                    //需要物业审核
                    PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApprove.class);
                    app.setContactPhone(pmgBatParkPeople.getPhone());
                    app.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                    app.setApplyTime(new Date());
                    app.setApplyStatus("1");
                    app.setParkName(pmgBatParkPeople.getParkName());
                    app.setBuildingName(pmgBatParkPeople.getBuildingName());
                    app.setBuildingUnitName(pmgBatParkPeople.getBuildingUnitName());
                    app.setRoomName(pmgBatParkPeople.getRoomName());
                    PeopleApproveQueryDto exist = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApproveQueryDto.class);
                    exist.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                    Page<PeopleApprove> res = peopleApproveService.getExistApproveList(exist);
                    if (Func.isNotEmpty(res.getRecords())) {
                        PeopleApprove record = res.getRecords().get(0);
                        if (record.getApplyStatus().equals("4")) {
                            //驳回后,重复提交的改回待审核
                            record.setApplyStatus("1");
                            peopleApproveService.saveOrUpdate(record);
                            //return R.success("业主信息已提交，请等待审核");
                            responseDataTypeDto.setValue(1);
                            return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                        }
                        responseDataTypeDto.setValue(2);
                        //return R.fail("业主信息已提交，请勿重复提交");
                        return R.data("200", responseDataTypeDto, "业主信息已提交，请勿重复提交");
                    }

                    peopleApproveService.savePeopleApprove(app);
                    //return R.success("业主信息已提交，请等待审核");
                    responseDataTypeDto.setValue(1);
                    return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                } else {
                    //不需要物业审核
                    pmgBatParkPeople.setBindStatus(1);
                    pmgBatParkPeople.setBindAccount(pmgBatParkPeopleQryDto.getPhone());
                    this.saveOrUpdate(pmgBatParkPeople);
                    //return R.success("认证成功");
                    responseDataTypeDto.setValue(0);
                    return R.data("200", responseDataTypeDto, "认证成功");
                }

            } //else if (Func.isNotEmpty(pmgBatParkPeople.getPeopleType()) && pmgBatParkPeople.getPeopleType().intValue() == ApproveConfigGroupEnum.RESIDENT_APPROVE.getValue()) {
            else {
                //非业主审核的其他peopleType走这边
                //住户审核
                SaasGenericConfig config = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.RESIDENT_APPROVE.getDesc());
                if (StringUtil.equals(config.getConfigGroupValue(), "2")) {
                    //需要物业审核
                    PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApprove.class);
                    app.setContactPhone(pmgBatParkPeople.getPhone());
                    app.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                    app.setApplyTime(new Date());
                    app.setApplyStatus("1");
                    app.setParkName(pmgBatParkPeople.getParkName());
                    app.setBuildingName(pmgBatParkPeople.getBuildingName());
                    app.setBuildingUnitName(pmgBatParkPeople.getBuildingUnitName());
                    app.setRoomName(pmgBatParkPeople.getRoomName());
                    PeopleApproveQueryDto exist = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApproveQueryDto.class);
                    exist.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                    Page<PeopleApprove> res = peopleApproveService.getPeopleApproveList(exist);
                    if (Func.isNotEmpty(res.getRecords())) {
                        PeopleApprove record = res.getRecords().get(0);
                        if (record.getApplyStatus().equals("4")) {
                            record.setApplyStatus("1");
                            peopleApproveService.saveOrUpdate(record);
                            //return R.success("住户信息已提交，请等待审核");
                            responseDataTypeDto.setValue(1);
                            return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                        }
                        //return R.fail("住户信息已提交，请勿重复提交");
                        responseDataTypeDto.setValue(2);
                        return R.data("200", responseDataTypeDto, "业主信息已提交，请勿重复提交");
                    }
                    peopleApproveService.savePeopleApprove(app);
                    //return R.success("住户信息已提交，请等待审核");
                    responseDataTypeDto.setValue(1);
                    return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                } else {
                    //不需要住户审核
                    pmgBatParkPeople.setBindStatus(1);
                    pmgBatParkPeople.setBindAccount(pmgBatParkPeopleQryDto.getPhone());
                    this.saveOrUpdate(pmgBatParkPeople);
                    //return R.success("认证成功");
                    responseDataTypeDto.setValue(0);
                    return R.data("200", responseDataTypeDto, "认证成功");
                }
            }
        } else {

            // 姓名 电话 身份照证 不存在
            if (Func.isNotEmpty(pmgBatParkPeopleQryDto.getPeopleType()) && pmgBatParkPeopleQryDto.getPeopleType().intValue() == ApproveConfigGroupEnum.OWNER_APPROVE.getValue()) {
                //业主审核
                SaasGenericConfig config = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.OWNER_APPROVE.getDesc());
                if (StringUtil.equals(config.getConfigGroupValue(), "2")) {
                    //需要业主审核
                    PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApprove.class);
                    app.setContactPhone(pmgBatParkPeopleQryDto.getPhone());
                    app.setApproveType(pmgBatParkPeopleQryDto.getPeopleType().intValue());
                    app.setApplyTime(new Date());
                    app.setApplyStatus("1");
                    app.setParkName(pmgBatParkPeopleQryDto.getParkName());
                    app.setBuildingName(pmgBatParkPeopleQryDto.getBuildingName());
                    app.setBuildingUnitName(pmgBatParkPeopleQryDto.getBuildingUnitName());
                    app.setRoomName(pmgBatParkPeopleQryDto.getRoomName());
                    PeopleApproveQueryDto exist = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApproveQueryDto.class);
                    exist.setApproveType(pmgBatParkPeopleQryDto.getPeopleType().intValue());
                    Page<PeopleApprove> res = peopleApproveService.getExistApproveList(exist);
                    if (Func.isNotEmpty(res.getRecords())) {
                        PeopleApprove record = res.getRecords().get(0);
                        if (record.getApplyStatus().equals("4")) {
                            record.setApplyStatus("1");
                            peopleApproveService.saveOrUpdate(record);
                            //return R.success("业主信息已提交，请等待审核");
                            responseDataTypeDto.setValue(1);
                            return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                        }
                        responseDataTypeDto.setValue(2);
                        //return R.fail("业主信息已提交，请勿重复提交");
                        return R.data("200", responseDataTypeDto, "业主信息已提交，请勿重复提交");
                    }

                    peopleApproveService.savePeopleApprove(app);
                    //return R.success("业主信息已提交，请等待审核");
                    responseDataTypeDto.setValue(1);
                    return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                }
//                else {
//                    pmgBatParkPeopleQryDto.setBindStatus(1);
//                    pmgBatParkPeopleQryDto.setBindAccount(pmgBatParkPeopleQryDto.getPhone());
//                    PmgBatParkPeople people = new PmgBatParkPeople();
//                    BeanUtil.copyProperties(pmgBatParkPeopleQryDto, people);
//                    this.saveOrUpdate(people);
//                    //return R.success("认证成功");
//                    responseDataTypeDto.setValue(0);
//                    return R.data("200", responseDataTypeDto, "认证成功");
//                }
            } else {
                //非业主审核的其他peopleType走这边
                //if (Func.isNotEmpty(pmgBatParkPeopleQryDto.getPeopleType()) && pmgBatParkPeopleQryDto.getPeopleType().intValue() == ApproveConfigGroupEnum.RESIDENT_APPROVE.getValue()) {
                SaasGenericConfig config2 = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.RESIDENT_APPROVE.getDesc());
                if (StringUtil.equals(config2.getConfigGroupValue(), "2")) {
                    //需要业主审核
                    PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApprove.class);
                    app.setContactPhone(pmgBatParkPeopleQryDto.getPhone());
                    app.setApproveType(pmgBatParkPeopleQryDto.getPeopleType().intValue());
                    app.setApplyTime(new Date());
                    app.setApplyStatus("1");
                    app.setParkName(pmgBatParkPeopleQryDto.getParkName());
                    app.setBuildingName(pmgBatParkPeopleQryDto.getBuildingName());
                    app.setBuildingUnitName(pmgBatParkPeopleQryDto.getBuildingUnitName());
                    app.setRoomName(pmgBatParkPeopleQryDto.getRoomName());
                    PeopleApproveQueryDto exist = BeanUtil.copyProperties(pmgBatParkPeopleQryDto, PeopleApproveQueryDto.class);
                    exist.setApproveType(pmgBatParkPeopleQryDto.getPeopleType().intValue());
                    Page<PeopleApprove> res = peopleApproveService.getPeopleApproveList(exist);
                    if (Func.isNotEmpty(res.getRecords())) {
                        PeopleApprove record = res.getRecords().get(0);
                        if (record.getApplyStatus().equals("4")) {
                            record.setApplyStatus("1");
                            peopleApproveService.saveOrUpdate(record);
                            responseDataTypeDto.setValue(1);
                            return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                            //return R.success("住户信息已提交，请等待审核");
                        }
                        //return R.fail("住户信息已提交，请勿重复提交");
                        responseDataTypeDto.setValue(2);
                        return R.data("200", responseDataTypeDto, "业主信息已提交，请勿重复提交");
                    }
                    peopleApproveService.savePeopleApprove(app);
                    //return R.success("住户信息已提交，请等待审核");
                    responseDataTypeDto.setValue(1);
                    return R.data("200", responseDataTypeDto, "业主信息已提交，请等待审核");
                } else {
//                    pmgBatParkPeople.setBindStatus(1);
//                    pmgBatParkPeople.setBindAccount(pmgBatParkPeopleQryDto.getPhone());
//                    this.saveOrUpdate(pmgBatParkPeople);
//                    return R.success("认证成功");
                }
            }

            //responseDataTypeDto.setValue(3);
            //return R.data("200", responseDataTypeDto, "未查到人员信息，请移步至服务中心更新业主信息");
            //return R.fail("未查到人员信息，请移步至服务中心更新业主信息");
        }
        return R.fail("未查到人员信息，请移步至服务中心更新业主信息");
    }

    /**
     * @param pmgBatParkPeopleQryDto
     * @description:
     * @return: boolean
     * @author: 洪铭铭
     * @time: 2024/5/29 15:11
     */
    @Override
    public boolean ownerConfirm(String ownerPhone, PmgBatParkPeopleQryDto pmgBatParkPeopleQryDto) {

        //SmsTool.sendOwnerConfirmMsg(ownerPhone, pmgBatParkPeopleQryDto);
        PmgBatMessageDto messageDto = new PmgBatMessageDto();
        messageDto.setMessageType(7);
        messageDto.setMessageTitle("业主确认通知");
        StringBuilder sb = new StringBuilder("http://192.168.0.191/pmsTest/property/pages/myHouse/identityAuthHousing/index");
        sb.append("?parkId=" + pmgBatParkPeopleQryDto.getParkId());
        sb.append("&parkName=" + pmgBatParkPeopleQryDto.getParkName());
        sb.append("&buildingId=" + pmgBatParkPeopleQryDto.getBuildingId());
        sb.append("&buildingName=" + pmgBatParkPeopleQryDto.getBuildingId());
        if (Func.isNotEmpty(pmgBatParkPeopleQryDto.getBuildingUnitId())) {
            sb.append("&buildingUnitId=" + pmgBatParkPeopleQryDto.getBuildingUnitId());
        }
        if (Func.isNotEmpty(pmgBatParkPeopleQryDto.getBuildingUnitId())) {
            sb.append("&buildingUnitName=" + pmgBatParkPeopleQryDto.getBuildingUnitName());
        }
        sb.append("&roomId=" + pmgBatParkPeopleQryDto.getRoomId());
        sb.append("&roomName=" + pmgBatParkPeopleQryDto.getRoomName());
        sb.append("&peopleType=" + pmgBatParkPeopleQryDto.getPeopleType());
        sb.append("&name=" + pmgBatParkPeopleQryDto.getName());
        sb.append("&idCard=" + pmgBatParkPeopleQryDto.getIdCard());
        sb.append("&phone=" + pmgBatParkPeopleQryDto.getPhone());
        sb.append("&submitTime=" + pmgBatParkPeopleQryDto.getSubmitTime());
        String content = String.format("<p>【保利智慧平台】%s(%s)正在认证「%s」%s%s%s房源的租客身份，需要业主(%s)确认。请点击<a href=\"%s\">立即处理</a>，进行通过/驳回处理。</p>", pmgBatParkPeopleQryDto.getName(), pmgBatParkPeopleQryDto.getPhone(), pmgBatParkPeopleQryDto.getParkName(), pmgBatParkPeopleQryDto.getBuildingName(), pmgBatParkPeopleQryDto.getBuildingUnitName(), pmgBatParkPeopleQryDto.getRoomName(), ownerPhone, sb);
        String escaped = StringEscapeUtils.escapeHtml4(content);
        //content = content.replaceAll("\"", "&quot;");

        messageDto.setMessageContent(escaped);
        messageDto.setMessageTime(new Date());
        User owner = iUserClient.getUserInfoByPhone(ownerPhone).getData();
        messageDto.setUserDetailId(owner.getId());
        messageFeignServer.saveMessage(messageDto);
        /*
        LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getRoomId()), PmgBatParkPeople::getRoomId, pmgBatParkPeopleQryDto.getRoomId());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getPeopleType()), PmgBatParkPeople::getPeopleType, pmgBatParkPeopleQryDto.getPeopleType());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getName()), PmgBatParkPeople::getName, pmgBatParkPeopleQryDto.getName());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getPhone()), PmgBatParkPeople::getPhone, pmgBatParkPeopleQryDto.getPhone());
        qw.eq(Func.isNotEmpty(pmgBatParkPeopleQryDto.getIdCard()), PmgBatParkPeople::getIdCard, pmgBatParkPeopleQryDto.getIdCard());
        List<PmgBatParkPeople> list = this.list(qw);
        if (Func.isNotEmpty(list)) {
            PmgBatParkPeople ppl = list.get(0);
            ppl.setBindStatus(1);
            this.saveOrUpdate(ppl);
            return true;
        } else {
            return false;
        }

         */
        return true;
    }

    /**
     * @param pmgBatParkPeople
     * @description: 添加住户
     * @return: org.nest.springwrap.core.tool.api.R
     * @author: 洪铭铭
     * @time: 2024/6/11 16:04
     */
    @Override
    public R saveTenant(PmgBatParkPeople pmgBatParkPeople) {
        SaasGenericConfig config = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.RESIDENT_APPROVE.getDesc());
        SaasGenericConfig ownerConfig = saasGenericConfigService.getConfigValue(ApproveConfigGroupEnum.OWNER_APPROVE.getDesc());
        if (pmgBatParkPeople.getPeopleType() == 2 || pmgBatParkPeople.getPeopleType() == 3) {
            if (StringUtil.equals(config.getConfigGroupValue(), "2")) {

                PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeople, PeopleApprove.class);
                app.setApplyStatus("1");
                app.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                app.setApplyTime(new Date());
                app.setTenantType(pmgBatParkPeople.getPeopleSubType());

                peopleApproveService.savePeopleApprove(app);
                return R.success("已提交住户信息，请耐心等待物业审核");
            } else {
                pmgBatParkPeople.setBindStatus(1);
                this.saveOrUpdate(pmgBatParkPeople);
                return R.success("添加成功");
            }
        } else {
            if (StringUtil.equals(ownerConfig.getConfigGroupValue(), "2")) {

                PeopleApprove app = BeanUtil.copyProperties(pmgBatParkPeople, PeopleApprove.class);
                app.setApplyStatus("1");
                app.setApproveType(pmgBatParkPeople.getPeopleType().intValue());
                app.setApplyTime(new Date());
                //app.setTenantType(pmgBatParkPeople.getPeopleSubType());

                peopleApproveService.savePeopleApprove(app);
                return R.success("已提交业主信息，请耐心等待物业审核");
            } else {
                pmgBatParkPeople.setBindStatus(1);
                this.saveOrUpdate(pmgBatParkPeople);
                return R.success("添加成功");
            }
        }
    }

    /**
     * @param pmgBatParkPeople
     * @description:
     * @return: java.util.List<com.yuchen.saas.park.api.entity.park.PmgBatParkPeople>
     * @author: 洪铭铭
     * @time: 2024/6/24 11:45
     */
    @Override
    public List<PmgBatParkPeople> getBindedPeople(PmgBatParkPeople pmgBatParkPeople) {
        LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
        qw.eq(Func.isNotEmpty(pmgBatParkPeople.getPeopleType()), PmgBatParkPeople::getPeopleType, pmgBatParkPeople.getPeopleType());
        qw.eq(Func.isNotEmpty(pmgBatParkPeople.getBindAccount()), PmgBatParkPeople::getBindAccount, pmgBatParkPeople.getBindAccount());
        qw.eq(PmgBatParkPeople::getBindStatus, 1);

        return this.list(qw);
    }

    private String getFangYuanPermissionStr(Long parkId, Long buildingId) {


        //获取这个人的楼栋id

        LambdaQueryWrapper<SaasParkElevatorPermissionElevatorGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Func.isNotEmpty(parkId), SaasParkElevatorPermissionElevatorGroup::getParkId, parkId);
        List<SaasParkElevatorPermissionElevatorGroup> records = saasParkElevatorPermissionElevatorGroupService.list(wrapper);


        List<PermissionDTO> permissionDTOList = new ArrayList<>();
        PermissionDTO permissionDTO = new PermissionDTO();
        permissionDTO.setLabel("所有");
        permissionDTO.setId("0");
        permissionDTO.setIsSelected(false);
        permissionDTO.setIsDisabled(false);
        List<GroupDTO> groupList = new ArrayList<>();
        for (SaasParkElevatorPermissionElevatorGroup group : records) {
            GroupDTO groupDTO = new GroupDTO();
            groupDTO.setIsSelected(false);
            groupDTO.setIsDisabled(false);
            groupDTO.setId(permissionDTO.getId() + "_" + group.getId() + "");
            groupDTO.setGroupId(group.getId());
            groupDTO.setLabel(group.getGroupName());

            groupDTO.setChildren(getPointFangYuan(group.getElevatorRange(), groupDTO.getId(), buildingId));
            groupList.add(groupDTO);
        }
        permissionDTO.setChildren(groupList);

        permissionDTOList.add(permissionDTO);


        return JSON.toJSONString(permissionDTOList);

    }

    private String getAllPermissionStr(Long parkId) {

        LambdaQueryWrapper<SaasParkElevatorPermissionElevatorGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Func.isNotEmpty(parkId), SaasParkElevatorPermissionElevatorGroup::getParkId, parkId);
        List<SaasParkElevatorPermissionElevatorGroup> records = saasParkElevatorPermissionElevatorGroupService.list(wrapper);


        List<PermissionDTO> permissionDTOList = new ArrayList<>();
        PermissionDTO permissionDTO = new PermissionDTO();
        permissionDTO.setLabel("所有");
        permissionDTO.setId("0");
        permissionDTO.setIsSelected(true);
        permissionDTO.setIsDisabled(false);
        List<GroupDTO> groupList = new ArrayList<>();
        for (SaasParkElevatorPermissionElevatorGroup group : records) {
            GroupDTO groupDTO = new GroupDTO();
            groupDTO.setIsSelected(true);
            groupDTO.setIsDisabled(false);
            groupDTO.setId(permissionDTO.getId() + "_" + group.getId() + "");
            groupDTO.setGroupId(group.getId());
            groupDTO.setLabel(group.getGroupName());

            groupDTO.setChildren(getPoint(group.getElevatorRange(), groupDTO.getId()));
            groupList.add(groupDTO);
        }
        permissionDTO.setChildren(groupList);

        permissionDTOList.add(permissionDTO);


        return JSON.toJSONString(permissionDTOList);


    }

    public List<DeviceDTO> getPointFangYuan(String strPoint, String id, Long buildId) {
        if (strPoint == null) {
            return null;
        }
        if (buildId == null) {
            return null;
        }
        String[] strPointList = strPoint.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(strPointList));
        List<SaasParkElevatorManageLocationEntity> listByIds = saasParkElevatorManageLocationMapper.getListByIds(list);

        List<DeviceDTO> deviceList = new ArrayList<>();
        for (SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity : listByIds) {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setId(id + "_" + saasParkElevatorManageLocationEntity.getId() + "");
            deviceDTO.setDeviceId(saasParkElevatorManageLocationEntity.getId());
            deviceDTO.setLabel(saasParkElevatorManageLocationEntity.getElevatorName());
            if (saasParkElevatorManageLocationEntity.getBuildingId().equals(buildId)) {
                deviceDTO.setIsSelected(true);
            } else {
                deviceDTO.setIsSelected(false);
            }
            deviceDTO.setIsDisabled(false);
            deviceDTO.setChildren(getFloor(saasParkElevatorManageLocationEntity.getStartFloor(), saasParkElevatorManageLocationEntity.getEndFloor(), deviceDTO.getId(),saasParkElevatorManageLocationEntity.getBuildingId().equals(buildId)));
            deviceList.add(deviceDTO);
        }
        return deviceList;

    }


    private List<FloorDTO> getFloorFangYuan(Integer start, Integer end, String id) {

        List<FloorDTO> listFloorDTO = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            FloorDTO floorDTO = new FloorDTO();
            floorDTO.setId(id + "_" + Long.parseLong(i + ""));
            floorDTO.setFloorId(Long.parseLong(i + ""));

            floorDTO.setLabel(i + "层");
            floorDTO.setIsSelected(true);
            floorDTO.setIsDisabled(false);

            if (i != 0) {
                listFloorDTO.add(floorDTO);
            }
        }
        return listFloorDTO;
    }


    public List<DeviceDTO> getPoint(String strPoint, String id) {
        if (strPoint == null) {
            return null;
        }
        String[] strPointList = strPoint.split(",");
        List<String> list = new ArrayList<>(Arrays.asList(strPointList));
        List<SaasParkElevatorManageLocationEntity> listByIds = saasParkElevatorManageLocationMapper.getListByIds(list);

        List<DeviceDTO> deviceList = new ArrayList<>();
        for (SaasParkElevatorManageLocationEntity saasParkElevatorManageLocationEntity : listByIds) {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setId(id + "_" + saasParkElevatorManageLocationEntity.getId() + "");
            deviceDTO.setDeviceId(saasParkElevatorManageLocationEntity.getId());
            deviceDTO.setLabel(saasParkElevatorManageLocationEntity.getElevatorName());
            deviceDTO.setIsSelected(true);
            deviceDTO.setIsDisabled(false);

            deviceDTO.setChildren(getFloor(saasParkElevatorManageLocationEntity.getStartFloor(), saasParkElevatorManageLocationEntity.getEndFloor(), deviceDTO.getId(),true));
            deviceList.add(deviceDTO);
        }
        return deviceList;

    }


    private List<FloorDTO> getFloor(Integer start, Integer end, String id, boolean eqBuilding) {

        List<FloorDTO> listFloorDTO = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            FloorDTO floorDTO = new FloorDTO();
            floorDTO.setId(id + "_" + Long.parseLong(i + ""));
            floorDTO.setFloorId(Long.parseLong(i + ""));

            floorDTO.setLabel(i + "层");
            if (eqBuilding) {
                floorDTO.setIsSelected(true);
            } else {
                floorDTO.setIsSelected(false);
            }
            floorDTO.setIsDisabled(false);

            if (i != 0) {
                listFloorDTO.add(floorDTO);
            }
        }
        return listFloorDTO;
    }


    /**
     * 同步电梯人员
     *
     * @return
     */
    @Override
    public void syncElevatorPerson(Long parkId, Long personId) {


        boolean result = false;

        //1、查询同步开关是否有开
        boolean isSyncElevator = false;

        isSyncElevator = getValueByValue(parkId, "isSyncElevator");

        //如果没开,直接关闭
        if (!isSyncElevator) {
            log.info("人员中心人员同步-梯控 没开");
            return;
        }

        //2、查询对应人员的人员类型大类是什么
        Map<String, String> map = new HashMap<>();
        Map<String, String> fangYuanRenYuanMap = peopleTypeMap(parkId, "房源人员");
        Map<String, String> teShuRenYuanRenYuanMap = peopleTypeMap(parkId, "特殊人员");
        Map<String, String> waiBuDengJiMap = peopleTypeMap(parkId, "外部登记");
        Map<String, String> teShuRenYuanMap = peopleTypeMap(parkId, "特殊人员");

        //3、合并几个大类
        map.putAll(fangYuanRenYuanMap);
        map.putAll(teShuRenYuanRenYuanMap);
        map.putAll(waiBuDengJiMap);
        map.putAll(teShuRenYuanMap);

        //4、获取还没同步的数据,判断最近同步时间有没有大于半小时,有的话进行这部分数据的同步,没有的话跳过
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -30);//获取半小时之前的时间


        //同步房源人员
        syncFangYuanRenYuan(parkId, personId, calendar, map);

        //同步物业人员
        syncWuYeRenYuan(parkId, personId, calendar, map);


    }

    private void syncWuYeRenYuan(Long parkId, Long personId, Calendar calendar, Map<String, String> map) {
        String wuYePermissionStr = getAllPermissionStr(parkId);

        boolean isSyncFangYuanRenYuan = false;
        boolean isSyncTeShuRenYuan = false;
        boolean isSyncWaiBuDengJi = false;
        boolean isSyncWuYeRenYuan = false;

        isSyncFangYuanRenYuan = getValueByValue(parkId, "isSyncFangYuanRenYuan");
        isSyncTeShuRenYuan = getValueByValue(parkId, "isSyncTeShuRenYuan");
        isSyncWaiBuDengJi = getValueByValue(parkId, "isSyncWaiBuDengJi");
        isSyncWuYeRenYuan = getValueByValue(parkId, "isSyncWuYeRenYuan");

        LambdaQueryWrapper<SaasParkPropertyPeopleInfo> qw = new LambdaQueryWrapper<>();
        //5、数据库里这个人的时间在当前时间半小时之前
        if (Func.isEmpty(personId)) {
            //手动某个人同步时候不进来,自动同步跟自动批量同步才进来
            qw.le(SaasParkPropertyPeopleInfo::getLastSyncElevatorTime, calendar.getTime());
        }
        qw.eq(SaasParkPropertyPeopleInfo::getIsDeleted, 0);
        qw.eq(Func.isNotEmpty(personId), SaasParkPropertyPeopleInfo::getId, personId);
        List<SaasParkPropertyPeopleInfo> listPmgBatParkPeople = saasParkPropertyPeopleInfoService.list(qw);

        for (SaasParkPropertyPeopleInfo saasParkPropertyPeopleInfo : listPmgBatParkPeople) {
            if (saasParkPropertyPeopleInfo.getPeopleType() != null) {
                //6、获取当前人员的大类型
                String bigType = map.get(saasParkPropertyPeopleInfo.getPeopleType().toString());
                //7、如果大类型是房源人员
                if ("房源人员".equals(bigType)) {
                    if (!isSyncFangYuanRenYuan) {
                        continue;
                    }
                }
                //8、如果大类型是特殊人员
                if ("特殊人员".equals(bigType)) {
                    if (!isSyncTeShuRenYuan) {
                        continue;
                    }
                }
                //9、如果大类型是外部人员
                if ("外部人员".equals(bigType)) {
                    if (!isSyncWaiBuDengJi) {
                        continue;
                    }
                }
                //10、如果大类型是物业人员
                if ("物业人员".equals(bigType)) {
                    if (!isSyncWuYeRenYuan) {
                        continue;
                    }


                }

                //物业人员需要同步对应默认所有的权限

                //房源人员需要同步对应默认权限


                //11、找到电梯的服务直接保存数据库
                SaasParkElevatorPerson saasParkElevatorPerson = new SaasParkElevatorPerson();

                saasParkElevatorPerson.setParkId(parkId);

                if (saasParkPropertyPeopleInfo.getSex() != null) {
                    if (saasParkPropertyPeopleInfo.getSex().equals("女")) {
                        saasParkElevatorPerson.setGender(2);
                    }
                    if (saasParkPropertyPeopleInfo.getSex().equals("男")) {
                        saasParkElevatorPerson.setGender(1);
                    }
                } else {
                    saasParkElevatorPerson.setGender(null);
                }
                saasParkElevatorPerson.setMianPersonId(saasParkPropertyPeopleInfo.getId());

//                saasParkElevatorPerson.setBuildingId(saasParkPropertyPeopleInfo.getBuildingId());
//                saasParkElevatorPerson.setUnitId(saasParkPropertyPeopleInfo.getBuildingUnitId());
//                saasParkElevatorPerson.setRoomNumberId(saasParkPropertyPeopleInfo.getRoomId());
                saasParkElevatorPerson.setBuildingId(null);
                saasParkElevatorPerson.setUnitId(null);
                saasParkElevatorPerson.setRoomNumberId(null);


                saasParkElevatorPerson.setCertificateNumber(saasParkPropertyPeopleInfo.getIdCard());
                saasParkElevatorPerson.setCertificateType(saasParkPropertyPeopleInfo.getIdType());
                saasParkElevatorPerson.setTelephone(saasParkPropertyPeopleInfo.getPhone());
                saasParkElevatorPerson.setCreateTime(new Date());
                saasParkElevatorPerson.setValidStartTime(new Date());
                String endTime = "2099-01-01 00:00:00";
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date date = formatter.parse(endTime);
                    saasParkElevatorPerson.setValidEndTime(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }


//                PropertyBuildingsLevel propertyBuildingsLevel = propertyBuildingsLevelService.getById(saasParkPropertyPeopleInfo.getFloorId());
//
//                if (propertyBuildingsLevel != null) {
//                    saasParkElevatorPerson.setFloorId(Long.parseLong(propertyBuildingsLevel.getLevelNum()));
//                }
                saasParkElevatorPerson.setFloorId(null);

                saasParkElevatorPerson.setUserType(2l);
                saasParkElevatorPerson.setUserId(saasParkPropertyPeopleInfo.getId());
                saasParkElevatorPerson.setUserFaceUrl(saasParkPropertyPeopleInfo.getFaceImgSrc());
                saasParkElevatorPerson.setIsDeleted(0);

                saasParkElevatorPerson.setUserName(saasParkPropertyPeopleInfo.getUserName());


                //判断是否已经同步,已经同步给id
                if (Func.isNotEmpty(saasParkElevatorPerson.getMianPersonId())) {
                    SaasParkElevatorPerson person = iSaasParkElevatorPersonService.getOne(new LambdaQueryWrapper<SaasParkElevatorPerson>().eq(SaasParkElevatorPerson::getMianPersonId, saasParkElevatorPerson.getMianPersonId()));
                    if (person != null) {
                        saasParkElevatorPerson.setId(person.getId());
                    } else {
                        //首次同步进行权限同步
                        //根据parkId和code获取这个人员类型的权限,把对应权限给到电梯的relative_elevator_group_json_str字段
                        LambdaQueryWrapper<PmgBatPeopleType> qwPeopleType = new LambdaQueryWrapper<>();
                        qwPeopleType.eq(PmgBatPeopleType::getCode, saasParkPropertyPeopleInfo.getPeopleType().toString());
                        qwPeopleType.eq(PmgBatPeopleType::getParkId, parkId);
                        qwPeopleType.last("limit 1");
                        PmgBatPeopleType pmgBatPeopleType = pmgBatPeopleTypeService.getOne(qwPeopleType);

                        if (pmgBatPeopleType != null) {
                            //外部人员默认设置的人员
                            if ("外部人员".equals(pmgBatPeopleType.getBigType())) {
                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(pmgBatPeopleType.getElevatorLimit());
                            }

                            //物业人员默认所有
                            if ("物业人员".equals(pmgBatPeopleType.getBigType())) {
                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(wuYePermissionStr);
                            }

                            //房源人员默认设置房源关联的设备与围墙机
                            if ("房源人员".equals(pmgBatPeopleType.getBigType())) {
                                String fangYuanPermissionStr = getFangYuanPermissionStr(parkId, saasParkElevatorPerson.getBuildingId());
                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(fangYuanPermissionStr);
                            }


                        }
                    }
                }


                boolean saveResult = iSaasParkElevatorPersonService.saveOrUpdate(saasParkElevatorPerson);

                //12、更新人员中心的人员表的最新同步时间
                if (saveResult) {
                    saasParkPropertyPeopleInfo.setLastSyncElevatorTime(new Date());
                    saasParkPropertyPeopleInfoService.saveOrUpdate(saasParkPropertyPeopleInfo);
                }
            }
        }
    }

    private void syncFangYuanRenYuan(Long parkId, Long personId, Calendar calendar, Map<String, String> map) {

        String wuYePermissionStr = getAllPermissionStr(parkId);

        boolean isSyncFangYuanRenYuan = false;
        boolean isSyncTeShuRenYuan = false;
        boolean isSyncWaiBuDengJi = false;
        boolean isSyncWuYeRenYuan = false;

        isSyncFangYuanRenYuan = getValueByValue(parkId, "isSyncFangYuanRenYuan");
        isSyncTeShuRenYuan = getValueByValue(parkId, "isSyncTeShuRenYuan");
        isSyncWaiBuDengJi = getValueByValue(parkId, "isSyncWaiBuDengJi");
        isSyncWuYeRenYuan = getValueByValue(parkId, "isSyncWuYeRenYuan");

        LambdaQueryWrapper<PmgBatParkPeople> qw = new LambdaQueryWrapper<>();
        //5、数据库里这个人的时间在当前时间半小时之前
        if (Func.isEmpty(personId)) {
            //手动某个人同步时候不进来,自动同步跟自动批量同步才进来
            qw.le(PmgBatParkPeople::getLastSyncElevatorTime, calendar.getTime());
        }
        qw.eq(PmgBatParkPeople::getIsDeleted, 0);
        qw.eq(Func.isNotEmpty(personId), PmgBatParkPeople::getId, personId);
        List<PmgBatParkPeople> listPmgBatParkPeople = this.list(qw);


        for (PmgBatParkPeople pmgBatParkPeople : listPmgBatParkPeople) {
            if (pmgBatParkPeople.getPeopleType() != null) {
                //6、获取当前人员的大类型
                String bigType = map.get(pmgBatParkPeople.getPeopleType().toString());
                //7、如果大类型是房源人员
                if ("房源人员".equals(bigType)) {
                    if (!isSyncFangYuanRenYuan) {
                        continue;
                    }
                }
                //8、如果大类型是特殊人员
                if ("特殊人员".equals(bigType)) {
                    if (!isSyncTeShuRenYuan) {
                        continue;
                    }
                }
                //9、如果大类型是外部人员
                if ("外部人员".equals(bigType)) {
                    if (!isSyncWaiBuDengJi) {
                        continue;
                    }
                }
                //10、如果大类型是物业人员
                if ("物业人员".equals(bigType)) {
                    if (!isSyncWuYeRenYuan) {
                        continue;
                    }


                }

                //物业人员需要同步对应默认所有的权限

                //房源人员需要同步对应默认权限


                //11、找到电梯的服务直接保存数据库
                SaasParkElevatorPerson saasParkElevatorPerson = new SaasParkElevatorPerson();

                saasParkElevatorPerson.setParkId(parkId);

                if (pmgBatParkPeople.getSex() != null) {
                    if (pmgBatParkPeople.getSex().equals("女")) {
                        saasParkElevatorPerson.setGender(2);
                    }
                    if (pmgBatParkPeople.getSex().equals("男")) {
                        saasParkElevatorPerson.setGender(1);
                    }
                } else {
                    saasParkElevatorPerson.setGender(null);
                }
                saasParkElevatorPerson.setMianPersonId(pmgBatParkPeople.getId());

                saasParkElevatorPerson.setBuildingId(pmgBatParkPeople.getBuildingId());
                saasParkElevatorPerson.setUnitId(pmgBatParkPeople.getBuildingUnitId());
                saasParkElevatorPerson.setRoomNumberId(pmgBatParkPeople.getRoomId());
                saasParkElevatorPerson.setCertificateNumber(pmgBatParkPeople.getIdCard());
                saasParkElevatorPerson.setCertificateType(pmgBatParkPeople.getIdType());
                saasParkElevatorPerson.setTelephone(pmgBatParkPeople.getPhone());
                saasParkElevatorPerson.setCreateTime(new Date());
                saasParkElevatorPerson.setValidStartTime(pmgBatParkPeople.getStartDate() == null ? new Date() : pmgBatParkPeople.getStartDate());
                String endTime = "2099-01-01 00:00:00";
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date date = formatter.parse(endTime);
                    saasParkElevatorPerson.setValidEndTime(pmgBatParkPeople.getExpireDate() == null ? date : pmgBatParkPeople.getExpireDate());
                } catch (ParseException e) {
                    e.printStackTrace();
                }


                PropertyBuildingsLevel propertyBuildingsLevel = propertyBuildingsLevelService.getById(pmgBatParkPeople.getFloorId());

                if (propertyBuildingsLevel != null) {
                    saasParkElevatorPerson.setFloorId(Long.parseLong(propertyBuildingsLevel.getLevelNum()));
                }

                saasParkElevatorPerson.setUserType(pmgBatParkPeople.getPeopleType());
                saasParkElevatorPerson.setUserId(pmgBatParkPeople.getId());
                saasParkElevatorPerson.setUserFaceUrl(pmgBatParkPeople.getImgsrc());
                saasParkElevatorPerson.setIsDeleted(0);

                saasParkElevatorPerson.setUserName(pmgBatParkPeople.getName());


                //判断是否已经同步,已经同步给id
                if (Func.isNotEmpty(saasParkElevatorPerson.getMianPersonId())) {
                    SaasParkElevatorPerson person = iSaasParkElevatorPersonService.getOne(new LambdaQueryWrapper<SaasParkElevatorPerson>().eq(SaasParkElevatorPerson::getMianPersonId, saasParkElevatorPerson.getMianPersonId()));
                    if (person != null) {
                        saasParkElevatorPerson.setId(person.getId());
                    } else {
                        //首次同步进行权限同步
                        //根据parkId和code获取这个人员类型的权限,把对应权限给到电梯的relative_elevator_group_json_str字段
                        LambdaQueryWrapper<PmgBatPeopleType> qwPeopleType = new LambdaQueryWrapper<>();
                        qwPeopleType.eq(PmgBatPeopleType::getCode, pmgBatParkPeople.getPeopleType().toString());
                        qwPeopleType.eq(PmgBatPeopleType::getParkId, parkId);
                        qwPeopleType.last("limit 1");
                        PmgBatPeopleType pmgBatPeopleType = pmgBatPeopleTypeService.getOne(qwPeopleType);

                        if (pmgBatPeopleType != null) {
                            //外部人员默认设置的人员
                            if ("外部人员".equals(pmgBatPeopleType.getBigType())) {
                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(pmgBatPeopleType.getElevatorLimit());
                            }

                            //物业人员默认所有
                            if ("物业人员".equals(pmgBatPeopleType.getBigType())) {
                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(wuYePermissionStr);
                            }

                            //房源人员默认设置房源关联的设备与围墙机
                            if ("房源人员".equals(pmgBatPeopleType.getBigType())) {

                                String fangYuanPermissionStr = getFangYuanPermissionStr(parkId, saasParkElevatorPerson.getBuildingId());


                                saasParkElevatorPerson.setRelativeElevatorGroupJsonStr(fangYuanPermissionStr);
                            }


                        }
                    }
                }


                boolean saveResult = iSaasParkElevatorPersonService.saveOrUpdate(saasParkElevatorPerson);

                //12、更新人员中心的人员表的最新同步时间
                if (saveResult) {
                    pmgBatParkPeople.setLastSyncElevatorTime(new Date());
                    this.saveOrUpdate(pmgBatParkPeople);
                }


            }
        }
    }


    /**
     * 同步门禁人员
     *
     * @param parkId
     */
    @Override
    public void syncDoorPerson(Long parkId, Long personId) {

    }


    private boolean getValueByValue(Long parkId, String key) {
        LambdaQueryWrapper<PmgBatPersonSysconfig> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(PmgBatPersonSysconfig::getParkId, parkId);
        queryWrapper.eq(PmgBatPersonSysconfig::getParamCode, key);
        PmgBatPersonSysconfig listPmgBatPersonSysconfig = iPmgBatPersonSysconfigService.getOne(queryWrapper);

        if (listPmgBatPersonSysconfig != null) {
            if ("1".equals(listPmgBatPersonSysconfig.getParamValue())) {
                log.info("parkId:{},{}有开,", parkId, key);
                return true;
            } else {
                log.info("parkId:{},{}没开,", parkId, key);
            }
        } else {
            log.info("parkId:{},{}没开,", parkId, key);
        }
        return false;
    }


    private Map<String, String> peopleTypeMap(long parkId, String bigType) {

        Map<String, String> map = new HashMap<>();

        LambdaQueryWrapper<PmgBatPeopleType> qwPeopleType = new LambdaQueryWrapper<>();
        qwPeopleType.eq(PmgBatPeopleType::getBigType, bigType);
        qwPeopleType.eq(PmgBatPeopleType::getParkId, parkId);
        List<PmgBatPeopleType> listPmgBatPeopleType = pmgBatPeopleTypeService.list(qwPeopleType);

        if (listPmgBatPeopleType != null) {
            for (PmgBatPeopleType pmgBatPeopleType : listPmgBatPeopleType) {
                map.put(pmgBatPeopleType.getCode(), bigType);
            }
        }
        return map;
    }


}
