package com.ruoyi.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.web.domain.dto.house.HouseInfoAddRequest;
import com.ruoyi.web.domain.dto.house.HouseInfoEditRequest;
import com.ruoyi.web.domain.dto.house.HouseInfoQueryRequest;
import com.ruoyi.web.domain.entity.HouseInfo;
import com.ruoyi.web.domain.entity.PersonHouseRelation;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.vo.HouseInfoVO;
import com.ruoyi.web.domain.vo.PersonInfoVO;
import com.ruoyi.web.mapper.HouseInfoMapper;
import com.ruoyi.web.service.HouseInfoService;
import com.ruoyi.web.service.PersonHouseRelationService;
import com.ruoyi.web.service.PersonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房屋服务
 */
@Service
public class HouseInfoServiceImpl extends ServiceImpl<HouseInfoMapper, HouseInfo>
        implements HouseInfoService {

    @Autowired
    private HouseInfoService houseInfoService;

    @Autowired
    private PersonHouseRelationService personHouseRelationService;

    @Autowired
    private PersonInfoService personInfoService;

    @Override
    public Integer addHouseInfo(HouseInfoAddRequest houseInfoAddRequest) {
        if (houseInfoAddRequest == null) {
            throw new ServiceException("请求参数为空");
        }
        try {
            HouseInfo houseInfo = new HouseInfo();
            BeanUtil.copyProperties(houseInfoAddRequest, houseInfo);
            // 将标签 List 转为 String
            houseInfo.setHouseTags(JSONUtil.toJsonStr(houseInfoAddRequest.getHouseTags()));
            // 数据校验 todo
            validHouseInfo(houseInfo, BusinessType.INSERT);

            // 保存到数据库
            this.save(houseInfo);
            return houseInfo.getId();
        } catch (Exception e) {
            log.error("添加房屋失败", e);
            throw new ServiceException("添加房屋失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteHouseInfo(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new ServiceException("id不能为空或id异常");
        }

        // 2. 分割ID字符串为List<Integer>
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            throw new ServiceException("ID格式异常");
        }

        // 3. 构建删除条件
        QueryWrapper<HouseInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);

        // 4. 执行删除（返回是否删除成功）
        return remove(queryWrapper);
    }

    @Override
    public void editHouseInfo(HouseInfoEditRequest houseInfoEditRequest) {
        // 判断是否存在
        Integer id = houseInfoEditRequest.getId();
        HouseInfo oldHouseInfo = this.getById(id);
        if (oldHouseInfo == null) {
            throw new ServiceException("没有找到房屋");
        }
        HouseInfo houseInfo = new HouseInfo();
        BeanUtil.copyProperties(houseInfoEditRequest, houseInfo);
        // 将人口标签 List 转为 String
        houseInfo.setHouseTags(JSONUtil.toJsonStr(houseInfoEditRequest.getHouseTags()));
        houseInfo.setUpdateTime(new Date());
        // 数据校验
        validHouseInfo(houseInfo, BusinessType.UPDATE);

        // 操作数据库
        boolean result = this.updateById(houseInfo);
        if (!result) {
            throw new ServiceException("修改房屋操作失败");
        }
    }

    /**
     * 校验房屋
     *
     * @param houseInfo
     */
    public void validHouseInfo(HouseInfo houseInfo, BusinessType type) {
        if (ObjectUtil.isEmpty(houseInfo)) {
            throw new ServiceException("数据为空");
        }
        Integer id = houseInfo.getId();
        String houseCode = houseInfo.getHouseCode();
        String doorplateNumber = houseInfo.getDoorplateNumber();
        String houseAddress = houseInfo.getHouseAddress();
        Integer houseOwnerId = houseInfo.getHouseOwnerId();
        Integer totalPoints = houseInfo.getTotalPoints();
        Integer remainingPoints = houseInfo.getRemainingPoints();
        Integer houseCategory = houseInfo.getHouseCategory();
        BigDecimal buildingArea = houseInfo.getBuildingArea();
        String grid = houseInfo.getGrid();
        String photoUrl = houseInfo.getPhotoUrl();
        String houseTags = houseInfo.getHouseTags();
        Date createTime = houseInfo.getCreateTime();
        Date updateTime = houseInfo.getUpdateTime();
        String delFlag = houseInfo.getDelFlag();


        // 修改数据时，id 不能为空 todo
        if (type != BusinessType.INSERT && ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        if (StrUtil.isBlank(houseCode)) {
            throw new ServiceException("房屋编号不能为空");
        }
    }

    /**
     * 获取房屋包装类
     *
     * @param houseInfo
     * @return
     */
    @Override
    public HouseInfoVO getHouseInfoVO(HouseInfo houseInfo) {
        if (ObjectUtil.isEmpty(houseInfo)) {
            throw new ServiceException("请求参数不存在");
        }
        HouseInfoVO houseInfoVO = new HouseInfoVO();
        BeanUtils.copyProperties(houseInfo, houseInfoVO);

        // 通过关联表 获取 成员数量
        Integer houseInfoId = houseInfo.getId();
        Integer memberCount = personHouseRelationService.lambdaQuery()
                .eq(PersonHouseRelation::getHouseId, houseInfoId)
                .count()
                .intValue();
        houseInfoVO.setMemberCount(memberCount);

        // 通过房主人员ID -> 房主姓名 身份证 联系方式(人员VO类)
        Integer houseOwnerId = houseInfo.getHouseOwnerId();
        if (houseOwnerId != null) {
            PersonInfo houseOwnerInfo = personInfoService.getById(houseOwnerId);
            PersonInfoVO houseOwnerInfoVO = personInfoService.getPersonInfoVO(houseOwnerInfo);
            houseInfoVO.setHouseOwnerInfo(houseOwnerInfoVO);
        }
        return houseInfoVO;
    }

    /**
     * 根据id获取人员包装类
     *
     * @param id
     * @return
     */
    @Override
    public HouseInfoVO getHouseInfoById(int id) {
        if (id <= 0 || ObjectUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空或id异常");
        }
        HouseInfo houseInfo = this.getById(id);
        return getHouseInfoVO(houseInfo);
    }


    /**
     * 分页获取房屋列表
     *
     * @param houseInfoQueryRequest
     * @return
     */
    @Override
    public Page<HouseInfoVO> getListHouseInfoByPage(HouseInfoQueryRequest houseInfoQueryRequest) {
        long current = houseInfoQueryRequest.getPageNum();
        long size = houseInfoQueryRequest.getPageSize();
        // 1. 分页查询房屋基础信息
        Page<HouseInfo> houseInfoPage = this.page(new Page<>(current, size),
                getQueryWrapper(houseInfoQueryRequest));

        // 2. 补充关联数据
        Page<HouseInfoVO> resultPage = new Page<>();
        BeanUtils.copyProperties(houseInfoPage, resultPage, "records");

        // 3. 处理每条记录
        List<HouseInfoVO> viewList = houseInfoPage.getRecords().stream().map(houseInfo -> {
            return getHouseInfoVO(houseInfo);
        }).collect(Collectors.toList());
        resultPage.setRecords(viewList);
        return resultPage;
    }


    /**
     * 获取查询条件
     *
     * @param houseInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<HouseInfo> getQueryWrapper(HouseInfoQueryRequest houseInfoQueryRequest) {
        QueryWrapper<HouseInfo> queryWrapper = new QueryWrapper<>();
        if (houseInfoQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Integer id = houseInfoQueryRequest.getId();
        String doorplateNumber = houseInfoQueryRequest.getDoorplateNumber();
        Integer houseOwnerId = houseInfoQueryRequest.getHouseOwnerId();
        String houseOwnerName = houseInfoQueryRequest.getHouseOwnerName();
        Integer houseCategory = houseInfoQueryRequest.getHouseCategory();
        Integer grid = houseInfoQueryRequest.getGrid();
        List<String> houseTags = houseInfoQueryRequest.getHouseTags();
        String sortField = houseInfoQueryRequest.getSortField();
        String sortOrder = houseInfoQueryRequest.getSortOrder();

        //门牌号、房主ID、房屋类别、所属网格、家庭标签
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(doorplateNumber), "doorplate_number", doorplateNumber);
        //queryWrapper.eq(ObjectUtil.isNotEmpty(houseOwnerId), "house_owner_id", houseOwnerId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(grid), "grid", grid);
        queryWrapper.eq(ObjectUtil.isNotEmpty(houseCategory), "house_category", houseCategory);

        // 优先使用 房主id 查询  没有房主id 再根据 房主姓名查询
        if (ObjectUtil.isNotEmpty(houseOwnerId)) {
            queryWrapper.eq("house_owner_id", houseOwnerId);
        } else if (StrUtil.isNotBlank(houseOwnerName)) {
            queryWrapper.exists("EXISTS (SELECT 1 FROM person_info p WHERE p.id = house_owner_id AND p.realname LIKE {0})");
        }

        // 家庭标签 JSON 数组查询
        if (CollUtil.isNotEmpty(houseTags)) {
            for (String tag : houseTags) {
                queryWrapper.like("house_tags", "\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
}




