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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.dto.people.*;
import com.yuchen.saas.park.api.entity.approve.SaasGenericConfig;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.park.PmgBatPeopleType;
import com.yuchen.saas.park.api.entity.park.people.SaasParkExternalPeopleInfo;
import com.yuchen.saas.park.api.entity.property.PropertyBuildingUnit;
import com.yuchen.saas.park.api.entity.property.PropertyBuildings;
import com.yuchen.saas.park.api.entity.property.PropertyCustomerArchives;
import com.yuchen.saas.park.api.entity.property.PropertyHouses;
import com.yuchen.saas.park.api.enums.PeopleRegisterEnum;
import com.yuchen.saas.park.api.enums.property.CreateTypeEnum;
import com.yuchen.saas.park.api.enums.property.CustomerCategoryEnum;
import com.yuchen.saas.park.api.enums.property.CustomerTypeEnum;
import com.yuchen.saas.park.api.enums.property.YesOrNoEnum;
import com.yuchen.saas.park.api.vo.people.ExternalExpressPeopleInfoPageVO;
import com.yuchen.saas.park.api.vo.people.ExternalExpressPeopleInfoVO;
import com.yuchen.saas.park.api.vo.people.ExternalPeopleInfoPageVO;
import com.yuchen.saas.park.api.vo.people.ExternalPeopleInfoVO;
import com.yuchen.saas.park.service.mapper.people.SaasParkExternalPeopleInfoMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.PmgBatPeopleTypeService;
import com.yuchen.saas.park.service.service.approve.ISaasGenericConfigService;
import com.yuchen.saas.park.service.service.people.ISaasParkExternalPeopleInfoService;
import com.yuchen.saas.park.service.service.property.IPropertyCustomerArchivesService;
import com.yuchen.saas.park.service.service.property.PropertyBuildingUnitService;
import com.yuchen.saas.park.service.service.property.PropertyBuildingsService;
import com.yuchen.saas.park.service.service.property.PropertyHousesService;
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.NestPage;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.nest.springwrap.core.tool.utils.SpringUtil;
import org.nest.springwrap.core.tool.validator.ValidatorUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 外部人员信息表 服务实现类
 * </p>
 *
 * @author linyb
 * @since 2024-12-01
 */
@Service
public class SaasParkExternalPeopleInfoServiceImpl extends BaseServiceImpl<SaasParkExternalPeopleInfoMapper, SaasParkExternalPeopleInfo> implements ISaasParkExternalPeopleInfoService {

    @Resource
    private PropertyHousesService housesService;

    @Resource
    private PropertyBuildingsService buildingsService;
    @Resource
    private PropertyBuildingUnitService unitService;

    @Resource
    private PmgBatParkInfoService parkInfoService;

    @Resource
    private IPropertyCustomerArchivesService iPropertyCustomerArchivesService;


    @Resource
    private IOrgUserClient orgUserClient;


    @Resource
    private ISaasGenericConfigService saasGenericConfigService;

    @Resource
    private PmgBatPeopleTypeService peopleTypeService;

