using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;

namespace Mall.AOP.CustomerAttribute
{
    /// <summary>
    /// 事务属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class TransactionCallHandlerAttribute : BaseInterceptorAttribute
    {
        /// <summary>
        /// 超时时间
        /// </summary>
        public int Timeout { get; set; }

        /// <summary>
        /// 事务范围
        /// </summary>
        public TransactionScopeOption ScopeOption { get; set; }

        /// <summary>
        /// 事务隔离级别
        /// </summary>
        public IsolationLevel IsolationLevel { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public TransactionCallHandlerAttribute()
        {
            Timeout = 30;
            ScopeOption = TransactionScopeOption.Required;
            IsolationLevel = IsolationLevel.ReadCommitted;
        }

        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public override Action Do(IInvocation invocation, Action action)
        {
            return () =>
            {
                Console.WriteLine("TransactionCallHandlerAttribute1");

                TransactionOptions transactionOptions = new TransactionOptions
                {
                    //设置事务隔离级别
                    IsolationLevel = this.IsolationLevel,
                    //设置事务超时时间为60秒
                    Timeout = new TimeSpan(0, 0, this.Timeout)
                };
                using (TransactionScope scope = new TransactionScope(this.ScopeOption, transactionOptions))
                {
                    try
                    {
                        //实现事务性工作
                        action.Invoke();
                        var result = invocation.ReturnValue;
                        bool.TryParse((result != null ? result.ToString() : ""),out bool IsSuccess);
                        if (IsSuccess)
                        {
                            scope.Complete();
                        }
                    }
                    catch (Exception ex)
                    {
                        // 记录异常
                        throw ex;
                    }
                }
                Console.WriteLine("TransactionCallHandlerAttribute2");
            };
        }
    }
}
