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(), false);
        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, true);
        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);
            GridRegion gridRegion = gridRegionMapper.getWgLevel(k);
            if (Objects.nonNull(gridRegion)) {
                houseResourceProfileGraph.setWgName(gridRegion.getWgName());
                if (Objects.nonNull(gridRegion.getJzArea())) {
                    houseResourceProfileGraph.setJzArea(new BigDecimal(gridRegion.getJzArea()));
                }
                if (Objects.nonNull(gridRegion.getPosition())) {
                    houseResourceProfileGraph.setPosition(gridRegion.getPosition());
                }
            }
            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, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList()));
            resourceProfileGraphList.add(houseResourceProfileGraph);
        });
        return resourceProfileGraphList.stream().sorted(Comparator.comparing(HouseResourceProfileGraph::getPosition, Comparator.nullsLast(Integer::compareTo))).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());
                houseResourceProfileGraph.setPosition(gridRegion.getPosition());
                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);
                    if (StringUtils.hasText(query.getFourOrHouseNumber())) {
                        result = result.stream().filter(x -> StringUtils.hasText(x.getWgName())).filter(x -> x.getWgName().contains(query.getFourOrHouseNumber())).collect(Collectors.toList());
                    }
                } else {
                    List<HouseResourcePage> pageList = new ArrayList<>();
                    for (HouseResource houseResource : collect) {
                        HouseResourcePage houseResourcePage = new HouseResourcePage();
                        BeanUtils.copyProperties(houseResource, houseResourcePage);
                        pageList.add(houseResourcePage);
                    }
                    if (StringUtils.hasText(query.getFourOrHouseNumber())) {
                        pageList = pageList.stream().filter(x -> StringUtils.hasText(x.getHouseNumber())).filter(x -> x.getHouseNumber().contains(query.getFourOrHouseNumber()) || x.getFour().contains(query.getFourOrHouseNumber())).collect(Collectors.toList());
                    }
                    if (!CollectionUtils.isEmpty(pageList)) {
                        houseResourceProfileGraph.setHouseResources(handleHouseList(pageList, true));
                        result.add(houseResourceProfileGraph);
                    }
                }
            }
            return result.stream().sorted(Comparator.comparing(HouseResourceProfileGraph::getPosition, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        }
        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, true);
        }
    }

    @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, true);
        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.setSjJdCount(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.setSbCount(list.stream().filter(x -> x.getHouseResourceType() == 3).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());

        Map<String, BigDecimal> industrySellMap = Arrays.asList("工业", "建筑业", "批发", "零售", "住宿", "餐饮", "服务业", "其他")
                .parallelStream()
                .collect(Collectors.toMap(industry -> industry, industry -> getIndustrySellCount(businessEntityInfos, industry, businessEntitySellMapper)));

        businessEntityStatisticsDetail.setGyCount(industrySellMap.getOrDefault("工业", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setJzyCount(industrySellMap.getOrDefault("建筑业", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setPfCount(industrySellMap.getOrDefault("批发", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setLsCount(industrySellMap.getOrDefault("零售", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setZsCount(industrySellMap.getOrDefault("住宿", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setCyCount(industrySellMap.getOrDefault("餐饮", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setFwyCount(industrySellMap.getOrDefault("服务业", BigDecimal.ZERO));
        businessEntityStatisticsDetail.setQtjjfzCount(industrySellMap.getOrDefault("其他", BigDecimal.ZERO));

        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;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveYearTax(YearTaxSaveUpdateDto dto) {
        if (Objects.nonNull(dto.getId())) {
            BusinessEntitySell existingSell = businessEntitySellMapper.selectBusinessEntitySellById(dto.getId());
            if (existingSell == null) {
                throw new RuntimeException("未找到对应的记录");
            }
            BeanUtils.copyProperties(dto, existingSell);
            businessEntitySellMapper.updateBusinessEntitySell(existingSell);
        } else {
            BusinessEntitySell businessEntitySell = new BusinessEntitySell();
            BeanUtils.copyProperties(dto, businessEntitySell);
            businessEntitySell.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            businessEntitySellMapper.insertBusinessEntitySell(businessEntitySell);
        }
    }

    private List<HouseResourcePage> handleHouseList(List<HouseResourcePage> list, boolean houseNumberSortFlag) {
        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()));
            }
        });
        if (houseNumberSortFlag) {
            return list.stream().sorted(Comparator.comparing(HouseResourcePage::getHouseNumber, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
        } else {
            return list;
        }
    }

    private BigDecimal getIndustrySellCount(List<BusinessEntityInfo> infos, String industry, BusinessEntitySellMapper sellMapper) {
        List<String> ids = infos.stream()
                .filter(x -> StringUtils.hasText(x.getIndustryClassification()) && x.getIndustryClassification().equals(industry))
                .map(BusinessEntityInfo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return BigDecimal.ZERO;
        }
        List<BusinessEntitySell> sells = sellMapper.selectBusinessEntitySellByEntityIds(ids);
        if (CollectionUtils.isEmpty(sells)) {
            return BigDecimal.ZERO;
        }
        return sells.stream().map(BusinessEntitySell::getYearSell).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
