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.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);
            GridRegion gridRegion = gridRegionMapper.selectByPrimaryKey(k);
            houseResourceProfileGraph.setWgName(gridRegion.getWgName());
            houseResourceProfileGraph.setHouseResources(handleHouseList(v));
            resourceProfileGraphList.add(houseResourceProfileGraph);
        });
        return resourceProfileGraphList;
    }

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

    private List<HouseResourcePage> handleHouseList(List<HouseResourcePage> list) {
        list.forEach(x -> {
            GridRegion two = gridRegionMapper.selectByPrimaryKey(x.getTwo());
            x.setWgName2(two.getWgName());

            GridRegion three = gridRegionMapper.selectByPrimaryKey(x.getThree());
            x.setWgName3(three.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;
    }
}
