package backend.dao;

import backend.model.User;
import backend.service.AuthService;
import backend.utils.DBConnectionPool;
import backend.utils.DBHelper;

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

public class UserDao {

    List<User> commonResultSet(ResultSet rs) throws SQLException{
        List<User> userPoList = new ArrayList<>();
        while(rs.next()){
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setRole(rs.getString("role"));
            user.setEmail(rs.getString("email"));
            user.setCreatedAt(rs.getDate("createdAt"));
            userPoList.add(user);
        }
        return userPoList;
    }

    public User findByUsername(String username) {
        User user = null;
        //1. 从连接池中创建数据库连接
        Connection conn = DBHelper.getInstance().getConnection();
        //2. 创建Statement对象
        String sql = "select id,username,password,role,email,createdAt from USER where username = ?";
        try {
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRole(rs.getString("role"));
                user.setEmail(rs.getString("email"));
                user.setCreatedAt(rs.getDate("createdAt"));
            }
        } catch (SQLException e) {
            System.out.println("查询用户失败: " + e.getMessage());
        }
        return user;
    }

    public User findById(int id) {
        User user = null;
        //1. 从连接池中创建数据库连接
        Connection conn = DBHelper.getInstance().getConnection();
        //2. 创建Statement对象
        String sql = "select id,username,password,role,email,createdAt from USER where id = ?";
        try{
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setInt(1,id);
            ResultSet rs = stmt.executeQuery();
            while(rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRole(rs.getString("role"));
                user.setEmail(rs.getString("email"));
                user.setCreatedAt(rs.getDate("createdAt"));
            }
        }catch (SQLException e) {
            System.out.println("查询用户失败: " + e.getMessage());
        }
        return user;
    }

    public boolean addUser(User user) {
        Connection conn = DBHelper.getInstance().getConnection();
        int row=0;
        if(conn==null)
            return false;
        String sql = "insert into USER (username,password,role,email,createdAt) values (?,?,?,?,?)";
        try{
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1,user.getUsername());
            stmt.setString(2,user.getPassword());
            stmt.setString(3,user.getRole());
            stmt.setString(4,user.getEmail());
            stmt.setDate(5,user.getCreatedAt());
            row = stmt.executeUpdate();
            stmt.close();
            DBConnectionPool.releaseConnection(conn);
        } catch (SQLException e) {
            System.out.println("添加用户失败: " + e.getMessage());
        }
        return row>0;
    }

    public boolean updateUser(User user) {
        Connection conn = DBHelper.getInstance().getConnection();
        int row = 0;
        if(conn==null)
            return false;

        String sql = "update USER set username = ?,password = ?,role = ?,email = ?,createdAt = ? where id = ?";
        try{
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1,user.getUsername());
            stmt.setString(2,user.getPassword());
            stmt.setString(3,user.getRole());
            stmt.setString(4,user.getEmail());
            stmt.setDate(5,user.getCreatedAt());
            stmt.setInt(6,user.getId());
            row = stmt.executeUpdate();
            stmt.close();
        } catch (SQLException e) {
            System.out.println("更新用户失败: " + e.getMessage());
        }finally {
            DBConnectionPool.releaseConnection(conn);
        }
        return row>0;
    }

    public boolean deleteUser(int id) {
        Connection conn = DBHelper.getInstance().getConnection();
        String sql = "delete from USER where id = ?";
        int row = 0;
        try{
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setInt(1,id);
            row = stmt.executeUpdate() ;
        } catch (SQLException e) {
            System.out.println("删除用户失败: " + e.getMessage());
        }
        return row>0;
    }

    public List<User> findAll() {
        List<User> userPoList = new ArrayList<>();
        Connection conn = DBHelper.getInstance().getConnection();
        String sql = "select id,username,password,role,email,createdAt from USER";
        try {
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRole(rs.getString("role"));
                user.setEmail(rs.getString("email"));
                user.setCreatedAt(rs.getDate("createdAt"));
                userPoList.add(user);
            }
        }catch (SQLException e) {
            System.out.println("查询所有用户失败: " + e.getMessage());
        }
        return userPoList;
    }


    public List<User> findByCondition(String role, String key) {
        List<User> userPoList = null;
        //1. 从连接池中拿到连接
        Connection conn = DBConnectionPool.getConnection();
        if(conn==null)
            return null;
        //2. 创建Statement对象
        String sql = "select id,username,password,role,email,createdAt from USER where username like ?";
        if(role != null)
            sql += " and role = ?";
        try{
            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, "%"+key+"%");
            if(role != null)
                stmt.setString(2, role);
            ResultSet rs = stmt.executeQuery();
            userPoList =commonResultSet(rs);
            rs.close();
            stmt.close();

        }catch(SQLException e){
            System.out.println("数据库异常："+ e.getMessage());
        }finally {
            DBConnectionPool.releaseConnection(conn);
        }
        return userPoList;
    }

    public static void main(String[] args) {
        UserDao userDao = new UserDao();
        AuthService authService = new AuthService();
        User user= userDao.findById(2);
        System.out.println(user.getRole());
        user.setRole("admin");
        System.out.println(user.getRole());
        userDao.updateUser(user);
        System.out.println(userDao.findById(2).getRole());
    }

}
