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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.manage.user.api.entity.User;
import com.yuchen.saas.manage.user.api.feign.IUserClient;
import com.yuchen.saas.park.api.dto.people.*;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.entity.park.people.SaasParkPropertyPeopleInfo;
import com.yuchen.saas.park.api.entity.property.PropertyBuildings;
import com.yuchen.saas.park.api.entity.property.PropertyCustomerArchives;
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.PropertyPeopleBuildingManagerPageVO;
import com.yuchen.saas.park.api.vo.people.PropertyPeopleBuildingManagerWechatVO;
import com.yuchen.saas.park.api.vo.people.PropertyPeopleInfoPageVO;
import com.yuchen.saas.park.api.vo.people.PropertyPeopleInfoVO;
import com.yuchen.saas.park.service.mapper.people.SaasParkPropertyPeopleInfoMapper;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.people.ISaasParkPropertyPeopleInfoService;
import com.yuchen.saas.park.service.service.property.IPropertyCustomerArchivesService;
import com.yuchen.saas.park.service.service.property.PropertyBuildingsService;
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 javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 物业人员信息表 服务实现类
 * </p>
 *
 * @author linyb
 * @since 2024-11-30
 */
@Service
public class SaasParkPropertyPeopleInfoServiceImpl extends BaseServiceImpl<SaasParkPropertyPeopleInfoMapper, SaasParkPropertyPeopleInfo> implements ISaasParkPropertyPeopleInfoService {

    @Resource
    private IUserClient userClient;

    @Resource
    private IOrgUserClient orgUserClient;

    @Resource
    private PmgBatParkInfoService parkInfoService;

    @Resource
    private IPropertyCustomerArchivesService iPropertyCustomerArchivesService;


    @Resource
    private PropertyBuildingsService buildingsService;

