package com.zksy.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.property.domain.*;
import com.zksy.property.domain.dto.ASimplifiedHouseInfoDto;
import com.zksy.property.domain.vo.ASimplifiedHouseInfoVo;
import com.zksy.property.domain.vo.HouseInfoVo;
import com.zksy.property.mapper.ASimplifiedHouseInfoMapper;
import com.zksy.property.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【a_simplified_house_info(房屋信息表)】的数据库操作Service实现
* @createDate 2025-07-14 11:59:44
*/
@Service
public class ASimplifiedHouseInfoServiceImpl extends ServiceImpl<ASimplifiedHouseInfoMapper, ASimplifiedHouseInfo>
    implements ASimplifiedHouseInfoService{
    @Autowired
    private ASimplifiedHouseInfoMapper houseInfoMapper;
    @Override
    public Page<ASimplifiedHouseInfo> findByPage(long pageNum, long pageSize, String assetType, String building, String houseName, String status) {
        Page<ASimplifiedHouseInfo> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<ASimplifiedHouseInfo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(assetType != null,ASimplifiedHouseInfo::getAssetType,assetType);
        queryWrapper.like(building != null,ASimplifiedHouseInfo::getBuilding,building);
        queryWrapper.like(houseName != null,ASimplifiedHouseInfo::getHouseName,houseName);
        queryWrapper.like(status != null,ASimplifiedHouseInfo::getStatus,status);
        queryWrapper.orderByDesc(ASimplifiedHouseInfo::getCreateTime);
        return this.page(page,queryWrapper);
    }

    @Override
    public List<ASimplifiedHouseInfo> getASimplifiedHouseInfoList(String assetType, String building, String houseName, String status) {
        LambdaQueryWrapper<ASimplifiedHouseInfo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(assetType != null,ASimplifiedHouseInfo::getAssetType,assetType);
        queryWrapper.like(building != null,ASimplifiedHouseInfo::getBuilding,building);
        queryWrapper.like(houseName != null,ASimplifiedHouseInfo::getHouseName,houseName);
        queryWrapper.like(status != null,ASimplifiedHouseInfo::getStatus,status);
        List<ASimplifiedHouseInfo> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public Page<ASimplifiedHouseInfoVo> getListPage(ASimplifiedHouseInfoDto entity) {
        int offset = 0;
        String sortClause = null;
        // 计算偏移量
        if (entity.getPageNum() != null && entity.getPageSize() != null) {
            offset = (entity.getPageNum() - 1) * entity.getPageSize();
        }

        // 创建分页对象
        Page<ASimplifiedHouseInfoVo> page = new Page<>(
                entity.getPageNum() != null ? entity.getPageNum() : 1,
                entity.getPageSize() != null ? entity.getPageSize() : 10
        );
        if (entity.getSortSearch() != null) {
            switch (entity.getSortSearch()) {
                case "1": sortClause = "a.rent_range DESC"; break;
                case "2": sortClause = "a.rent_range ASC"; break;
                case "3": sortClause = "b.area DESC"; break;
                case "4": sortClause = "b.area ASC"; break;
                default: sortClause = null;
            }
        }
        // 执行查询
        List<ASimplifiedHouseInfoVo> list = houseInfoMapper.getListPage(entity,offset,entity.getPageSize(),sortClause);

        // 设置分页数据
        page.setRecords(list);
        page.setTotal(houseInfoMapper.getListPageTotal(entity));

        return page;
    }

    @Autowired
    private AHouseInfoDetailService aHouseInfoDetailService;
    @Autowired
    private ATenantInfoService aTenantInfoService;
    @Autowired
    private ADeviceInfoService aDeviceInfoService;
    @Autowired
    @Lazy
    private AContractInfoService aContractInfoService;

    @Override
    public HouseInfoVo getHouseDetailInfo(String simplifiedHouseId) {
        ASimplifiedHouseInfo houseInfo = this.getById(simplifiedHouseId);
        if (houseInfo == null) {
            throw new RuntimeException("数据不存在");
        }

        HouseInfoVo vo = new HouseInfoVo();
        vo.setHouseName(houseInfo.getHouseName());
        vo.setAddress(houseInfo.getAddress());
        vo.setStatus(houseInfo.getStatus());
        vo.setRentRange(houseInfo.getRentRange());
        vo.setAssetType(houseInfo.getAssetType());

        // 设置房屋详细信息
        AHouseInfoDetail detail = aHouseInfoDetailService.getBySimplifiedHouseId(simplifiedHouseId);
        vo.setHouseInfo(buildHouseInfo(houseInfo, detail));

        // 设置设备信息
        List<ADeviceInfo> deviceInfos = aDeviceInfoService.getBySimplifiedHouseId(simplifiedHouseId);
        vo.setDeviceInfo(mapDeviceInfo(deviceInfos));

        // 如果房屋已租，设置租户和合同信息
        if ("已租".equals(houseInfo.getStatus())) {
            vo.setTenantInfo(buildTenantInfo(simplifiedHouseId));
            vo.setContractInfo(buildContractInfo(simplifiedHouseId));
        }

        return vo;
    }

    @Override
    @Transactional
    public boolean removeBatchId(String[] ids) {
        try {
            for (String id : ids) {
                //根据id查询房屋信息
                ASimplifiedHouseInfo houseInfo = this.getById(id);
                if(houseInfo == null){
                    throw new RuntimeException("数据不存在");
                }else if("已租".equals(houseInfo.getStatus())){
                    throw new RuntimeException("该房屋已租，请先解约");
                }
                //设备
                List<ADeviceInfo> deviceInfos = aDeviceInfoService.getBySimplifiedHouseId(id);
                if(deviceInfos != null && deviceInfos.size() > 0){
                    throw new RuntimeException("该房屋已绑定设备，请先删除设备");
                }
                //租户
                ATenantInfo tenantInfos = aTenantInfoService.getBySimplifiedHouseId(id);
                if(tenantInfos != null){
                    throw new RuntimeException("该房屋已绑定租户，请先删除租户");
                }
                //合同
                AContractInfo contractInfo = aContractInfoService.getBySimplifiedHouseId(id);
                if(contractInfo != null){
                    throw new RuntimeException("该房屋已绑定合同，请先删除合同");
                }
                //房屋详细信息
                AHouseInfoDetail houseInfoDetail = aHouseInfoDetailService.getBySimplifiedHouseId(id);
                if(houseInfoDetail != null){
                    boolean remove = aHouseInfoDetailService.removeById(houseInfoDetail.getId());
                    if (!remove) {
                        throw new RuntimeException("删除失败");
                    }
                }
                boolean remove = this.removeById(id);
                if (!remove) {
                    throw new RuntimeException("删除失败");
                }
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getArrears() {
        return houseInfoMapper.getArrears();
    }

    // 构建房屋详细信息
    private HouseInfoVo.HouseInfo buildHouseInfo(ASimplifiedHouseInfo houseInfo, AHouseInfoDetail detail) {
        HouseInfoVo.HouseInfo info = new HouseInfoVo.HouseInfo();
        info.setFloor(houseInfo.getFloor());

        if (detail != null) {
            info.setArea(detail.getArea());
            info.setHouseType(detail.getHouseType());
            info.setIntroduce(detail.getIntroduce());
        }

        return info;
    }

    // 映射设备信息列表
    private List<HouseInfoVo.DeviceInfo> mapDeviceInfo(List<ADeviceInfo> deviceInfos) {
        return deviceInfos.stream()
                .map(deviceInfo -> {
                    HouseInfoVo.DeviceInfo device = new HouseInfoVo.DeviceInfo();
                    device.setDeviceName(deviceInfo.getDeviceName());
                    device.setDeviceType(deviceInfo.getDeviceType());
                    device.setDeviceBrand(deviceInfo.getDeviceBrand());
                    device.setDeviceNumber(deviceInfo.getDeviceNumber());
                    device.setDevicePrice(deviceInfo.getDevicePrice());
                    return device;
                })
                .collect(Collectors.toList());
    }

    // 构建租户信息
    private HouseInfoVo.TenantInfo buildTenantInfo(String simplifiedHouseId) {
        ATenantInfo tenantInfo = aTenantInfoService.getBySimplifiedHouseId(simplifiedHouseId);
        HouseInfoVo.TenantInfo tenant = new HouseInfoVo.TenantInfo();

        if (tenantInfo != null) {
            tenant.setTenantName(tenantInfo.getTenantName());
            tenant.setTenantIdCard(tenantInfo.getTenantIdCard());
            tenant.setTenantInDate(formatDate(tenantInfo.getTenantInDate()));
            tenant.setTenantTime(tenantInfo.getTenantTime());
            tenant.setTenantRent(tenantInfo.getTenantRent().toString());
            tenant.setTenantNumber(tenantInfo.getTenantNumber());
        }

        return tenant;
    }

    // 构建合同信息
    private HouseInfoVo.ContractInfo buildContractInfo(String simplifiedHouseId) {
        AContractInfo contractInfo = aContractInfoService.getBySimplifiedHouseId(simplifiedHouseId);
        HouseInfoVo.ContractInfo contract = new HouseInfoVo.ContractInfo();

        if (contractInfo != null) {
            contract.setContractNumber(contractInfo.getContractNumber());
            contract.setContractDate(formatDate(contractInfo.getContractDate()));
            contract.setContractTime(contractInfo.getContractTime());
            contract.setContractExpirationDate(formatDate(contractInfo.getContractExpirationDate()));
            contract.setContractDeposit(contractInfo.getContractDeposit().toString());
            contract.setContractStatus(contractInfo.getContractStatus());
            contract.setContractOriginalUrl(contractInfo.getOriginalContractUrl());
        }

        return contract;
    }

    // 日期格式化工具方法
    private String formatDate(LocalDate date) {
        return date != null ? date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) : null;
    }
}




