package com.hrs.dao.impl;

import com.hrs.dao.HouseDao;
import com.hrs.model.entity.House;
import com.hrs.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: HouseDaoImpl.java
* @Description: 房源数据访问实现类/负责房源表的增删改查操作
*
* @version: v1.0.0
* @author: 赵恒
* @date: 2026年4月13日 上午9:34:28 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     赵恒           v1.0.0               新建文件
*/
public class HouseDaoImpl implements HouseDao {

    /**
     * 查询已上架的房源（供租客查看）
     */
    @Override
    public List<House> findPublishedHouses() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status = '1' " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 根据区域筛选房源
     */
    @Override
    public List<House> findHousesByArea(String area) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status = '1' AND h.area LIKE ? " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + area + "%");
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 根据价格区间筛选房源
     */
    @Override
    public List<House> findHousesByPrice(int minPrice, int maxPrice) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status = '1' AND h.rent_price BETWEEN ? AND ? " +
                         "ORDER BY h.rent_price ASC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, minPrice);
            pstmt.setInt(2, maxPrice);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 根据房源ID查询详情
     */
    @Override
    public House findById(Long id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        House house = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                house = resultSetToHouse(rs);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return house;
    }

    /**
     * 查询房东自己的房源
     */
    @Override
    public List<House> findByLandlordId(Long landlordId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hrs_house WHERE landlord_id = ? ORDER BY create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, landlordId);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 查询所有房源（管理员用）
     */
    @Override
    public List<House> findAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 查询待审核房源（管理员用）
     */
    @Override
    public List<House> findPendingHouses() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status = '0' " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 查询已上架房源（管理员用）
     */
    @Override
    public List<House> findPublishedHousesForAdmin() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status = '1' " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 查询已下架房源（管理员用）
     */
    @Override
    public List<House> findOfflineHouses() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<House> houseList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT h.*, u.real_name as landlord_name, u.phone as landlord_phone " +
                         "FROM hrs_house h " +
                         "LEFT JOIN hrs_user u ON h.landlord_id = u.id " +
                         "WHERE h.status IN ('2', '3') " +
                         "ORDER BY h.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                houseList.add(resultSetToHouse(rs));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return houseList;
    }

    /**
     * 添加房源
     */
    @Override
    public boolean add(House house) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO hrs_house (landlord_id, house_no, title, area, address, " +
                         "house_type, rent_price, rent_type, facility, description, img_url, " +
                         "status, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, house.getLandlordId());
            pstmt.setString(2, house.getHouseNo());
            pstmt.setString(3, house.getTitle());
            pstmt.setString(4, house.getArea());
            pstmt.setString(5, house.getAddress());
            pstmt.setString(6, house.getHouseType());
            pstmt.setBigDecimal(7, house.getRentPrice());
            pstmt.setString(8, house.getRentType());
            pstmt.setString(9, house.getFacility());
            pstmt.setString(10, house.getDescription());
            pstmt.setString(11, house.getImgUrl());
            pstmt.setString(12, house.getStatus() != null ? house.getStatus() : "0");

            int rows = pstmt.executeUpdate();
            success = rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(pstmt, conn);
        }

        return success;
    }

    /**
     * 更新房源
     */
    @Override
    public boolean update(House house) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE hrs_house SET title=?, area=?, address=?, house_type=?, " +
                         "rent_price=?, rent_type=?, facility=?, description=?, img_url=?, " +
                         "update_time=NOW() WHERE id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, house.getTitle());
            pstmt.setString(2, house.getArea());
            pstmt.setString(3, house.getAddress());
            pstmt.setString(4, house.getHouseType());
            pstmt.setBigDecimal(5, house.getRentPrice());
            pstmt.setString(6, house.getRentType());
            pstmt.setString(7, house.getFacility());
            pstmt.setString(8, house.getDescription());
            pstmt.setString(9, house.getImgUrl());
            pstmt.setLong(10, house.getId());

            int rows = pstmt.executeUpdate();
            success = rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(pstmt, conn);
        }

        return success;
    }

    /**
     * 更新房源状态（审核/上架/下架）
     */
    @Override
    public boolean updateStatus(Long houseId, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE hrs_house SET status=?, update_time=NOW() WHERE id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, status);
            pstmt.setLong(2, houseId);

            int rows = pstmt.executeUpdate();
            success = rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(pstmt, conn);
        }

        return success;
    }

    /**
     * 删除房源
     */
    @Override
    public boolean delete(Long id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM hrs_house WHERE id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, id);

            int rows = pstmt.executeUpdate();
            success = rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(pstmt, conn);
        }

        return success;
    }

    /**
     * 统计已上架房源数量
     */
    @Override
    public int countPublished() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM hrs_house WHERE status = '1'";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return count;
    }

    /**
     * 统计房源总数（管理员用）
     */
    @Override
    public int countAll() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM hrs_house";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pstmt, conn);
        }

        return count;
    }

    /**
     * 将ResultSet转换为House对象
     */
    private House resultSetToHouse(ResultSet rs) throws SQLException {
        House house = new House();
        house.setId(rs.getLong("id"));
        house.setLandlordId(rs.getLong("landlord_id"));
        house.setHouseNo(rs.getString("house_no"));
        house.setTitle(rs.getString("title"));
        house.setArea(rs.getString("area"));
        house.setAddress(rs.getString("address"));
        house.setHouseType(rs.getString("house_type"));
        house.setRentPrice(rs.getBigDecimal("rent_price"));
        house.setRentType(rs.getString("rent_type"));
        house.setFacility(rs.getString("facility"));
        house.setDescription(rs.getString("description"));
        house.setImgUrl(rs.getString("img_url"));
        house.setStatus(rs.getString("status"));
        house.setCreateBy(rs.getString("create_by"));
        house.setCreateTime(rs.getTimestamp("create_time"));
        house.setUpdateBy(rs.getString("update_by"));
        house.setUpdateTime(rs.getTimestamp("update_time"));

        // 关联字段
        try {
            house.setLandlordName(rs.getString("landlord_name"));
            house.setLandlordPhone(rs.getString("landlord_phone"));
        } catch (SQLException e) {
            // 可能没有这些字段
        }

        return house;
    }
}