    @Override
    public NestPage<ExternalPeopleInfoPageVO> getPage(ExternalPeopleInfoPageDTO dto) {
        ValidatorUtils.validateEntity(dto);
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SaasParkExternalPeopleInfo::getProjectId,dto.getProjectId());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getBuildingId()),SaasParkExternalPeopleInfo::getBuildingId,dto.getBuildingId());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getUnitId()),SaasParkExternalPeopleInfo::getUnitId,dto.getUnitId());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getHouseId()),SaasParkExternalPeopleInfo::getHouseId,dto.getHouseId());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getUserName()),SaasParkExternalPeopleInfo::getUserName,dto.getUserName());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getSex()),SaasParkExternalPeopleInfo::getSex,dto.getSex());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getPhone()),SaasParkExternalPeopleInfo::getPhone,dto.getPhone());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getIdCard()),SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getIdType()),SaasParkExternalPeopleInfo::getIdType,dto.getIdType());

        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getCertificationStatus()),SaasParkExternalPeopleInfo::getCertificationStatus,dto.getCertificationStatus());
        lambdaQueryWrapper.ge(Func.isNotEmpty(dto.getRegisterStartTime()),SaasParkExternalPeopleInfo::getRegisterStartTime,dto.getRegisterStartTime());
        lambdaQueryWrapper.le(Func.isNotEmpty(dto.getRegisterEndTime()),SaasParkExternalPeopleInfo::getRegisterEndTime,dto.getRegisterEndTime());

        lambdaQueryWrapper.in(SaasParkExternalPeopleInfo::getPeopleType,14,15);
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getPeopleType()),SaasParkExternalPeopleInfo::getPeopleType,dto.getPeopleType());
        lambdaQueryWrapper.and(Func.isNotEmpty(dto.getEffectiveStatus()),i->{
            i.isNotNull(SaasParkExternalPeopleInfo::getRegisterEndTime)
                    .eq(SaasParkExternalPeopleInfo::getCertificationStatus, 2);
            if (dto.getEffectiveStatus() == 1) {
                i.lt(SaasParkExternalPeopleInfo::getRegisterEndTime, new Date());
            } else if (dto.getEffectiveStatus() == 2) {
                i.ge(SaasParkExternalPeopleInfo::getRegisterEndTime, new Date());
            }});
        IPage<SaasParkExternalPeopleInfo> page = Condition.getPage(dto);
        IPage<SaasParkExternalPeopleInfo> iPage = this.page(page, lambdaQueryWrapper);
        NestPage<ExternalPeopleInfoPageVO> nestPage = new NestPage<>();
        nestPage.setSize(dto.getSize());
        nestPage.setCurrent(dto.getCurrent());
        List<SaasParkExternalPeopleInfo> records = iPage.getRecords();
        if (Func.isEmpty(records)){
            return nestPage;
        }
        List<Long> buildingIdList = records.stream().map(SaasParkExternalPeopleInfo::getBuildingId).filter(Func::isNotEmpty).distinct().collect(Collectors.toList());
        Map<Long, String> buildingHashMap = new HashMap<>(2);
        List<PropertyBuildings> propertyBuildings = buildingsService.listByIds(buildingIdList);
        buildingHashMap.putAll(propertyBuildings.stream().collect(Collectors.toMap(PropertyBuildings::getId,PropertyBuildings::getBuildingName)));
        List<Long> unitIdList = records.stream().map(SaasParkExternalPeopleInfo::getUnitId).filter(Func::isNotEmpty).distinct().collect(Collectors.toList());
        Map<Long, String> unitHashMap = new HashMap<>(2);
        List<PropertyBuildingUnit> unitList = unitService.listByIds(unitIdList);
        unitHashMap.putAll(unitList.stream().collect(Collectors.toMap(PropertyBuildingUnit::getId,PropertyBuildingUnit::getUnitName)));
        List<Long> houseIdList = records.stream().map(SaasParkExternalPeopleInfo::getHouseId).filter(Func::isNotEmpty).distinct().collect(Collectors.toList());
        Map<Long, String> houseHashMap = new HashMap<>(2);
        List<PropertyHouses> housesList = housesService.listByIds(houseIdList);
        houseHashMap.putAll(housesList.stream().collect(Collectors.toMap(PropertyHouses::getId,PropertyHouses::getHouseName)));
        List<Long> confirmOrgUserList = records.stream()
                .map(SaasParkExternalPeopleInfo::getConfirmOrgUser)
                .filter(Func::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> confirmOrgUserMap =new HashMap<>(2);
        R<List<NestOrgUser>> confirmOrgUserListR = orgUserClient.findOrgUserListByIds(confirmOrgUserList);
        if (R.isSuccess(confirmOrgUserListR)&&Func.isNotEmpty(confirmOrgUserListR.getData())){
            confirmOrgUserMap.putAll(confirmOrgUserListR.getData().stream()
                    .collect(Collectors.toMap(NestOrgUser::getId, NestOrgUser::getName)));
        }

        List<Long> parkIdList = records.stream()
                .map(SaasParkExternalPeopleInfo::getProjectId)
                .filter(Func::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        List<PmgBatParkInfo> parkInfoList = parkInfoService.listByIds(parkIdList);
        Map<Long, String> parkMap = parkInfoList.stream()
                .collect(Collectors.toMap(PmgBatParkInfo::getId, PmgBatParkInfo::getParkName));
        List<ExternalPeopleInfoPageVO> infoPageVOS = records.stream()
                .map(e -> {
            ExternalPeopleInfoPageVO pageVO = new ExternalPeopleInfoPageVO();
            Func.copy(e, pageVO);
            if (Func.isNotEmpty(pageVO.getBuildingId())){
                String buildingName = buildingHashMap.get(pageVO.getBuildingId());
                pageVO.setBuildingName(buildingName);
            }
            if (Func.isNotEmpty(pageVO.getUnitId())){
                String unitName = unitHashMap.get(pageVO.getBuildingId());
                pageVO.setUnitName(unitName);
            }
            if (Func.isNotEmpty(pageVO.getHouseId())){
                String houseName = houseHashMap.get(pageVO.getHouseId());
                pageVO.setHouseName(houseName);
            }
            if(Func.isNotEmpty(e.getProjectId())){
                String parkName = parkMap.get(e.getProjectId());
                pageVO.setProjectName(parkName);
            }
            pageVO.setPeopleType(e.getPeopleType());
            pageVO.setConfirmOrgUser(e.getConfirmOrgUser());
            if(Func.isNotEmpty(e.getConfirmOrgUser())){
                String orgUserName = confirmOrgUserMap.get(e.getConfirmOrgUser());
                pageVO.setConfirmOrgUserName(orgUserName);
            }

            return pageVO;
        }).collect(Collectors.toList());
        nestPage.setRecords(infoPageVOS);
        return nestPage;
    }

    @Override
    public ExternalPeopleInfoVO info(Long id) {
        SaasParkExternalPeopleInfo peopleInfo = this.getById(id);
        if (Func.isEmpty(peopleInfo)){
            throw new ServiceException("数据不存在！");
        }
        ExternalPeopleInfoVO pageVO = Func.copy(peopleInfo, ExternalPeopleInfoVO.class);
        if(Func.isNotEmpty(pageVO.getProjectId())){
            PmgBatParkInfo parkInfo = parkInfoService.getById(pageVO.getProjectId());
            if (Func.isNotEmpty(parkInfo)){
                String parkName = parkInfo.getParkName();
                pageVO.setProjectName(parkName);
            }

        }
        if(Func.isNotEmpty(pageVO.getBuildingId())){
            PropertyBuildings buildings = buildingsService.getById(pageVO.getBuildingId());
            if (Func.isNotEmpty(buildings)){
                pageVO.setBuildingName(buildings.getBuildingName());
            }
        }
        if(Func.isNotEmpty(pageVO.getUnitId())){
            PropertyBuildingUnit unit = unitService.getById(pageVO.getBuildingId());
            if (Func.isNotEmpty(unit)){
                pageVO.setUnitName(unit.getUnitName());
            }
        }
        if(Func.isNotEmpty(pageVO.getHouseName())){
            PropertyHouses houses = housesService.getById(pageVO.getBuildingId());
            if (Func.isNotEmpty(houses)){
                pageVO.setHouseName(houses.getHouseName());
            }
        }
        if(Func.isNotEmpty(pageVO.getConfirmOrgUser())){
            R<NestOrgUser> orgUserR = orgUserClient.detail(pageVO.getConfirmOrgUser());
            if (R.isSuccess(orgUserR)&&Func.isNotEmpty(orgUserR.getData())){
                pageVO.setConfirmOrgUserName(orgUserR.getData().getName());
            }
        }
        return pageVO;
    }

    @Override
    public boolean save(ExternalPeopleInfoSaveDTO dto) {
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaasParkExternalPeopleInfo::getHouseId,dto.getHouseId());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getOwnerPeopleId,dto.getOwnerPeopleId());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getCertificationStatus,1);
        int one = this.count(queryWrapper);
        if (one>0){
            throw new ServiceException("该房源已存在此人员待确认，无需重复添加");
        }
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getHouseId,dto.getHouseId());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getOwnerPeopleId,dto.getOwnerPeopleId());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getCertificationStatus,2);
        queryWrapper1.ge(SaasParkExternalPeopleInfo::getRegisterEndTime,new Date());
        int one1 = this.count(queryWrapper1);
        if (one1>0){
            throw new ServiceException("该房源已存在此人员，无需重复添加");
        }
        //todo 人员如何去重  按身份证还是楼栋
        SaasParkExternalPeopleInfo saasParkExternalPeopleInfo = new SaasParkExternalPeopleInfo();
        Func.copy(dto,saasParkExternalPeopleInfo);
        saasParkExternalPeopleInfo.setCertificationStatus(1);
        if (Func.isNotEmpty(AuthUtil.getUser())&&Func.isNotEmpty(AuthUtil.getUser().getOrgUserId())){
            saasParkExternalPeopleInfo.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
            saasParkExternalPeopleInfo.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        }
        boolean save = this.save(saasParkExternalPeopleInfo);
        if (save){
            SaasParkExternalPeopleInfoServiceImpl bean = SpringUtil.getBean(SaasParkExternalPeopleInfoServiceImpl.class);
            bean.sysPropertyCustomerArchives(saasParkExternalPeopleInfo);
        }

        return save;
    }

    @Override
    public boolean update(ExternalPeopleInfoUpdateDTO dto) {
        SaasParkExternalPeopleInfo peopleInfo = this.getById(dto.getId());
        if (Func.isEmpty(peopleInfo)){
            throw new ServiceException("数据不存在！");
        }

        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaasParkExternalPeopleInfo::getHouseId,dto.getHouseId());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getOwnerPeopleId,dto.getOwnerPeopleId());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper.ne(SaasParkExternalPeopleInfo::getId,dto.getId());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getCertificationStatus,1);
        int one = this.count(queryWrapper);
        if (one>0){
            throw new ServiceException("该房源已存在此人员待确认，无需重复添加");
        }
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getHouseId,dto.getHouseId());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getOwnerPeopleId,dto.getOwnerPeopleId());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper1.ne(SaasParkExternalPeopleInfo::getId,dto.getId());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getCertificationStatus,2);
        queryWrapper1.ge(SaasParkExternalPeopleInfo::getRegisterEndTime,new Date());
        int one1 = this.count(queryWrapper1);
        if (one1>0){
            throw new ServiceException("该房源已存在此人员，无需重复添加");
        }
        Func.copy(dto,peopleInfo);
        if (Func.isNotEmpty(AuthUtil.getUser())&&Func.isNotEmpty(AuthUtil.getUser().getOrgUserId())){
            peopleInfo.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());

        }
        boolean update = this.updateById(peopleInfo);
        if (update){
            SaasParkExternalPeopleInfoServiceImpl bean = SpringUtil.getBean(SaasParkExternalPeopleInfoServiceImpl.class);
            bean.sysPropertyCustomerArchives(peopleInfo);
        }
        return update;
    }

    @Override
    public boolean approve(PropertyPeopleExternalApproveDTO dto) {
        SaasParkExternalPeopleInfo register = this.getById(dto.getId());
        if (Func.isEmpty(register)){
            throw new ServiceException("数据不存在！");
        }
        if(dto.getApproveStatus()==2){
            register.setCertificationStatus(PeopleRegisterEnum.REJECTED.getCode());
            register.setConfirmTime(new Date());
            register.setConfirmOrgUser(AuthUtil.getUser().getOrgUserId());
            register.setApproveRemark(dto.getApproveRemark());

            return this.updateById(register);
        }
        if(dto.getApproveStatus()==1){
            register.setCertificationStatus(PeopleRegisterEnum.CONFIRMED.getCode());
            register.setConfirmTime(new Date());
            register.setConfirmOrgUser(AuthUtil.getUser().getOrgUserId());
            register.setApproveRemark(dto.getApproveRemark());
            register.setConfirmType(2);
            boolean updateById = this.updateById(register);
            return updateById;
        }
        return false;
    }

    @Override
    public boolean approveBatch(PropertyPeopleExternalApproveBatchDTO dto) {
        List<SaasParkExternalPeopleInfo> list = this.listByIds(dto.getIdList());
        list.forEach(e->{

            if(dto.getApproveStatus()==2){
                e.setCertificationStatus(PeopleRegisterEnum.REJECTED.getCode());

            }
            if(dto.getApproveStatus()==1) {
                e.setCertificationStatus(PeopleRegisterEnum.CONFIRMED.getCode());
                e.setConfirmType(2);
            }

            e.setConfirmTime(new Date());
            e.setConfirmOrgUser(AuthUtil.getUser().getOrgUserId());
            e.setApproveRemark(dto.getApproveRemark());
        });
        return this.updateBatchById(list,list.size());
    }

    @Override
    public NestPage<ExternalExpressPeopleInfoPageVO> getPage(ExternalExpressPeopleInfoPageDTO dto) {
        ValidatorUtils.validateEntity(dto);
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SaasParkExternalPeopleInfo::getProjectId,dto.getProjectId());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getUserName()),SaasParkExternalPeopleInfo::getUserName,dto.getUserName());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getSex()),SaasParkExternalPeopleInfo::getSex,dto.getSex());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getPhone()),SaasParkExternalPeopleInfo::getPhone,dto.getPhone());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getIdCard()),SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getIdType()),SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getCertificationStatus()),SaasParkExternalPeopleInfo::getCertificationStatus,dto.getCertificationStatus());
        lambdaQueryWrapper.ge(Func.isNotEmpty(dto.getRegisterStartTime()),SaasParkExternalPeopleInfo::getRegisterStartTime,dto.getRegisterStartTime());
        lambdaQueryWrapper.le(Func.isNotEmpty(dto.getRegisterEndTime()),SaasParkExternalPeopleInfo::getRegisterEndTime,dto.getRegisterEndTime());
        lambdaQueryWrapper.in(SaasParkExternalPeopleInfo::getPeopleType,13);
        IPage<SaasParkExternalPeopleInfo> page = Condition.getPage(dto);
        IPage<SaasParkExternalPeopleInfo> iPage = this.page(page, lambdaQueryWrapper);
        NestPage<ExternalExpressPeopleInfoPageVO> nestPage = new NestPage<>();
        nestPage.setSize(dto.getSize());
        nestPage.setCurrent(dto.getCurrent());
        List<SaasParkExternalPeopleInfo> records = iPage.getRecords();
        if (Func.isEmpty(records)){
            return nestPage;
        }
        List<Long> confirmOrgUserList = records.stream()
                .map(SaasParkExternalPeopleInfo::getConfirmOrgUser)
                .filter(Func::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, String> confirmOrgUserMap =new HashMap<>(2);
        R<List<NestOrgUser>> confirmOrgUserListR = orgUserClient.findOrgUserListByIds(confirmOrgUserList);
        if (R.isSuccess(confirmOrgUserListR)&&Func.isNotEmpty(confirmOrgUserListR.getData())){
            confirmOrgUserMap= confirmOrgUserListR.getData().stream()
                    .collect(Collectors.toMap(NestOrgUser::getId, NestOrgUser::getName));
        }

        List<Long> parkIdList = records.stream()
                .map(SaasParkExternalPeopleInfo::getProjectId)
                .filter(Func::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        List<PmgBatParkInfo> parkInfoList = parkInfoService.listByIds(parkIdList);
        Map<Long, String> parkMap = parkInfoList.stream()
                .collect(Collectors.toMap(PmgBatParkInfo::getId, PmgBatParkInfo::getParkName));
        List<ExternalExpressPeopleInfoPageVO> registerPageVOList =new ArrayList<>();
        for (SaasParkExternalPeopleInfo e : records) {
            ExternalExpressPeopleInfoPageVO pageVO = new ExternalExpressPeopleInfoPageVO();
            Func.copy(e,pageVO);
            pageVO.setIdCard(e.getIdCard());
            pageVO.setProjectId(e.getProjectId());
            if(Func.isNotEmpty(e.getProjectId())){
                String parkName = parkMap.get(e.getProjectId());
                pageVO.setProjectName(parkName);
            }
            pageVO.setPeopleType(e.getPeopleType());
            pageVO.setConfirmOrgUser(e.getConfirmOrgUser());
            if(Func.isNotEmpty(e.getConfirmOrgUser())){
                String orgUserName = confirmOrgUserMap.get(e.getConfirmOrgUser());
                pageVO.setConfirmOrgUserName(orgUserName);
            }
            registerPageVOList.add(pageVO);
        }

        nestPage.setRecords(registerPageVOList);
        return nestPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean expressSave(ExternalExpressPeopleInfoSaveDTO dto) {
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper.eq(SaasParkExternalPeopleInfo::getCertificationStatus,1);
        int one = this.count(queryWrapper);
        if (one>0){
            throw new ServiceException("此人员已存在待工作人员确认，无需重复登记。");
        }
        LambdaQueryWrapper<SaasParkExternalPeopleInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdCard,dto.getIdCard());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getIdType,dto.getIdType());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getPeopleType,dto
                .getPeopleType());
        queryWrapper1.eq(SaasParkExternalPeopleInfo::getCertificationStatus,2);
        queryWrapper1.ge(SaasParkExternalPeopleInfo::getRegisterEndTime,new Date());
        int one1 = this.count(queryWrapper1);
        if (one1>0){
            throw new ServiceException("此人员已存在且在有效期，无需重复登记。");
        }

        SaasParkExternalPeopleInfo saasParkExternalPeopleInfo = new SaasParkExternalPeopleInfo();
        Func.copy(dto,saasParkExternalPeopleInfo);
        saasParkExternalPeopleInfo.setCertificationStatus(1);
        if (Func.isNotEmpty(AuthUtil.getUser())&&Func.isNotEmpty(AuthUtil.getUser().getOrgUserId())){
            saasParkExternalPeopleInfo.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
            saasParkExternalPeopleInfo.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        }
        //获取自动确认配置
        LambdaQueryWrapper<SaasGenericConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(SaasGenericConfig::getParkId,dto.getProjectId());
        configLambdaQueryWrapper.eq(SaasGenericConfig::getConfigGroupName,"外卖快递审核");
        SaasGenericConfig saasGenericConfig = saasGenericConfigService.getOne(configLambdaQueryWrapper, false);
        if (Func.isNotEmpty(saasGenericConfig)){
            if (Func.equalsSafe(saasGenericConfig.getConfigGroupValue(),"1")){
                Date date = new Date();
                saasParkExternalPeopleInfo.setCertificationStatus(2);
                saasParkExternalPeopleInfo.setConfirmType(1);
                saasParkExternalPeopleInfo.setConfirmTime(date);
                //获取有效时间
                LambdaQueryWrapper<PmgBatPeopleType> peopleTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
                peopleTypeLambdaQueryWrapper.eq(PmgBatPeopleType::getParkId,dto.getProjectId());
                peopleTypeLambdaQueryWrapper.in(PmgBatPeopleType::getCode,13,19);
                PmgBatPeopleType peopleType = peopleTypeService.getOne(peopleTypeLambdaQueryWrapper, false);
                if (Func.isNotEmpty(peopleType)) {
                    if (Func.isNotEmpty(peopleType.getUpdateDays())){
                        saasParkExternalPeopleInfo.setRegisterStartTime(date);
                        saasParkExternalPeopleInfo.setRegisterEndTime(DateUtil.offsetDay(date,peopleType.getUpdateDays()));
                    }
                }
                boolean save = this.save(saasParkExternalPeopleInfo);
                if (save){
                    SaasParkExternalPeopleInfoServiceImpl bean = SpringUtil.getBean(SaasParkExternalPeopleInfoServiceImpl.class);
                    bean.sysPropertyCustomerArchives(saasParkExternalPeopleInfo);
                }
                return save;
            }
        }
        boolean save = this.save(saasParkExternalPeopleInfo);

        return save;
    }

    @Override
    public ExternalExpressPeopleInfoVO expressInfo(Long id) {

        SaasParkExternalPeopleInfo peopleInfo = this.getById(id);
        if (Func.isEmpty(peopleInfo)){
            throw new ServiceException("数据不存在！");
        }
        ExternalExpressPeopleInfoVO pageVO = Func.copy(peopleInfo, ExternalExpressPeopleInfoVO.class);
        if(Func.isNotEmpty(pageVO.getProjectId())){
            PmgBatParkInfo parkInfo = parkInfoService.getById(pageVO.getProjectId());
            if (Func.isNotEmpty(parkInfo)){
                String parkName = parkInfo.getParkName();
                pageVO.setProjectName(parkName);
            }
        }
        if(Func.isNotEmpty(pageVO.getConfirmOrgUser())){
            R<NestOrgUser> orgUserR = orgUserClient.detail(pageVO.getConfirmOrgUser());
            if (R.isSuccess(orgUserR)&&Func.isNotEmpty(orgUserR.getData())){
                pageVO.setConfirmOrgUserName(orgUserR.getData().getName());
            }
        }
        return pageVO;
    }

    @Async
    //todo 同步人员档案 后期需求
    public void sysPropertyCustomerArchives(SaasParkExternalPeopleInfo peopleInfo){
        if (Func.isNotEmpty(peopleInfo.getIdCard())) {
            Integer count = iPropertyCustomerArchivesService.lambdaQuery().eq(PropertyCustomerArchives::getIdNo, peopleInfo.getIdCard()).count();
            if (count > 0) {
                return;
            }
        }
        PropertyCustomerArchives createCustomerArchives = new PropertyCustomerArchives();
        createCustomerArchives.setParkId(peopleInfo.getProjectId());
        createCustomerArchives.setCustomerType(CustomerTypeEnum.PERSON.getValue());
        createCustomerArchives.setCustomerCategory(CustomerCategoryEnum.OTHER.getValue() );
        createCustomerArchives.setCustomerName(peopleInfo.getUserName());
        createCustomerArchives.setIdNo(peopleInfo.getIdCard());
        createCustomerArchives.setIdType(Integer.valueOf(peopleInfo.getIdType()));
        createCustomerArchives.setLinkManOne(peopleInfo.getUserName());
        createCustomerArchives.setLinkPhoneOne(peopleInfo.getPhone());
        createCustomerArchives.setFacePhoto(peopleInfo.getFaceImgSrc());
        createCustomerArchives.setSex(Integer.valueOf(peopleInfo.getSex()));
        createCustomerArchives.setCreateType(CreateTypeEnum.AUTO_SYNC.getValue());
        createCustomerArchives.setCreatePeopleId(AuthUtil.getUser().getUserDetailId());
        createCustomerArchives.setIsLink(YesOrNoEnum.YES.getValue());
        iPropertyCustomerArchivesService.save(createCustomerArchives);
    }
}
