using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

using BookShopOnline.Model;
using BookShopOnline.IDal;
using BookShopOnline.DBHelper;
using BookShopOnline.WebConfig;

namespace BookShopOnline.SQLServerDal
{
    public class OrdersDal:DBAccess,IOrders
    {
        #region 插入订单
        //事务过程：插入订单信息->初始化订单状态->插入订单清单->删除购物车
        public string InsertOrders(Orders orders,DataSet shoppingCartList)
        {
            if (shoppingCartList == null || shoppingCartList.Tables[0].Rows.Count == 0)
                return null;

            string orderID = CreateOrderID();

            using (SqlConnection conn = new SqlConnection(Config.SQLServerConnStr))
            {
                conn.Open();
                const string transName = "InsertOrders";
                SqlTransaction trans = conn.BeginTransaction(transName);
                try
                {
                    #region 插入订单信息
                    decimal totalBookPrice = (decimal)0;
                    foreach (DataRow shoppingCart in shoppingCartList.Tables[0].Rows)
                    {
                        totalBookPrice += Convert.ToDecimal(shoppingCart["TotalSellPrice"]);
                    }
                    SqlParameter[] parmInsertOrders =
                    {
                        new SqlParameter("@OrderID",orderID),
                        new SqlParameter("@UserID",orders.UserID),
                        new SqlParameter("@TipID",OrderStaticTip.WaitForPay),
                        new SqlParameter("@ReceiverName",orders.ReceiverName),
                        new SqlParameter("@ReceiverAddress",orders.ReceiverAddress),
                        new SqlParameter("@ReceiverPostalCode",orders.ReceiverPostalCode),
                        new SqlParameter("@ReceiverPhone",orders.ReceiverPhone),
                        new SqlParameter("@TotalBookPrice",totalBookPrice),
                        new SqlParameter("@HasPayedPrice",(decimal)0),
                        new SqlParameter("@PortTypeID",orders.PortTypeID),
                        new SqlParameter("@PayTypeID",orders.PayTypeID)
                    };
                    SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_InsertOrders.ToString(), parmInsertOrders);
                    #endregion

                    #region 初始化订单状态
                    int[] staticIDList ={ (int)OrderStatic.IsHasCancel, (int)OrderStatic.IsHasConfirmed, (int)OrderStatic.IsHasPayed, (int)OrderStatic.IsHasPorted };
                    foreach (int staticID in staticIDList)
                    {
                        SqlParameter[] parmInsertOrder_OrderStatic =
                      {
                           new SqlParameter("@OrderID",orderID),
                           new SqlParameter("@StaticID",staticID),
                           new SqlParameter("@YesOrNo",false)
                      };
                        SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_InsertOrder_OrderStatic.ToString(), parmInsertOrder_OrderStatic);
                    }
                    #endregion

                    #region 插入订单清单
                    foreach (DataRow shoppingCart in shoppingCartList.Tables[0].Rows)
                    {
                        SqlParameter[] parmInsertOrderDetail =
                      {
                           new SqlParameter("@OrderID",orderID),
                           new SqlParameter("@BookID",shoppingCart["BookID"]),
                           new SqlParameter("@Quatity",shoppingCart["Quatity"])
                       };
                        SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_InsertOrderDetail.ToString(), parmInsertOrderDetail);
                    }
                    #endregion

                    #region 删除购物车
                    SqlParameter parmDeleteShoppingCartByCartGuid = new SqlParameter("@CartGuid", shoppingCartList.Tables[0].Rows[0]["CartGuid"]);
                    SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_DeleteShoppingCartByCartGuid.ToString(), parmDeleteShoppingCartByCartGuid);
                    #endregion

