package com.ruoyi.system.service.house.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.grid.GridRegionUserExample;
import com.ruoyi.system.domain.house.BusinessEntityInfo;
import com.ruoyi.system.domain.house.BusinessEntitySell;
import com.ruoyi.system.domain.house.HouseResource;
import com.ruoyi.system.domain.house.enums.HouseEnums;
import com.ruoyi.system.domain.house.vo.*;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.mapper.grid.GridRegionUserMapper;
import com.ruoyi.system.mapper.house.BusinessEntityInfoMapper;
import com.ruoyi.system.mapper.house.BusinessEntitySellMapper;
import com.ruoyi.system.mapper.house.HouseResourceMapper;
import com.ruoyi.system.service.house.HouseResourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HouseResourceServiceImpl implements HouseResourceService {

    private final HouseResourceMapper houseResourceMapper;

    private final BusinessEntityInfoMapper businessEntityInfoMapper;

    private final BusinessEntitySellMapper businessEntitySellMapper;

    private final GridRegionMapper gridRegionMapper;

    private final GridRegionUserMapper gridRegionUserMapper;

    public HouseResourceServiceImpl(HouseResourceMapper houseResourceMapper, BusinessEntityInfoMapper businessEntityInfoMapper, BusinessEntitySellMapper businessEntitySellMapper, GridRegionMapper gridRegionMapper, GridRegionUserMapper gridRegionUserMapper) {
        this.houseResourceMapper = houseResourceMapper;
        this.businessEntityInfoMapper = businessEntityInfoMapper;
        this.businessEntitySellMapper = businessEntitySellMapper;
        this.gridRegionMapper = gridRegionMapper;
        this.gridRegionUserMapper = gridRegionUserMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveHouseResource(HouseResourceSaveUpdateDto dto) {
        String houseResourceId = UUID.randomUUID().toString().replaceAll("-", "");
        dto.getHouseResource().setId(houseResourceId);
        houseResourceMapper.insertHouseResource(dto.getHouseResource());

        for (BusinessEntityDto businessEntityDto : dto.getBusinessEntityDtoList()) {
            BusinessEntityInfo businessEntityInfo = new BusinessEntityInfo();
            BeanUtils.copyProperties(businessEntityDto, businessEntityInfo);
            String businessEntityInfoId = UUID.randomUUID().toString().replaceAll("-", "");
            businessEntityInfo.setId(businessEntityInfoId);
            businessEntityInfo.setHouseResourceId(houseResourceId);
            businessEntityInfoMapper.insertBusinessEntityInfo(businessEntityInfo);

            for (BusinessEntitySell businessEntitySell : businessEntityDto.getBusinessEntitySells()) {
                businessEntitySell.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                businessEntitySell.setBusinessEntityInfoId(businessEntityInfoId);
                businessEntitySellMapper.insertBusinessEntitySell(businessEntitySell);
            }
        }
    }

    @Override
    public HouseResourceDetail queryHouseResourceById(String id) {
        HouseResource houseResource = houseResourceMapper.selectHouseResourceById(id);
        if (houseResource == null) {
            return null;
        }
        HouseResourceDetail houseResourceDetail = new HouseResourceDetail();
        BeanUtils.copyProperties(houseResource, houseResourceDetail);
        GridRegionExample gridRegionExample = new GridRegionExample();
        gridRegionExample.createCriteria().andWgCodeEqualTo(houseResourceDetail.getTwo()).andWgTypeEqualTo(String.valueOf(houseResourceDetail.getType()));
        List<GridRegion> two = gridRegionMapper.selectByExample(gridRegionExample);
        if (!two.isEmpty()) {
            houseResourceDetail.setWgName2(two.get(0).getWgName());
        }
        GridRegionExample gridRegionExampleThree = new GridRegionExample();
        gridRegionExampleThree.createCriteria().andWgCodeEqualTo(houseResourceDetail.getThree()).andWgTypeEqualTo(String.valueOf(houseResourceDetail.getType()));
        List<GridRegion> three = gridRegionMapper.selectByExample(gridRegionExampleThree);
        if (!three.isEmpty()) {
            houseResourceDetail.setWgName3(three.get(0).getWgName());
        }
        if (StringUtils.hasText(houseResourceDetail.getHouseResourceUrl())) {
            houseResourceDetail.setHouseResourceUrlList(Arrays.asList(houseResourceDetail.getHouseResourceUrl().split(",")));
        }
        if (StringUtils.hasText(houseResourceDetail.getBusinessLicenseUrl())) {
            houseResourceDetail.setBusinessLicenseUrlList(Arrays.asList(houseResourceDetail.getBusinessLicenseUrl().split(",")));
        }
        houseResourceDetail.setHouseResourceAttributeText(HouseEnums.HouseResourceAttributeEnum.getDescByCode(houseResourceDetail.getHouseResourceAttribute()));
        houseResourceDetail.setHouseResourceTypeText(HouseEnums.HouseResourceTypeEnum.getDescByCode(houseResourceDetail.getHouseResourceType()));
        houseResourceDetail.setOrientationText(HouseEnums.OrientationEnum.getDescByCode(houseResourceDetail.getOrientation()));
        houseResourceDetail.setDecorationConditionText(HouseEnums.DecorationConditionEnum.getDescByCode(houseResourceDetail.getDecorationCondition()));
        houseResourceDetail.setRentalUnitText(HouseEnums.RentalUnitEnum.getDescByCode(houseResourceDetail.getRentalUnit()));
        houseResourceDetail.setHireStatusText(HouseEnums.hireStatusTextEnum.getDescByCode(houseResourceDetail.getHireStatus()));

        List<BusinessEntityInfo> businessEntityInfos = businessEntityInfoMapper.selectAllBusinessEntityInfosByHouseResourceId(houseResourceDetail.getId());
        List<BusinessEntityDto> businessEntityDtoList = new ArrayList<>();
        for (BusinessEntityInfo businessEntityInfo : businessEntityInfos) {
            BusinessEntityDto businessEntityDto = new BusinessEntityDto();
            BeanUtils.copyProperties(businessEntityInfo, businessEntityDto);
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityId(businessEntityInfo.getId());
            businessEntityDto.setBusinessEntitySells(businessEntitySells);
            businessEntityDtoList.add(businessEntityDto);
        }
        houseResourceDetail.setBusinessEntityDtoList(businessEntityDtoList);
        return houseResourceDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateHouseResource(HouseResourceSaveUpdateDto dto) {
        if (Objects.isNull(dto.getHouseResource().getId())) {
            throw new RuntimeException("房源id不能为空");
        }
        houseResourceMapper.updateHouseResource(dto.getHouseResource());

        businessEntityInfoMapper.deleteByHouseResourceId(dto.getHouseResource().getId());
        for (String s : dto.getBusinessEntityDtoList().stream().map(BusinessEntityDto::getId).collect(Collectors.toList())) {
            businessEntitySellMapper.deleteBusinessEntitySellById(s);
        }
        for (BusinessEntityDto businessEntityDto : dto.getBusinessEntityDtoList()) {
            BusinessEntityInfo businessEntityInfo = new BusinessEntityInfo();
            BeanUtils.copyProperties(businessEntityDto, businessEntityInfo);
            String businessEntityInfoId = UUID.randomUUID().toString().replaceAll("-", "");
            businessEntityInfo.setId(businessEntityInfoId);
            businessEntityInfo.setHouseResourceId(dto.getHouseResource().getId());
            businessEntityInfoMapper.insertBusinessEntityInfo(businessEntityInfo);

            for (BusinessEntitySell businessEntitySell : businessEntityDto.getBusinessEntitySells()) {
                businessEntitySell.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                businessEntitySell.setBusinessEntityInfoId(businessEntityInfoId);
                businessEntitySellMapper.insertBusinessEntitySell(businessEntitySell);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHouseResourceById(String id) {
        houseResourceMapper.deleteHouseResourceById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveHouseResources(List<HouseResource> houseResources) {
        houseResourceMapper.batchInsertHouseResources(houseResources);
    }

    @Override
    public IPage<HouseResourcePage> pageHouseResources(HouseResourcePageQuery query) {
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andUserIdEqualTo(userId);
        List<GridRegionUser> gridRegionUsers = gridRegionUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(gridRegionUsers) && !SecurityUtils.getLoginUser().getUser().isAdmin()) {
            query.setWgCodes(gridRegionUsers.stream().map(GridRegionUser::getWgId).collect(Collectors.toList()));
        }
        IPage<HouseResourcePage> page = houseResourceMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), query);
        List<HouseResourcePage> records = handleHouseList(page.getRecords());
        page.setRecords(records);
        return page;
    }

    @Override
    public List<HouseResourceProfileGraph> profileGraphHouseResources(HouseResourcePageQuery query) {
        List<HouseResourcePage> list = houseResourceMapper.selectProfileGraph(query);
        list.forEach(x -> x.setIncome(businessEntityInfoMapper.selectYearSellByHouseResourceId(x.getId())));
        List<HouseResourcePage> houseResourcePages = handleHouseList(list);
        if (StringUtils.hasText(query.getName())) {
            houseResourcePages = houseResourcePages.stream().filter(x -> !CollectionUtils.isEmpty(x.getBusinessEntityInfoNames())).filter(x -> x.getBusinessEntityInfoNames().contains(query.getName())).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getHouseAreaMin())) {
            houseResourcePages = houseResourcePages.stream().filter(x -> Objects.nonNull(x.getHouseArea())).filter(x -> x.getHouseArea().compareTo(query.getHouseAreaMin()) >= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getHouseAreaMax())) {
            houseResourcePages = houseResourcePages.stream().filter(x -> Objects.nonNull(x.getHouseArea())).filter(x -> x.getHouseArea().compareTo(query.getHouseAreaMax()) <= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getYearSellMin())) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getIncome().compareTo(query.getYearSellMin()) >= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getYearSellMax())) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getIncome().compareTo(query.getYearSellMax()) <= 0).collect(Collectors.toList());
        }
        if (query.isZlFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceAttribute() == 0).collect(Collectors.toList());
        }
        if (query.isZyFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceAttribute() == 2).collect(Collectors.toList());
        }
        if (query.isQtFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceAttribute() == 1).collect(Collectors.toList());
        }
        if (query.isZaiyingFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceType() == 0).collect(Collectors.toList());
        }
        if (query.isXzFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceType() == 1).collect(Collectors.toList());
        }
        if (query.isGkFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceType() == 2).collect(Collectors.toList());
        }
        if (query.isZyzyFlag()) {
            houseResourcePages = houseResourcePages.stream().filter(x -> x.getHouseResourceType() == 4).collect(Collectors.toList());
        }
        List<HouseResourceProfileGraph> resourceProfileGraphList = new ArrayList<>();
        Map<String, List<HouseResourcePage>> collect = houseResourcePages.stream().collect(Collectors.groupingBy(HouseResourcePage::getFour));
        collect.forEach((k, v) -> {
            HouseResourceProfileGraph houseResourceProfileGraph = new HouseResourceProfileGraph();
            houseResourceProfileGraph.setId(k);
            String wgName = gridRegionMapper.getWgNameByCode(k);
            if (StringUtils.hasText(wgName)) {
                houseResourceProfileGraph.setWgName(wgName);
            }
            String jzAreaByCode = gridRegionMapper.getJzAreaByCode(k);
            if (StringUtils.hasText(jzAreaByCode)) {
                houseResourceProfileGraph.setJzArea(new BigDecimal(jzAreaByCode));
            }
            houseResourceProfileGraph.setJyArea(v.stream().map(HouseResourcePage::getHouseArea).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            houseResourceProfileGraph.setKzCount(v.stream().filter(x -> x.getHouseResourceType() == HouseEnums.HouseResourceTypeEnum.KZ.getCode()).count());
            houseResourceProfileGraph.setKzArea(v.stream().filter(x -> x.getHouseResourceType() == HouseEnums.HouseResourceTypeEnum.KZ.getCode()).map(HouseResourcePage::getHouseArea).reduce(BigDecimal.ZERO, BigDecimal::add));
            houseResourceProfileGraph.setAreaTotal(v.stream().map(HouseResourcePage::getHouseArea).reduce(BigDecimal.ZERO, BigDecimal::add));
            houseResourceProfileGraph.setHouseResources(v.stream().sorted(Comparator.comparing(HouseResourcePage::getHouseNumber)).collect(Collectors.toList()));
            resourceProfileGraphList.add(houseResourceProfileGraph);
        });
        return resourceProfileGraphList.stream().sorted(Comparator.comparing(HouseResourceProfileGraph::getId)).collect(Collectors.toList());
    }

    @Override
    public List<HouseResourceProfileGraph> appProfileGraphHouseResources(HouseResourcePageQuery query) {
        GridRegionExample gridRegionExample = new GridRegionExample();
        gridRegionExample.createCriteria().andWgParentIdEqualTo(query.getThree()).andLevelEqualTo("4");
        List<GridRegion> fourList = gridRegionMapper.selectByExample(gridRegionExample);
        if (!CollectionUtils.isEmpty(fourList)) {
            List<HouseResourceProfileGraph> result = new ArrayList<>();
            List<HouseResource> houseResources = houseResourceMapper.selectAll();
            for (GridRegion gridRegion : fourList) {
                HouseResourceProfileGraph houseResourceProfileGraph = new HouseResourceProfileGraph();
                houseResourceProfileGraph.setId(gridRegion.getWgCode());
                houseResourceProfileGraph.setWgName(gridRegion.getWgName());
                List<HouseResource> collect = houseResources.stream().filter(x -> x.getFour().equals(gridRegion.getWgCode())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    houseResourceProfileGraph.setHouseResources(Collections.emptyList());
                    result.add(houseResourceProfileGraph);
                } else {
                    List<HouseResourcePage> pageList = new ArrayList<>();
                    for (HouseResource houseResource : collect) {
                        HouseResourcePage houseResourcePage = new HouseResourcePage();
                        BeanUtils.copyProperties(houseResource, houseResourcePage);
                        pageList.add(houseResourcePage);
                    }
                    houseResourceProfileGraph.setHouseResources(handleHouseList(pageList));
                    result.add(houseResourceProfileGraph);
                }
            }
            return result;
        }
        return Collections.emptyList();
    }

    @Override
    public List<HouseResourcePage> listHouseResources(HouseResourcePageQuery query) {
        List<HouseResourcePage> list = houseResourceMapper.selectList(query);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        } else {
            return handleHouseList(list);
        }
    }

    @Override
    public BusinessEntityStatisticsDetail businessEntityStatistics(HouseResourcePageQuery query) {
        List<HouseResourcePage> listPages = houseResourceMapper.selectProfileGraph(query);
        listPages.forEach(x -> x.setIncome(businessEntityInfoMapper.selectYearSellByHouseResourceId(x.getId())));
        if (CollectionUtils.isEmpty(listPages)) {
            return new BusinessEntityStatisticsDetail();
        }
        List<HouseResourcePage> list = handleHouseList(listPages);
        BusinessEntityStatisticsDetail businessEntityStatisticsDetail = new BusinessEntityStatisticsDetail();
        if (StringUtils.hasText(query.getTwo())) {
            list = list.stream().filter(x -> x.getTwo().equals(query.getTwo())).collect(Collectors.toList());
        }
        if (StringUtils.hasText(query.getThree())) {
            list = list.stream().filter(x -> x.getThree().equals(query.getThree())).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(list)) {
            return businessEntityStatisticsDetail;
        }
        if (StringUtils.hasText(query.getName())) {
            list = list.stream().filter(x -> !CollectionUtils.isEmpty(x.getBusinessEntityInfoNames())).filter(x -> x.getBusinessEntityInfoNames().contains(query.getName())).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getHouseAreaMin())) {
            list = list.stream().filter(x -> Objects.nonNull(x.getHouseArea())).filter(x -> x.getHouseArea().compareTo(query.getHouseAreaMin()) >= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getHouseAreaMax())) {
            list = list.stream().filter(x -> Objects.nonNull(x.getHouseArea())).filter(x -> x.getHouseArea().compareTo(query.getHouseAreaMax()) <= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getYearSellMin())) {
            list = list.stream().filter(x -> x.getIncome().compareTo(query.getYearSellMin()) >= 0).collect(Collectors.toList());
        }
        if (Objects.nonNull(query.getYearSellMax())) {
            list = list.stream().filter(x -> x.getIncome().compareTo(query.getYearSellMax()) <= 0).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(list)) {
            return businessEntityStatisticsDetail;
        }
        businessEntityStatisticsDetail.setLyCount(list.stream().filter(x -> x.getType() == 1).count());
        businessEntityStatisticsDetail.setJdCount(list.stream().filter(x -> x.getType() == 4).count());
        businessEntityStatisticsDetail.setJqCount(list.stream().filter(x -> x.getType() == 5).count());
        businessEntityStatisticsDetail.setZhtCount(list.stream().filter(x -> x.getType() == 6).count());
        businessEntityStatisticsDetail.setScCount(list.stream().filter(x -> x.getType() == 7).count());

        businessEntityStatisticsDetail.setSjLyCount(list.stream().filter(x -> x.getType() == 1).collect(Collectors.groupingBy(HouseResourcePage::getThree)).size());
        businessEntityStatisticsDetail.setSjJqCount(list.stream().filter(x -> x.getType() == 4).collect(Collectors.groupingBy(HouseResourcePage::getThree)).size());
        businessEntityStatisticsDetail.setSjJqCount(list.stream().filter(x -> x.getType() == 5).collect(Collectors.groupingBy(HouseResourcePage::getThree)).size());
        businessEntityStatisticsDetail.setSjZhtCount(list.stream().filter(x -> x.getType() == 6).collect(Collectors.groupingBy(HouseResourcePage::getThree)).size());
        businessEntityStatisticsDetail.setSjScCount(list.stream().filter(x -> x.getType() == 7).collect(Collectors.groupingBy(HouseResourcePage::getThree)).size());

        businessEntityStatisticsDetail.setZlCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 0).count());
        businessEntityStatisticsDetail.setZyCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 2).count());
        businessEntityStatisticsDetail.setQtCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 1).count());

        businessEntityStatisticsDetail.setZaiyingCount(list.stream().filter(x -> x.getHouseResourceType() == 0).count());
        businessEntityStatisticsDetail.setXzCount(list.stream().filter(x -> x.getHouseResourceType() == 1).count());
        businessEntityStatisticsDetail.setGkCount(list.stream().filter(x -> x.getHouseResourceType() == 2).count());
        businessEntityStatisticsDetail.setZyzyCount(list.stream().filter(x -> x.getHouseResourceType() == 4).count());

        List<String> houseResourceIds = list.stream().map(HouseResourcePage::getId).collect(Collectors.toList());
        List<BusinessEntityInfo> businessEntityInfos = businessEntityInfoMapper.selectAllBusinessEntityInfosByHouseResourceIds(houseResourceIds);
        if (CollectionUtils.isEmpty(businessEntityInfos)) {
            return businessEntityStatisticsDetail;
        }
        businessEntityStatisticsDetail.setZtCount(businessEntityInfos.size());

        List<String> gyIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("工业")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(gyIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(gyIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setGyCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> jzyIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("建筑业")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(jzyIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(jzyIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setJzyCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> pfIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("批发")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(pfIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(pfIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setPfCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> lsIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("零售")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(lsIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(lsIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setLsCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> zsIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("住宿")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(zsIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(zsIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setZsCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> cyIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("餐饮")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(cyIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(cyIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setCyCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> fwyIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("服务业")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(fwyIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(fwyIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setFwyCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }

        List<String> qtIds = businessEntityInfos.stream().filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals("其他")).map(BusinessEntityInfo::getId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(qtIds)) {
            List<BusinessEntitySell> businessEntitySells = businessEntitySellMapper.selectBusinessEntitySellByEntityIds(qtIds);
            if (!CollectionUtils.isEmpty(businessEntitySells)) {
                businessEntityStatisticsDetail.setQtjjfzCount(businessEntitySells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
        }
        businessEntityStatisticsDetail.setJjzl(businessEntityStatisticsDetail.getGyCount()
                .add(businessEntityStatisticsDetail.getJzyCount())
                .add(businessEntityStatisticsDetail.getPfCount())
                .add(businessEntityStatisticsDetail.getLsCount())
                .add(businessEntityStatisticsDetail.getZsCount())
                .add(businessEntityStatisticsDetail.getCyCount())
                .add(businessEntityStatisticsDetail.getFwyCount())
                .add(businessEntityStatisticsDetail.getQtjjfzCount()));
        return businessEntityStatisticsDetail;
    }

    @Override
    public PageBusinessEntityStatisticsDetail pageBusinessEntityStatistics(PageBusinessEntityStatisticsQuery query) {
        List<HouseResource> list = houseResourceMapper.selectPageBusinessEntityStatistics();
        if (CollectionUtils.isEmpty(list)) {
            return new PageBusinessEntityStatisticsDetail();
        }
        List<HouseResource> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(query.getTwos())) {
            for (String two : query.getTwos()) {
                for (HouseResource houseResource : list) {
                    if (two.equals(houseResource.getTwo())) {
                        result.add(houseResource);
                    }
                }
            }
        } else {
            String userId = SecurityUtils.getLoginUser().getUser().getUserId();
            GridRegionUserExample example = new GridRegionUserExample();
            GridRegionUserExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            criteria.andUserIdEqualTo(userId);
            List<GridRegionUser> gridRegionUsers = gridRegionUserMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(gridRegionUsers) && !SecurityUtils.getLoginUser().getUser().isAdmin()) {
                List<String> twos = gridRegionUsers.stream().map(GridRegionUser::getWgId).collect(Collectors.toList());
                for (String two : twos) {
                    for (HouseResource houseResource : list) {
                        if (two.equals(houseResource.getTwo())) {
                            result.add(houseResource);
                        }
                    }
                }
            } else {
                result = list;
            }
        }
        if (CollectionUtils.isEmpty(result)) {
            return new PageBusinessEntityStatisticsDetail();
        }
        PageBusinessEntityStatisticsDetail pageBusinessEntityStatisticsDetail = new PageBusinessEntityStatisticsDetail();
        pageBusinessEntityStatisticsDetail.setLyCount(result.stream().filter(x -> x.getType() == 1).count());
        pageBusinessEntityStatisticsDetail.setDlCount(result.stream().filter(x -> x.getType() == 4).count());
        pageBusinessEntityStatisticsDetail.setJqCount(result.stream().filter(x -> x.getType() == 5).count());
        pageBusinessEntityStatisticsDetail.setZhtCount(result.stream().filter(x -> x.getType() == 6).count());
        pageBusinessEntityStatisticsDetail.setScCount(result.stream().filter(x -> x.getType() == 7).count());
        pageBusinessEntityStatisticsDetail.setTotalCount(result.size());

        pageBusinessEntityStatisticsDetail.setSjLyCount(result.stream().filter(x -> x.getType() == 1).collect(Collectors.groupingBy(HouseResource::getThree)).size());
        pageBusinessEntityStatisticsDetail.setSjDlCount(result.stream().filter(x -> x.getType() == 4).collect(Collectors.groupingBy(HouseResource::getThree)).size());
        pageBusinessEntityStatisticsDetail.setSjJqCount(result.stream().filter(x -> x.getType() == 5).collect(Collectors.groupingBy(HouseResource::getThree)).size());
        pageBusinessEntityStatisticsDetail.setSjZhtCount(result.stream().filter(x -> x.getType() == 6).collect(Collectors.groupingBy(HouseResource::getThree)).size());
        pageBusinessEntityStatisticsDetail.setSjScCount(result.stream().filter(x -> x.getType() == 7).collect(Collectors.groupingBy(HouseResource::getThree)).size());
        pageBusinessEntityStatisticsDetail.setSjTotalCount(result.stream().collect(Collectors.groupingBy(HouseResource::getThree)).size());
        return pageBusinessEntityStatisticsDetail;
    }

    private List<HouseResourcePage> handleHouseList(List<HouseResourcePage> list) {
        list.forEach(x -> {
            GridRegionExample twoExample = new GridRegionExample();
            twoExample.createCriteria().andWgTypeEqualTo(String.valueOf(x.getType())).andWgCodeEqualTo(x.getTwo());
            List<GridRegion> two = gridRegionMapper.selectByExample(twoExample);
            if (!CollectionUtils.isEmpty(two)) {
                x.setWgName2(two.get(0).getWgName());
            }
            GridRegionExample threeExample = new GridRegionExample();
            threeExample.createCriteria().andWgTypeEqualTo(String.valueOf(x.getType())).andWgCodeEqualTo(x.getThree());
            List<GridRegion> three = gridRegionMapper.selectByExample(threeExample);
            if (!CollectionUtils.isEmpty(three)) {
                x.setWgName3(three.get(0).getWgName());
            }
            x.setHouseResourceAttributeText(HouseEnums.HouseResourceAttributeEnum.getDescByCode(x.getHouseResourceAttribute()));
            x.setHouseResourceTypeText(HouseEnums.HouseResourceTypeEnum.getDescByCode(x.getHouseResourceType()));
            x.setOrientationText(HouseEnums.OrientationEnum.getDescByCode(x.getOrientation()));
            x.setDecorationConditionText(HouseEnums.DecorationConditionEnum.getDescByCode(x.getDecorationCondition()));
            x.setRentalUnitText(HouseEnums.RentalUnitEnum.getDescByCode(x.getRentalUnit()));
            x.setHireStatusText(HouseEnums.hireStatusTextEnum.getDescByCode(x.getHireStatus()));
            List<BusinessEntityInfo> businessEntityInfos = businessEntityInfoMapper.selectAllBusinessEntityInfosByHouseResourceId(x.getId());
            if (!CollectionUtils.isEmpty(businessEntityInfos)) {
                x.setBusinessEntityInfoNames(businessEntityInfos.stream().map(BusinessEntityInfo::getName).collect(Collectors.toList()));
            }
        });
        return list;
    }
}
