using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MeterVision.db
{
    public abstract class SQLiteHelper1
    {
        private static string DBFileName = AppDomain.CurrentDomain.BaseDirectory + "\\MeterVision.db";
        private static string connectionString = string.Format("data source={0}", DBFileName);

        /// <summary>
        /// 
        /// </summary>
        public SQLiteHelper1()
        {

        }

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <returns>返回连接字符串</returns>
        public static string GetConnStr()
        {
            return SQLiteHelper1.connectionString;
        }

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

        /// <summary>
        /// 从SQL语句中返回一个值
        /// </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();
                        int count = Convert.ToInt32(cmd.ExecuteScalar());
                        return count;
                    }
                    catch (SQLiteException e)
                    {
                        connection.Close();
                        throw 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();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (SQLiteException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></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);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (SQLiteException e)
                    {
                        throw 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;//cmdType;
            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)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                string SQLString = string.Format("delete from '{0}'", TableName);
                using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (SQLiteException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </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();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (SQLiteException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }


        /// <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();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataTable</returns>
        public static DataTable QueryTable(string SQLString)
        {

            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                    //ex.State = 
                    //connection.Close();
                }
                return ds.Tables[0];
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="ds"></param>
        /// <param name="sTName"></param>
        public static void QueryD(string SQLString, DataSet ds, string sTName)
        {

            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                //DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    //command.Fill(ds, "ds");
                    command.Fill(ds, sTName);
                }
                catch (SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                    //ex.State = 
                    //connection.Close();
                }
                //return ds.Tables[0];
            }
        }

        /// <summary>
        /// 执行查询语句，返回表的空表格式
        /// </summary>
        /// <param name="sTableName">表名</param>
        /// <returns>DataTable</returns>
        public static DataTable QueryNullTable(string sTableName)
        {
            string SQLString = string.Format("select * from {0} Limit 0", sTableName);
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                    //ex.State = 
                    //connection.Close();
                }
                return ds.Tables[0];
            }
        }
        /// <summary>
        /// 增加新记录
        /// </summary>
        /// <param name="sTableName"></param>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static bool AddNewRow(string sTableName, DataRow dr)
        {
            try
            {
                string SQLString = string.Format("select * from {0} Limit 0", sTableName);
                SQLiteDataAdapter da = new SQLiteDataAdapter(SQLString, connectionString);
                SQLiteCommandBuilder scb = new SQLiteCommandBuilder(da);
                DataRow[] drList = new DataRow[] { dr };
                da.Update(drList);
                scb.Dispose();
                scb = null;
                return true;
            }
            catch
            {
                return false;
            }
            //return true;
        }
        /// <summary>
        /// 产生新行
        /// </summary>
        /// <param name="sTableName"></param>
        /// <returns></returns>
        public static DataRow CreatNewRow(string sTableName)
        {
            try
            {
                string SQLString = string.Format("select * from {0} Limit 0", sTableName);
                DataTable dt = QueryTable(SQLString);
                DataRow dr = dt.NewRow();
                //dt.Dispose();
                //dt = null;
                return dr;
            }
            catch (SQLiteException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取表的结构
        /// </summary>
        /// <param name="sTableName">表名</param>
        /// <returns></returns>
        public static DataTable GetDTFormat(string sTableName)
        {
            string SQLString = string.Format("select * from {0} Limit 0", sTableName);
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (SQLiteException ex)
                {
                    throw new Exception(ex.Message);
                    //ex.State = 
                    //connection.Close();
                }
                return ds.Tables[0];
            }
        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </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();
                SQLiteDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (SQLiteException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行语句清理多余空间
        /// </summary>
        public static void ClearSQLite()
        {
            SQLiteConnection connection = new SQLiteConnection(connectionString);
            try
            {
                using (SQLiteCommand cmd = new SQLiteCommand("VACUUM", connection))
                {
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (SQLiteException e)
            {
                throw e;
            }
        }
    }//--SqlliteApp结束

}
