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


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuchen.saas.manage.system.api.entity.NestApplyManage;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.ISysClient;
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.property.EnterpriseUserSyncAddDto;
import com.yuchen.saas.park.api.dto.property.PropertyEnterpriseMemberSyncDto;
import com.yuchen.saas.park.api.entity.property.*;
import com.yuchen.saas.park.api.vo.property.PropertyEnterpriseUserSyncVo;
import com.yuchen.saas.park.service.mapper.property.PropertyEnterpriseUserSyncMapper;
import com.yuchen.saas.park.service.service.property.*;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
;

/**
 * <p>
 * 物业同步组织成员记录表 服务实现类
 * </p>
 *
 * @author cxj
 * @since 2024-01-04
 */
@Service
public class PropertyEnterpriseUserSyncServiceImpl extends BaseServiceImpl<PropertyEnterpriseUserSyncMapper, PropertyEnterpriseUserSync> implements IPropertyEnterpriseUserSyncService {

    @Resource
    private ISysClient iSysClient;

    @Resource
    private IPropertyEnterpriseAddressService iPropertyEnterpriseAddressService;

    @Resource
    private PropertyHousesService propertyHousesService;

    @Resource
    private PropertyBuildingsService propertyBuildingsService;

    @Resource
    private IUserClient iUserClient;

    @Resource
    private IPropertyEnterpriseMemberService iPropertyEnterpriseMemberService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(EnterpriseUserSyncAddDto param) {
        PropertyEnterpriseAddress enterpriseAddress = iPropertyEnterpriseAddressService.getById(param.getEnterpriseAddressId());
        if(Func.isEmpty(enterpriseAddress)){
            throw new ServiceException("所选物业企业入驻地址已经不存在!");
        }
        if(Func.isNotEmpty(enterpriseAddress.getIsValid())&&enterpriseAddress.getIsValid()==1){
            throw new ServiceException("所选物业企业入驻地址已失效!");
        }
        LambdaQueryWrapper<PropertyEnterpriseUserSync> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PropertyEnterpriseUserSync::getDeptId,enterpriseAddress.getDeptId())
                .eq(PropertyEnterpriseUserSync::getEnterpriseAddressId,enterpriseAddress.getId());
        List<PropertyEnterpriseUserSync> oldList = list(queryWrapper);
        if(Func.isNotEmpty(oldList)){
            deleteLogic(oldList.stream().map(a->a.getId()).collect(Collectors.toList()));
        }
        //旧的删除掉,重新同步
        for (PropertyEnterpriseUserSync item:oldList) {
            PropertyEnterpriseMember oldEnterpriseMember = iPropertyEnterpriseMemberService.getById(item.getEnterpriseMemberId());
            if(Func.isNotEmpty(oldEnterpriseMember)){
                iPropertyEnterpriseMemberService.deleteEnterpriseMember(oldEnterpriseMember.getId());
            }
        }

        R<List<NestOrgUser>> listR = iSysClient.orgUserListByIds(param.getOrgUserIds());
        if(listR.isSuccess()&&Func.isNotEmpty(listR.getData())){
            for (NestOrgUser item:listR.getData()) {
                if(!Func.equalsSafe(enterpriseAddress.getDeptId(),item.getDeptId())){
                    throw new ServiceException("组织成员参数错误!");
                }
                Long enterpriseMemberId =saveMember( enterpriseAddress, item);
                PropertyEnterpriseUserSync enterpriseUserSync=new PropertyEnterpriseUserSync();
                enterpriseUserSync.setEnterpriseAddressId(enterpriseAddress.getId());
                enterpriseUserSync.setParkId(enterpriseAddress.getParkId());
                enterpriseUserSync.setDeptId(enterpriseAddress.getDeptId());
                enterpriseUserSync.setOrgUserId(item.getId());
                enterpriseUserSync.setUserId(item.getUserId());
                enterpriseUserSync.setEnterpriseMemberId(enterpriseMemberId);
                save(enterpriseUserSync);
            }
        }
        return true;
    }

    @Override
    public List<PropertyEnterpriseUserSyncVo> getByAddressId(Long enterpriseAddressId) {
        PropertyEnterpriseAddress enterpriseAddress = iPropertyEnterpriseAddressService.getById(enterpriseAddressId);
        if(Func.isEmpty(enterpriseAddress)){
            return Collections.emptyList();
        }
        LambdaQueryWrapper<PropertyEnterpriseUserSync> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PropertyEnterpriseUserSync::getDeptId,enterpriseAddress.getDeptId())
                .eq(PropertyEnterpriseUserSync::getEnterpriseAddressId,enterpriseAddress.getId());
        List<PropertyEnterpriseUserSync> oldList = list(queryWrapper);
        if(Func.isEmpty(oldList)){
            return Collections.emptyList();
        }
        List<Long> orgUserIds = oldList.stream().map(a -> a.getOrgUserId()).collect(Collectors.toList());
        R<List<NestOrgUser>> listR = iSysClient.orgUserListByIds(orgUserIds);
        Map<Long,String> orgUserNameMap=null;
        if(listR.isSuccess()&&Func.isNotEmpty(listR.getData())){
            orgUserNameMap=listR.getData().stream().collect(Collectors.toMap(NestOrgUser::getId, NestOrgUser::getName,
                    (v1, v2) -> v2));
        }
        Map<Long, String> finalOrgUserNameMap = orgUserNameMap;
        return oldList.stream().map(a->{
            PropertyEnterpriseUserSyncVo vo=new PropertyEnterpriseUserSyncVo();
            vo.setOrgUserIds(a.getOrgUserId());
            if(Func.isNotEmpty(finalOrgUserNameMap)&&finalOrgUserNameMap.containsKey(a.getOrgUserId())){
                vo.setName(finalOrgUserNameMap.get(a.getOrgUserId()));
            }
            PropertyEnterpriseMember enterpriseMember = iPropertyEnterpriseMemberService.getById(a.getEnterpriseMemberId());
            if(Func.isNotEmpty(enterpriseMember)){
                vo.setMemberStatus(enterpriseMember.getMemberStatus());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    private Long saveMember(PropertyEnterpriseAddress enterpriseAddress,NestOrgUser item){
        PropertyEnterpriseMemberSyncDto syncDto=new PropertyEnterpriseMemberSyncDto();
        syncDto.setParkId(enterpriseAddress.getParkId());
        syncDto.setEnterpriseId(enterpriseAddress.getLinkId());
        PropertyHouses houses = propertyHousesService.getById(enterpriseAddress.getHouseId());
        if(Func.isNotEmpty(houses)){
            PropertyBuildings propertyBuildings = propertyBuildingsService.getById(houses.getBuildingId());
            if(Func.isNotEmpty(propertyBuildings)){
                syncDto.setAddress(propertyBuildings.getBuildingName()+houses.getHouseName());
            }else {
                syncDto.setAddress(houses.getHouseName());
            }
        }
        syncDto.setUserName(item.getName());
        R<User> userR = iUserClient.userInfoById(item.getUserId());
        if(userR.isSuccess()&&Func.isNotEmpty(userR.getData())){
            syncDto.setLinkPhone(userR.getData().getPhone());
        }
        return iPropertyEnterpriseMemberService.syncEnterpriseMember(syncDto);
    }
}
