using System;
using System.Data.SqlClient;
using System.Data;
using System.Reflection;
using Logger;
using System.Collections.Generic;

namespace WebApi.Helpers
{
    public class SqlServer
    {
        public static bool ExecuteProcedure(string ProcedureName, SqlParameter[] sqlParameters, out DataTable dt, out string errorMessage)
        {
            bool result = false;
            dt = new DataTable();
            errorMessage = "";
            using (SqlConnection sqlConnection = new SqlConnection(Tools.AppConfigManage.ReadConfig("ConnectionString")))
            {
                try
                {
                    sqlConnection.Open();
                    // 开始事务
                    SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
                    try
                    {
                        using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
                        {
                            sqlCommand.Transaction = sqlTransaction; // 将事务附加到SqlCommand对象
                            sqlCommand.CommandType = CommandType.StoredProcedure;
                            sqlCommand.CommandText = ProcedureName;

                            if (sqlParameters != null)
                            {
                                for (int i = 0; i < sqlParameters.Length; i++)
                                {
                                    sqlCommand.Parameters.Add(sqlParameters[i]);
                                }
                            }

                            // 创建SqlDataAdapter并关联SqlCommand
                            using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                            {
                                // 填充DataTable
                                sqlDataAdapter.Fill(dt);
                            }
                            // 如果执行成功，提交事务
                            sqlTransaction.Commit();
                            result = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        // 如果执行过程中出现异常，回滚事务
                        try
                        {
                            sqlTransaction.Rollback();
                            errorMessage = ProcedureName + "存储过程执行失败，事务已回滚。错误信息：" + ex.Message;
                            Log.Error(ProcedureName + "存储过程执行失败，事务已回滚。错误信息：" + ex.Message);
                        }
                        catch (Exception exRollback)
                        {
                            // 如果回滚操作也失败，记录回滚异常
                            errorMessage = ProcedureName + "事务回滚失败。错误信息：" + exRollback.Message;
                            Log.Error(ProcedureName + "事务回滚失败。错误信息：" + exRollback.Message);
                        }
                        finally
                        {
                            if (sqlConnection.State == ConnectionState.Open)
                            {
                                sqlConnection.Close();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                    Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
                }
                finally
                {
                    if (sqlConnection.State == ConnectionState.Open)
                    {
                        sqlConnection.Close();
                    }
                }
            }
            return result;
        }
        public static bool ExecuteSql(string sql, out DataTable dt, out string errorMessage)
        {
            bool result = false;
            dt = new DataTable();
            errorMessage = "";
            using (SqlConnection sqlConnection = new SqlConnection(Tools.AppConfigManage.ReadConfig("ConnectionString")))
            {
                try
                {
                    sqlConnection.Open();
                    // 开始事务
                    using (SqlTransaction sqlTransaction = sqlConnection.BeginTransaction())
                    {
                        using (SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection, sqlTransaction))
                        {
                            sqlCommand.CommandType = CommandType.Text; // 设置为执行文本命令

                            // 创建SqlDataAdapter并关联SqlCommand
                            using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                            {
                                // 填充DataTable
                                sqlDataAdapter.Fill(dt);
                            }

                            // 如果执行成功，提交事务
                            sqlTransaction.Commit();
                            result = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                    Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
                }
                finally
                {
                    if (sqlConnection.State == ConnectionState.Open)
                    {
                        sqlConnection.Close();
                    }
                }
            }
            return result;
        }

        public static bool ExecuteProcedure(string ProcedureName, Dictionary<string, Object> sqlParametersDictionary, out DataTable dt, out string errorMessage)
        {
            // 处理字典数据 转为 SqlParameter
            List <SqlParameter> parameterList = new List <SqlParameter> ();
            foreach (KeyValuePair<string,Object> param in sqlParametersDictionary)
            {
                parameterList.Add(new SqlParameter("@" + param.Key, param.Value));
            }
            SqlParameter[] sqlParameters = parameterList.ToArray();

            bool result = false;
            dt = new DataTable();
            errorMessage = "";
            using (SqlConnection sqlConnection = new SqlConnection(Tools.AppConfigManage.ReadConfig("ConnectionString")))
            {
                try
                {
                    sqlConnection.Open();
                    // 开始事务
                    SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
                    try
                    {
                        using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
                        {
                            sqlCommand.Transaction = sqlTransaction; // 将事务附加到SqlCommand对象
                            sqlCommand.CommandType = CommandType.StoredProcedure;
                            sqlCommand.CommandText = ProcedureName;

                            if (sqlParameters != null)
                            {
                                for (int i = 0; i < sqlParameters.Length; i++)
                                {
                                    sqlCommand.Parameters.Add(sqlParameters[i]);
                                }
                            }

                            // 创建SqlDataAdapter并关联SqlCommand
                            using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                            {
                                // 填充DataTable
                                sqlDataAdapter.Fill(dt);
                            }
                            // 如果执行成功，提交事务
                            sqlTransaction.Commit();
                            result = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        // 如果执行过程中出现异常，回滚事务
                        try
                        {
                            sqlTransaction.Rollback();
                            errorMessage = ProcedureName + "存储过程执行失败，事务已回滚。错误信息：" + ex.Message;
                            Log.Error(ProcedureName + "存储过程执行失败，事务已回滚。错误信息：" + ex.Message);
                        }
                        catch (Exception exRollback)
                        {
                            // 如果回滚操作也失败，记录回滚异常
                            errorMessage = ProcedureName + "事务回滚失败。错误信息：" + exRollback.Message;
                            Log.Error(ProcedureName + "事务回滚失败。错误信息：" + exRollback.Message);
                        }
                        finally
                        {
                            if (sqlConnection.State == ConnectionState.Open)
                            {
                                sqlConnection.Close();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.Message;
                    Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
                }
                finally
                {
                    if (sqlConnection.State == ConnectionState.Open)
                    {
                        sqlConnection.Close();
                    }
                }
            }
            return result;
        }
    }
}
