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.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
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.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;

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

    @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(",")));
        }
        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) {
        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<HouseResourceProfileGraph> resourceProfileGraphList = new ArrayList<>();
        Map<String, List<HouseResourcePage>> collect = list.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);
            }
            List<HouseResourcePage> houseResourcePages = handleHouseList(v);
            houseResourceProfileGraph.setHouseResources(houseResourcePages.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<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(String two) {
        List<HouseResource> list = houseResourceMapper.selectAll();
        if (CollectionUtils.isEmpty(list)) {
            return new BusinessEntityStatisticsDetail();
        }
        BusinessEntityStatisticsDetail businessEntityStatisticsDetail = new BusinessEntityStatisticsDetail();
        if (StringUtils.hasText(two)) {
            list = list.stream().filter(x -> x.getTwo().equals(two)).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.setZlCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 0).count());
        businessEntityStatisticsDetail.setZyCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 1).count());
        businessEntityStatisticsDetail.setQtCount(list.stream().filter(x -> x.getHouseResourceAttribute() == 2).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());

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

        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));
            }
        }
        return businessEntityStatisticsDetail;
    }

    @Override
    public PageBusinessEntityStatisticsDetail pageBusinessEntityStatistics(PageBusinessEntityStatisticsQuery query) {
        List<HouseResource> list = houseResourceMapper.selectAll();
        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 {
            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());
        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;
    }
}
