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.core.domain.AjaxResult;
import com.ruoyi.system.domain.grid.GridCompany;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.grid.GridShop;
import com.ruoyi.system.domain.house.HouseResource;
import com.ruoyi.system.domain.house.HouseResourceAssociationObject;
import com.ruoyi.system.domain.house.enums.HouseEnums;
import com.ruoyi.system.domain.house.vo.HouseResourceDetail;
import com.ruoyi.system.domain.house.vo.HouseResourcePage;
import com.ruoyi.system.domain.house.vo.HouseResourcePageQuery;
import com.ruoyi.system.domain.house.vo.HouseResourceSaveUpdateDto;
import com.ruoyi.system.domain.other.Labels;
import com.ruoyi.system.domain.other.LabelsExample;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.mapper.house.HouseResourceAssociationObjectMapper;
import com.ruoyi.system.mapper.house.HouseResourceMapper;
import com.ruoyi.system.mapper.other.LabelsMapper;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridShopService;
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.StringUtils;

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

@Service
public class HouseResourceServiceImpl implements HouseResourceService {

    private final HouseResourceMapper houseResourceMapper;

    private final HouseResourceAssociationObjectMapper houseResourceAssociationObjectMapper;

    private final GridRegionMapper gridRegionMapper;

    private final GridCompanyService gridCompanyService;

    private final GridShopService gridShopService;

    private final LabelsMapper labelsMapper;

    public HouseResourceServiceImpl(HouseResourceMapper houseResourceMapper, HouseResourceAssociationObjectMapper houseResourceAssociationObjectMapper, GridRegionMapper gridRegionMapper, GridCompanyService gridCompanyService, GridShopService gridShopService, LabelsMapper labelsMapper) {
        this.houseResourceMapper = houseResourceMapper;
        this.houseResourceAssociationObjectMapper = houseResourceAssociationObjectMapper;
        this.gridRegionMapper = gridRegionMapper;
        this.gridCompanyService = gridCompanyService;
        this.gridShopService = gridShopService;
        this.labelsMapper = labelsMapper;
    }

    @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 (GridCompany gridCompany : dto.getCompanyList()) {
            AjaxResult result = gridCompanyService.add(gridCompany);
            if (result.isSuccess()) {
                String id = result.get("data").toString();
                HouseResourceAssociationObject houseResourceAssociationObject = new HouseResourceAssociationObject();
                houseResourceAssociationObject.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                houseResourceAssociationObject.setHouseResourceId(houseResourceId);
                houseResourceAssociationObject.setBusinessId(id);
                houseResourceAssociationObject.setType(1);
                houseResourceAssociationObjectMapper.insertHouseResourceObjectAssociation(houseResourceAssociationObject);
            }
        }

        for (GridShop gridShop : dto.getShopList()) {
            try {
                AjaxResult result = gridShopService.addGridShop(gridShop);
                if (result.isSuccess()) {
                    String id = result.get("data").toString();
                    HouseResourceAssociationObject houseResourceAssociationObject = new HouseResourceAssociationObject();
                    houseResourceAssociationObject.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    houseResourceAssociationObject.setHouseResourceId(houseResourceId);
                    houseResourceAssociationObject.setBusinessId(id);
                    houseResourceAssociationObject.setType(2);
                    houseResourceAssociationObjectMapper.insertHouseResourceObjectAssociation(houseResourceAssociationObject);
                }
            } catch (Exception e) {
                throw new RuntimeException("新增shop出错");
            }
        }
    }

    @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());
        }
        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()));
        return houseResourceDetail;
    }

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

        for (GridCompany gridCompany : dto.getCompanyList()) {
            if (!StringUtils.hasText(gridCompany.getId())) {
                AjaxResult result = gridCompanyService.add(gridCompany);
                if (result.isSuccess()) {
                    String id = result.get("data").toString();
                    HouseResourceAssociationObject houseResourceAssociationObject = new HouseResourceAssociationObject();
                    houseResourceAssociationObject.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    houseResourceAssociationObject.setHouseResourceId(dto.getHouseResource().getId());
                    houseResourceAssociationObject.setBusinessId(id);
                    houseResourceAssociationObject.setType(1);
                    houseResourceAssociationObjectMapper.insertHouseResourceObjectAssociation(houseResourceAssociationObject);
                }
            } else {
                gridCompanyService.edit(gridCompany);
            }
        }

        for (GridShop gridShop : dto.getShopList()) {
            if (Objects.isNull(gridShop.getId())) {
                AjaxResult result = null;
                try {
                    result = gridShopService.addGridShop(gridShop);
                } catch (Exception e) {
                    throw new RuntimeException("新增shop出错");
                }
                if (result.isSuccess()) {
                    String id = result.get("data").toString();
                    HouseResourceAssociationObject houseResourceAssociationObject = new HouseResourceAssociationObject();
                    houseResourceAssociationObject.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    houseResourceAssociationObject.setHouseResourceId(dto.getHouseResource().getId());
                    houseResourceAssociationObject.setBusinessId(id);
                    houseResourceAssociationObject.setType(2);
                    houseResourceAssociationObjectMapper.insertHouseResourceObjectAssociation(houseResourceAssociationObject);
                } else {
                    return result;
                }
            } else {
                try {
                    gridShopService.updateGridShop(gridShop);
                } catch (Exception e) {
                    throw new RuntimeException("更新shop出错");
                }
            }
        }
        return AjaxResult.success();
    }

    @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);
        page.getRecords().forEach(x -> {
            GridRegionExample gridRegionExample = new GridRegionExample();
            gridRegionExample.createCriteria().andWgCodeEqualTo(x.getTwo()).andWgTypeEqualTo(String.valueOf(x.getType()));
            List<GridRegion> two = gridRegionMapper.selectByExample(gridRegionExample);
            if (!two.isEmpty()) {
                x.setWgName2(two.get(0).getWgName());
            }
            if (StringUtils.hasText(x.getHouseResourceUrl())) {
                x.setHouseResourceUrlList(Arrays.asList(x.getHouseResourceUrl().split(",")));
            }
            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()));
        });
        return page;
    }
}