                    trans.Commit();
                }
                catch
                {
                    trans.Rollback(transName);
                    orderID = null;
                }
            }
            return orderID;
        }
       #endregion

        #region 获取一条订单信息
        public DataSet SelectOrdersByOrderID(string orderID)
        {
            SqlParameter parm = new SqlParameter("@OrderID", orderID);

            return SQLHelper.GetDataSet(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_SelectOrdersByOrderID.ToString(), parm);
        }
        #endregion

        #region 获取所有订单
        public DataSet SelectAllOrders()
        {
            return SQLHelper.GetDataSet(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_SelectAllOrders.ToString(), null);
        }
        #endregion

        #region 获取订单状态
        public DataSet SelectOrderStaticByOrderID(string orderID)
        {
            SqlParameter parm = new SqlParameter("@OrderID", orderID);

            return SQLHelper.GetDataSet(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_SelectOrderStaticByOrderID.ToString(), parm);
        }
        #endregion

        #region 获取订单状态提示
        public DataSet SelectOrderStaticTip()
        {
            return SQLHelper.GetDataSet(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_SelectOrderStaticTip.ToString(), null);
        }
        #endregion

        #region 获取用户的订单
        public DataSet SelectOrdersByUserID(int userID)
        {
            SqlParameter parm = new SqlParameter("@UserID", userID);

            return SQLHelper.GetDataSet(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_SelectOrdersByUserID.ToString(), parm);
        }
        #endregion

        #region 按类别获取订单
        public DataSet SelectOrdersByOrderType(OrderType orderType)
        {
            SqlParameter parm =new SqlParameter("@OrderType", orderType);

            return base.GetDataSet(StoredProcedureName.sp_SelectOrdersByOrderType, parm);
        }
        #endregion

        #region 搜索订单
        public DataSet SelectOrdersBySearch(string orderID, string orderDate)
        {
            SqlParameter[] parms ={
                new SqlParameter("@OrderID",orderID),
                new SqlParameter("@OrderDate",orderDate)
            };

            return base.GetDataSet(StoredProcedureName.sp_SelectOrdersBySearch, parms);
        }
        #endregion

        #region 修改订单状态和提示
        public bool UpdateOrderStaicAndTip(string orderID,IList<Order_OrderStatic> order_OrderStaticList,int tipID)
        {
            bool result = false;
            SqlConnection conn = new SqlConnection(Config.SQLServerConnStr);

            conn.Open();
            string transName="UpdateOrderStaicAndTip";
            SqlTransaction trans=conn.BeginTransaction(transName);
            try
            {
                //更新订单状态
                foreach (Order_OrderStatic order_OrderStatic in order_OrderStaticList)
                {
                    SqlParameter[] parmsUpdateOrder_OrderStatic ={
                        new SqlParameter("@OrderID",orderID),
                        new SqlParameter("@StaticID",order_OrderStatic.StaticID),
                        new SqlParameter("@YesOrNo",order_OrderStatic.YesOrNo)
                    };

                    SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_UpdateOrder_OrderStatic.ToString(), parmsUpdateOrder_OrderStatic);
                }

                //更新订单状态提示
                SqlParameter[] parmsUpdateOrderStaticTip ={
                    new SqlParameter("@OrderID",orderID),
                    new SqlParameter("@TipID",tipID)
                };

                SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_UpdateOrderStaticTip.ToString(), parmsUpdateOrderStaticTip);

                trans.Commit();
                result = true;
            }
            catch
            {
                trans.Rollback(transName);
                result = false;
            }

            return result;
        }
        #endregion

        #region 付款
        //事务过程：更新已付款的金额->更新订单状态->更新订单状态提示
        public bool PayForOrders(int userID, string orderID, decimal payPrice)
        {
            bool result =false;

            using (SqlConnection conn = new SqlConnection(Config.SQLServerConnStr))
            {
                conn.Open();
                string transName = "PayForOrders";
                SqlTransaction trans= conn.BeginTransaction(transName);
                try
                {
                    SqlParameter[] parmsPayForOrders ={
                        new SqlParameter("@UserID",userID),
                        new SqlParameter("@OrderID",orderID),
                        new SqlParameter("@PayPrice",payPrice),
                    };
                  
                    SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, StoredProcedureName.sp_PayForOrders.ToString(), parmsPayForOrders);

                    trans.Commit();
                    result = true;
                }
                catch
                {
                    trans.Rollback(transName);
                    result = false;
                }
                finally { conn.Close(); }

                return result;
            }
           
        }
        #endregion

        #region 修改订单
        public int UpdateOrders(Orders orders)
        {
            SqlParameter[] parms ={
                new SqlParameter("@UserID",orders.UserID),
                new SqlParameter("@OrderID",orders.OrderID),
                new SqlParameter("@ReceiverName",orders.ReceiverName),
                new SqlParameter("@ReceiverPostalCode",orders.ReceiverPostalCode),
                new SqlParameter("@ReceiverPhone",orders.ReceiverPhone),
                new SqlParameter("@ReceiverAddress",orders.ReceiverAddress),
                new SqlParameter("@PortTypeID",orders.PortTypeID),
                new SqlParameter("@PayTypeID",orders.PayTypeID)
            };

            return SQLHelper.ExecuteNonQuery(Config.SQLServerConnStr, CommandType.StoredProcedure, StoredProcedureName.sp_UpdateOrders.ToString(), parms);
        }
        #endregion

        #region 辅助方法
        private string CreateOrderID()
        {
            string orderID =null;

            DateTime now = DateTime.Now;
            orderID =""+ now.Year + now.Month + now.Day + now.Hour + now.Minute + now.Second + now.Millisecond;

            Random random = new Random();
            orderID+=random.Next(100,900).ToString();

            return orderID;
        }
        #endregion
    }
}
