package com.hrs.dao.impl;

import com.hrs.dao.HouseDao;
import com.hrs.dao.OrderDao;
import com.hrs.model.entity.House;
import com.hrs.model.entity.Order;
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: OrderDaoImpl.java
* @Description: 订单数据访问实现类
*
* @version: v1.0.0
* @author: 赵恒
* @date: 2026年4月13日 上午9:34:55 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     赵恒           v1.0.0               新建文件
*/
public class OrderDaoImpl implements OrderDao {

    private HouseDao houseDao = new HouseDaoImpl();
    private UserDaoImpl userDao = new UserDaoImpl();

    /**
     * 添加订单
     */
    @Override
    public boolean add(Order order) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO hrs_order (tenant_id, house_id, order_no, rent_start_time, " +
                         "rent_end_time, total_rent, pay_status, status, create_time) " +
                         "VALUES (?, ?, ?, ?, ?, ?, '0', '0', NOW())";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, order.getTenantId());
            pstmt.setLong(2, order.getHouseId());
            pstmt.setString(3, order.getOrderNo());
            pstmt.setTimestamp(4, new Timestamp(order.getRentStartTime().getTime()));
            pstmt.setTimestamp(5, new Timestamp(order.getRentEndTime().getTime()));
            pstmt.setBigDecimal(6, order.getTotalRent());

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

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

        return success;
    }

    /**
     * 根据租客ID查询订单列表
     */
    @Override
    public List<Order> findByTenantId(Long tenantId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Order> orderList = new ArrayList<>();

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

            while (rs.next()) {
                Order order = resultSetToOrder(rs);
                orderList.add(order);
            }

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

        return orderList;
    }

    /**
     * 根据房东ID查询订单列表
     */
    @Override
    public List<Order> findByLandlordId(Long landlordId) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Order> orderList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT o.* FROM hrs_order o " +
                         "INNER JOIN hrs_house h ON o.house_id = h.id " +
                         "WHERE h.landlord_id = ? " +
                         "ORDER BY o.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, landlordId);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Order order = resultSetToOrder(rs);
                orderList.add(order);
            }

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

        return orderList;
    }

    /**
     * 根据订单ID查询
     */
    @Override
    public Order findById(Long id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Order order = null;

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

            if (rs.next()) {
                order = resultSetToOrder(rs);
            }

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

        return order;
    }

    /**
     * 根据订单编号查询
     */
    @Override
    public Order findByOrderNo(String orderNo) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Order order = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hrs_order WHERE order_no = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, orderNo);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                order = resultSetToOrder(rs);
            }

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

        return order;
    }

    /**
     * 更新订单状态
     */
    @Override
    public boolean updateStatus(Long orderId, String status) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

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

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

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

        return success;
    }

    /**
     * 更新支付状态
     */
    @Override
    public boolean updatePayStatus(Long orderId, String payStatus) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE hrs_order SET pay_status=?, update_time=NOW() WHERE id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, payStatus);
            pstmt.setLong(2, orderId);

            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_order 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_order o " +
                         "INNER JOIN hrs_house h ON o.house_id = h.id " +
                         "WHERE h.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_order 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;
    }

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

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT o.* FROM hrs_order o " +
                         "ORDER BY o.create_time DESC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Order order = resultSetToOrder(rs);
                orderList.add(order);
            }

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

        return orderList;
    }

    /**
     * 统计所有订单数量（管理员用）
     */
    @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_order";
            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转换为Order对象
     */
    private Order resultSetToOrder(ResultSet rs) throws SQLException {
        Order order = new Order();
        order.setId(rs.getLong("id"));
        order.setTenantId(rs.getLong("tenant_id"));
        order.setHouseId(rs.getLong("house_id"));
        order.setOrderNo(rs.getString("order_no"));
        order.setRentStartTime(rs.getTimestamp("rent_start_time"));
        order.setRentEndTime(rs.getTimestamp("rent_end_time"));
        order.setTotalRent(rs.getBigDecimal("total_rent"));
        order.setPayStatus(rs.getString("pay_status"));
        order.setStatus(rs.getString("status"));
        order.setCreateBy(rs.getString("create_by"));
        order.setCreateTime(rs.getTimestamp("create_time"));
        order.setUpdateBy(rs.getString("update_by"));
        order.setUpdateTime(rs.getTimestamp("update_time"));

        try {
            House house = houseDao.findById(order.getHouseId());
            order.setHouse(house);
        } catch (Exception e) {
            // 忽略
        }

        try {
            User tenant = userDao.findById(order.getTenantId());
            order.setTenant(tenant);
        } catch (Exception e) {
            // 忽略
        }

        return order;
    }
}
