package com.hrs.dao.impl;

import com.hrs.dao.HouseDao;
import com.hrs.dao.ReservationDao;
import com.hrs.dao.UserDao;
import com.hrs.model.entity.Reservation;
import com.hrs.model.entity.House;
import com.hrs.model.entity.User;
import com.hrs.util.DBUtil;

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

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: ReservationDaoImpl.java
* @Description: 预约看房数据访问实现类
*
* @version: v1.0.0
* @author: 赵恒
* @date: 2026年4月13日 上午9:35:10 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     赵恒           v1.0.0               新建文件
*/
public class ReservationDaoImpl implements ReservationDao {
	
    private HouseDao houseDao = new HouseDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    /**
     * 添加预约
     */
    @Override
    public boolean add(Reservation reservation) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO hrs_reservation (tenant_id, house_id, landlord_id, reserve_time, remark, status, create_time) " +
                         "VALUES (?, ?, ?, ?, ?, '0', NOW())";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, reservation.getTenantId());
            pstmt.setLong(2, reservation.getHouseId());
            pstmt.setLong(3, reservation.getLandlordId());
            pstmt.setTimestamp(4, new Timestamp(reservation.getReserveTime().getTime()));
            pstmt.setString(5, reservation.getRemark());

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

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

        return success;
    }

    /**
     * 查询租客的所有预约
     */
    @Override
    public List<Reservation> findByTenantId(Long tenantId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Reservation> reservationList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hrs_reservation WHERE tenant_id = ? ORDER BY reserve_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, tenantId);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Reservation reservation = resultSetToReservation(rs);
                // 关联房源详情
                House house = houseDao.findById(reservation.getHouseId());
                reservation.setHouse(house);
                reservationList.add(reservation);
            }

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

        return reservationList;
    }

    /**
     * 查询房东收到的预约
     */
    @Override
    public List<Reservation> findByLandlordId(Long landlordId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Reservation> reservationList = new ArrayList<>();

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

            while (rs.next()) {
                Reservation reservation = resultSetToReservation(rs);
                // 关联房源详情
                House house = houseDao.findById(reservation.getHouseId());
                reservation.setHouse(house);
                // 关联租客信息
                User tenant = userDao.findById(reservation.getTenantId());
                reservation.setTenant(tenant);
                reservationList.add(reservation);
            }

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

        return reservationList;
    }

    /**
     * 根据ID查询预约
     */
    @Override
    public Reservation findById(Long id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Reservation reservation = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hrs_reservation WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                reservation = resultSetToReservation(rs);
                House house = houseDao.findById(reservation.getHouseId());
                reservation.setHouse(house);
                User tenant = userDao.findById(reservation.getTenantId());
                reservation.setTenant(tenant);
                User landlord = userDao.findById(reservation.getLandlordId());
                reservation.setLandlord(landlord);
            }

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

        return reservation;
    }

    /**
     * 更新预约状态（房东确认/取消）
     */
    @Override
    public boolean updateStatus(Long id, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

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

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

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

        return success;
    }

    /**
     * 取消预约（租客取消）
     */
    @Override
    public boolean cancel(Long id, Long tenantId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE hrs_reservation SET status='2', update_time=NOW() WHERE id=? AND tenant_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, id);
            pstmt.setLong(2, tenantId);

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

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

        return success;
    }

    /**
     * 统计租客的预约数量
     */
    @Override
    public int countByTenantId(Long tenantId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM hrs_reservation WHERE tenant_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, tenantId);
            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 countByLandlordId(Long landlordId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM hrs_reservation WHERE landlord_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, landlordId);
            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 boolean existsByHouseId(Long houseId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) FROM hrs_reservation WHERE house_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, houseId);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }

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

        return false;
    }

    /**
     * 将ResultSet转换为Reservation对象
     */
    private Reservation resultSetToReservation(ResultSet rs) throws SQLException {
        Reservation reservation = new Reservation();
        reservation.setId(rs.getLong("id"));
        reservation.setTenantId(rs.getLong("tenant_id"));
        reservation.setHouseId(rs.getLong("house_id"));
        reservation.setLandlordId(rs.getLong("landlord_id"));
        reservation.setReserveTime(rs.getTimestamp("reserve_time"));
        reservation.setRemark(rs.getString("remark"));
        reservation.setStatus(rs.getString("status"));
        reservation.setHandleTime(rs.getTimestamp("handle_time"));
        reservation.setCreateBy(rs.getString("create_by"));
        reservation.setCreateTime(rs.getTimestamp("create_time"));
        reservation.setUpdateBy(rs.getString("update_by"));
        reservation.setUpdateTime(rs.getTimestamp("update_time"));
        return reservation;
    }
}
