using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Threading.Tasks;

namespace MeterVision.db
{
    public abstract class SQLiteHelper
    {
        private static string DBFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MeterVision.db");
        //private static string connectionString = $"data source={DBFileName}";
        private static string connectionString = $"Data Source={DBFileName};Version=3;";
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string GetConnStr()
        {
            return connectionString;
        }

        /// <summary>
        /// 创建本地库连接
        /// </summary>
        /// <returns>返回本地库连接</returns>
        public static SQLiteConnection CreateConn()
        {
            return new SQLiteConnection(connectionString);
        }

        // 获取 SQLite 数据库连接
        public static SQLiteConnection GetConnection()
        {
            return new SQLiteConnection(connectionString);
        }

        // 执行 SQL 命令（不返回结果集，仅返回受影响的行数）
        public static int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)
        {
            using (SQLiteConnection conn = GetConnection())
            {
                conn.Open();
                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                {
                    // 添加参数
                    if (parameters != null)
                    {
                        cmd.Parameters.AddRange(parameters);
                    }

                    // 执行 SQL 语句并返回受影响的行数
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        // 支持事务的 ExecuteNonQuery
        public static int ExecuteNonQuery(string sql, SQLiteParameter[] parameters, SQLiteTransaction transaction)
        {
            using (SQLiteCommand cmd = new SQLiteCommand(sql, transaction.Connection, transaction))
            {
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }

                return cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 执行查询语句，返回一个值
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>返回的值</returns>
        public static int ExecuteSel(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    return Convert.ToInt32(cmd.ExecuteScalar());
                }
                catch (SQLiteException e)
                {
                    throw new Exception("Error executing SELECT query.", e);
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    return cmd.ExecuteNonQuery();
                }
                catch (SQLiteException e)
                {
                    throw new Exception("Error executing SQL.", e);
                }
            }
        }

        /// <summary>
        /// 执行一组SQL语句
        /// </summary>
        /// <param name="SQLList">SQL语句集合</param>
        /// <returns>成功返回True,失败返回False</returns>
        public static bool ExecuteSql(List<string> SQLList)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (SQLiteTransaction transaction = connection.BeginTransaction())
                {
                    try
                    {
                        foreach (var SQL in SQLList)
                        {
                            using (SQLiteCommand cmd = new SQLiteCommand(SQL, connection))
                            {
                                cmd.ExecuteNonQuery();
                            }
                        }
                        transaction.Commit();
                        return true;
                    }
                    catch (SQLiteException e)
                    {
                        transaction.Rollback();
                        throw new Exception("Transaction failed, rolled back.", e);
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，带参数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="cmdParms">SQL参数</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, SQLiteParameter[] cmdParms)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            using (SQLiteCommand cmd = new SQLiteCommand())
            {
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    return cmd.ExecuteNonQuery();
                }
                catch (SQLiteException e)
                {
                    throw new Exception("Error executing parameterized SQL.", e);
                }
            }
        }

        private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (SQLiteParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 删除指定表的所有数据
        /// </summary>
        /// <param name="TableName">指定的表名</param>
        /// <returns>影响的记录数</returns>
        public static int DelTableData(string TableName)
        {
            string SQLString = $"DELETE FROM '{TableName}'";
            return ExecuteSql(SQLString);
        }

        /// <summary>
        /// 执行查询语句，返回单个值
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>查询结果（object）</returns>
        public static object GetSingle(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    var result = cmd.ExecuteScalar();
                    return result == DBNull.Value ? null : result;
                }
                catch (SQLiteException e)
                {
                    throw new Exception("Error executing scalar query.", e);
                }
            }
        }

        public static object GetSingle(string sql, params SQLiteParameter[] parameters)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    if (parameters != null)
                    {
                        command.Parameters.AddRange(parameters);
                    }

                    object result = command.ExecuteScalar();
                    return result == DBNull.Value ? null : result;
                }
            }
        }


        /// <summary>
        /// 执行查询语句，返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>查询结果的DataTable</returns>
        public static DataTable QueryTable(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataTable dt = new DataTable();
                try
                {
                    connection.Open();
                    using (SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection))
                    {
                        command.Fill(dt);
                    }
                }
                catch (SQLiteException ex)
                {
                    throw new Exception("Error executing query.", ex);
                }
                return dt;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>查询结果的DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    using (SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection))
                    {
                        command.Fill(ds);
                    }
                }
                catch (SQLiteException ex)
                {
                    throw new Exception("Error executing query.", ex);
                }
                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句，返回空表格式
        /// </summary>
        /// <param name="sTableName">表名</param>
        /// <returns>空表的DataTable</returns>
        public static DataTable QueryNullTable(string sTableName)
        {
            string SQLString = $"SELECT * FROM {sTableName} LIMIT 0";
            return QueryTable(SQLString);
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SQLiteDataReader ExecuteReader(string strSQL)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
            try
            {
                connection.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (SQLiteException e)
            {
                throw new Exception("Error executing reader.", e);
            }
        }

        //public static SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] parameters)
        //{
        //    SQLiteConnection connection = new SQLiteConnection(connectionString);
        //    SQLiteCommand command = new SQLiteCommand(sql, connection);
        //    if (parameters != null)
        //    {
        //        command.Parameters.AddRange(parameters);
        //    }

        //    return command.ExecuteReader();
        //}

        public static SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] parameters)
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);

            try
            {
                // 打开连接
                connection.Open();

                SQLiteCommand command = new SQLiteCommand(sql, connection);
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                // CommandBehavior.CloseConnection 确保当 reader 被关闭时，连接也会自动关闭
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch
            {
                // 如果发生异常，确保关闭连接
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                }

                // 重新抛出异常，便于上层捕获
                throw;
            }
        }

        public static async Task<SQLiteDataReader> ExecuteReaderAsync(string sql, params SQLiteParameter[] parameters)
        {
            // 创建一个 TaskCompletionSource，用于包装同步的 ExecuteReader 方法
            return await Task.Run(() =>
            {
                SQLiteConnection connection = new SQLiteConnection(connectionString);
                try
                {
                    // 打开连接
                    connection.Open();

                    SQLiteCommand command = new SQLiteCommand(sql, connection);
                    if (parameters != null)
                    {
                        command.Parameters.AddRange(parameters);
                    }

                    // CommandBehavior.CloseConnection 确保当 reader 被关闭时，连接也会自动关闭
                    return command.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch
                {
                    // 确保发生异常时关闭连接
                    if (connection.State == System.Data.ConnectionState.Open)
                    {
                        connection.Close();
                    }

                    // 重新抛出异常供上层处理
                    throw;
                }
            });
        }


        /// <summary>
        /// 执行SQL语句清理SQLite数据库的多余空间
        /// </summary>
        public static void ClearSQLite()
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            using (SQLiteCommand cmd = new SQLiteCommand("VACUUM", connection))
            {
                try
                {
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (SQLiteException e)
                {
                    throw new Exception("Error cleaning SQLite database.", e);
                }
            }
        }

        // 查询SQLite数据库中的所有表名
        public static List<string> GetAllTables()
        {
            List<string> tableNames = new List<string>();

            // 创建数据库连接并打开
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                // SQL查询所有表
                string query = "SELECT name FROM sqlite_master WHERE type='table';";

                using (SQLiteCommand command = new SQLiteCommand(query, connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            // 将表名添加到列表中
                            tableNames.Add(reader["name"].ToString());
                        }
                    }
                }
            }

            return tableNames;
        }

        //////////////////////////////////////////////////////
    }
}