    @Override
    public NestPage<PropertyPeopleInfoPageVO> getPage(PropertyPeopleInfoPageDTO dto) {
        ValidatorUtils.validateEntity(dto);
        LambdaQueryWrapper<SaasParkPropertyPeopleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SaasParkPropertyPeopleInfo::getProjectId,dto.getProjectId());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getSex()),SaasParkPropertyPeopleInfo::getSex,dto.getSex());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getPeopleType()),SaasParkPropertyPeopleInfo::getPeopleType,dto.getPeopleType());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getPhone()),SaasParkPropertyPeopleInfo::getPhone,dto.getPhone());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getIdCard()),SaasParkPropertyPeopleInfo::getIdCard,dto.getIdCard());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getIdType()),SaasParkPropertyPeopleInfo::getIdType,dto.getIdType());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getUserName()),SaasParkPropertyPeopleInfo::getUserName,dto.getUserName());
        lambdaQueryWrapper.like(Func.isNotEmpty(dto.getBindAccount()),SaasParkPropertyPeopleInfo::getBindAccount,dto.getBindAccount());
        lambdaQueryWrapper.eq(Func.isNotEmpty(dto.getBindStatus()),SaasParkPropertyPeopleInfo::getBindStatus,dto.getBindStatus());
        IPage<SaasParkPropertyPeopleInfo> page = Condition.getPage(dto);
        IPage<SaasParkPropertyPeopleInfo> iPage = this.page(page, lambdaQueryWrapper);
        NestPage<PropertyPeopleInfoPageVO> nestPage = new NestPage<>();
        nestPage.setSize(dto.getSize());
        nestPage.setCurrent(dto.getCurrent());
        List<SaasParkPropertyPeopleInfo> records = iPage.getRecords();
        if (Func.isEmpty(records)){
            return nestPage;
        }
        List<PropertyPeopleInfoPageVO> infoPageVOS = records.stream().map(e -> {
            PropertyPeopleInfoPageVO pageVO = new PropertyPeopleInfoPageVO();
            Func.copy(e, pageVO);
            return pageVO;
        }).collect(Collectors.toList());
        nestPage.setRecords(infoPageVOS);
        return nestPage;
    }

    @Override
    public PropertyPeopleInfoVO info(Long id) {
        SaasParkPropertyPeopleInfo peopleInfo = this.getById(id);
        if (Func.isEmpty(peopleInfo)){
            throw new ServiceException("数据不存在！");
        }
        PropertyPeopleInfoVO pageVO = new PropertyPeopleInfoVO();
        Func.copy(peopleInfo,pageVO);
        if(Func.isNotEmpty(pageVO.getBindAccount())){
            R<User> user = userClient.getUserById(peopleInfo.getBindAccount());
            if (R.isSuccess(user)&&Func.isNotEmpty(user.getData())){
                String userName = user.getData().getName();
                pageVO.setBindAccountName(userName);
            }
        }
        if(Func.isNotEmpty(pageVO.getProjectId())){
            PmgBatParkInfo parkInfo = parkInfoService.getById(pageVO.getProjectId());
            if (Func.isNotEmpty(parkInfo)){
                String parkName = parkInfo.getParkName();
                pageVO.setProjectName(parkName);
            }

        }
        return pageVO;
    }

    @Override
    public boolean save(PropertyPeopleInfoSaveDTO dto) {
        LambdaQueryWrapper<SaasParkPropertyPeopleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaasParkPropertyPeopleInfo::getPhone,dto.getPhone());

        int one = this.count(queryWrapper);
        if (one>0){
            throw new ServiceException("该手机号已存在物业人员信息中");
        }

        if (Func.isNotEmpty(dto.getIdCard())){
            LambdaQueryWrapper<SaasParkPropertyPeopleInfo> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SaasParkPropertyPeopleInfo::getIdCard,dto.getIdCard());
            int one1 = this.count(queryWrapper);
            if (one1>0){
                throw new ServiceException("该证件号已存在物业人员信息中");
            }
        }
        SaasParkPropertyPeopleInfo peopleInfo = new SaasParkPropertyPeopleInfo();
        Func.copy(dto,peopleInfo);
        if (Func.isNotEmpty(AuthUtil.getUser())&&Func.isNotEmpty(AuthUtil.getUser().getOrgUserId())){
            peopleInfo.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
            peopleInfo.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        }
        boolean save = this.save(peopleInfo);
        if (save){
            SaasParkPropertyPeopleInfoServiceImpl bean = SpringUtil.getBean(SaasParkPropertyPeopleInfoServiceImpl.class);
            bean.sysPropertyCustomerArchives(peopleInfo);
        }
        return save;
    }

    @Override
    public boolean update(PropertyPeopleInfoUpdateDTO dto) {
        SaasParkPropertyPeopleInfo saasParkPropertyPeopleInfo = this.getById(dto.getId());
        if (Func.isEmpty(saasParkPropertyPeopleInfo)){
            throw new ServiceException("数据不存在！");
        }
        LambdaQueryWrapper<SaasParkPropertyPeopleInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SaasParkPropertyPeopleInfo::getPhone,dto.getPhone());
        queryWrapper.ne(SaasParkPropertyPeopleInfo::getId,dto.getId());
        int one = this.count(queryWrapper);
        if (one>0){
            throw new ServiceException("该手机号已存在物业人员信息中");
        }

        if (Func.isNotEmpty(dto.getIdCard())){
            LambdaQueryWrapper<SaasParkPropertyPeopleInfo> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SaasParkPropertyPeopleInfo::getIdCard,dto.getIdCard());
            queryWrapper.ne(SaasParkPropertyPeopleInfo::getId,dto.getId());
            int one1 = this.count(queryWrapper);
            if (one1>0){
                throw new ServiceException("该证件号已存在物业人员信息中");
            }
        }
        Func.copy(dto,saasParkPropertyPeopleInfo);
        if (Func.isNotEmpty(AuthUtil.getUser())&&Func.isNotEmpty(AuthUtil.getUser().getOrgUserId())){
            saasParkPropertyPeopleInfo.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
        }

        boolean save = this.updateById(saasParkPropertyPeopleInfo);
        if (save){
            SaasParkPropertyPeopleInfoServiceImpl bean = SpringUtil.getBean(SaasParkPropertyPeopleInfoServiceImpl.class);
            bean.sysPropertyCustomerArchives(saasParkPropertyPeopleInfo);
        }
        return save;
    }

    @Override
    public NestPage<PropertyPeopleBuildingManagerPageVO> getPage(PropertyPeopleBuildManagerPageDTO dto) {
        ValidatorUtils.validateEntity(dto);
        IPage<SaasParkPropertyPeopleInfo> page = Condition.getPage(dto);
        IPage<PropertyPeopleBuildingManagerPageVO> iPage=this.baseMapper.getPage(page,dto);
        NestPage<PropertyPeopleBuildingManagerPageVO> nestPage = new NestPage<>();
        nestPage.setSize(dto.getSize());
        nestPage.setCurrent(dto.getCurrent());
        List<PropertyPeopleBuildingManagerPageVO> records = iPage.getRecords();
        nestPage.setRecords(records);
        if (Func.isEmpty(records)){
            return nestPage;
        }

        List<PropertyPeopleBuildingManagerPageVO> infoPageVOS = records.stream().map(e -> {
            PropertyPeopleBuildingManagerPageVO pageVO = new PropertyPeopleBuildingManagerPageVO();
            Func.copy(e, pageVO);
            if (Func.isNotEmpty(pageVO.getManagerBindBuildingId())){
                List<Long> buildingIdList = Func.toLongList(pageVO.getManagerBindBuildingId());
                 String buildingName=buildingsService.listByIds(buildingIdList).stream()
                         .map(PropertyBuildings::getBuildingName)
                         .filter(Func::isNotEmpty)
                         .collect(Collectors.joining(","));
                 pageVO.setManagerBindBuildingName(buildingName);
            }
            if (Func.isNotEmpty(pageVO.getEngineerBindBuildingId())){
                List<Long> buildingIdList = Func.toLongList(pageVO.getEngineerBindBuildingId());
                String buildingName=buildingsService.listByIds(buildingIdList).stream()
                        .map(PropertyBuildings::getBuildingName)
                        .filter(Func::isNotEmpty)
                        .collect(Collectors.joining(","));
                pageVO.setManagerBindBuildingName(buildingName);
            }
            return pageVO;
        }).collect(Collectors.toList());
        nestPage.setRecords(infoPageVOS);
        return nestPage;
    }

    @Override
    public Boolean buildingManagerAdd(PropertyPeopleBuildManagerAddDTO dto) {
        if (dto.getWorkType()==1){
            List<SaasParkPropertyPeopleInfo> propertyPeopleInfos = dto.getIdList().stream().map(e -> {
                SaasParkPropertyPeopleInfo peopleInfo = new SaasParkPropertyPeopleInfo();
                peopleInfo.setIsBuildingManager(1);
                return peopleInfo;
            }).collect(Collectors.toList());
           return this.updateBatchById(propertyPeopleInfos,propertyPeopleInfos.size());
        }
        if (dto.getWorkType()==2){
            List<SaasParkPropertyPeopleInfo> propertyPeopleInfos = dto.getIdList().stream().map(e -> {
                SaasParkPropertyPeopleInfo peopleInfo = new SaasParkPropertyPeopleInfo();
                peopleInfo.setIsBuildingEngineer(1);
                return peopleInfo;
            }).collect(Collectors.toList());
           return this.updateBatchById(propertyPeopleInfos,propertyPeopleInfos.size());
        }
        return false;
    }

    @Override
    public Boolean buildingManagerDelete(PropertyPeopleBuildManagerDeleteDTO dto) {
        SaasParkPropertyPeopleInfo peopleInfo = new SaasParkPropertyPeopleInfo();
        if (dto.getWorkType()==1){
            peopleInfo.setIsBuildingManager(1);
            return this.updateById(peopleInfo);
        }
        if (dto.getWorkType()==2){
                peopleInfo.setIsBuildingEngineer(1);
                return this.updateById(peopleInfo);
        }
        return false;
    }

    @Override
    public PropertyPeopleBuildingManagerWechatVO infoByBuildingId(Long buildingId) {
        PropertyBuildings propertyBuildings = buildingsService.getById(buildingId);
        if (Func.isEmpty(propertyBuildings)){
            throw new ServiceException("楼栋信息不存在！");
        }
        PropertyPeopleBuildingManagerWechatVO vo= this.baseMapper.getBuildingManagerInfoByBuildingId(buildingId);
        return vo;
    }

    @Async
    //todo 同步人员档案 后期需求
    public void sysPropertyCustomerArchives(SaasParkPropertyPeopleInfo 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.setBindStatus(peopleInfo.getBindStatus());
        createCustomerArchives.setBindAccount(String.valueOf(peopleInfo.getBindAccount()));
        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);

    }
}
