using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RFrameGenerate.BLL.Recharge
{
    public class LockManage
    {
        private static object lockObj = new object();

        /// <summary>
        /// 获取锁
        /// </summary>
        public static LockModel GetLock(string prev, string orderNo)
        {
            string key = LockManage.GetKey(prev, orderNo);

            var value = LockManage.GetCahce<LockModel>(key);

            if (value != null) return value;

            lock (lockObj)
            {
                value = LockManage.GetCahce<LockModel>(key);

                if (value != null) return value;

                value = new LockModel() { IsSuccess = false, IsExecuted = false };

                LockManage.InertCache(key, value, 1);

                return value;
            }
        }

        /// <summary>
        /// 释放锁
        /// </summary>        
        public static void ReleaseLock(string prev, string orderNo, bool isExecuted = true, bool isSuccess = true)
        {
            string key = LockManage.GetKey(prev,orderNo);

            var value = LockManage.GetCahce<LockModel>(key);

            if (value == null) return;

            value.IsExecuted = isExecuted;
            value.IsSuccess = isSuccess;
        }

        #region 私有辅助函数
        private static string GetKey(string prev, string orderNo)
        {
            return string.Format("{0}_{1}", prev, orderNo);
        }
        private static void Remove(string key)
        {
            System.Web.HttpContext.Current.Cache.Remove(key);
        }

        private static T GetCahce<T>(string key)
        {
            if (string.IsNullOrEmpty(key)) return default(T);

            var value = System.Web.HttpContext.Current.Cache.Get(key);

            if (value == null) return default(T);

            if (value is T) return (T)value;

            return default(T);
        }

        private static void InertCache(string key, object value, int minutes)
        {
            LockManage.InertCache(key, value, new TimeSpan(0, minutes, 0));
        }

        private static void InertCache(string key, object value, TimeSpan span)
        {
            if (value == null) return;

            System.Web.HttpContext.Current.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, span);
        }

        #endregion
    }

    public class LockModel
    {
        public bool IsSuccess { get; set; }
        public bool IsExecuted { get; set; }

        public bool Verity()
        {
            if (this.IsExecuted && this.IsSuccess) return true;

            return false;
        }
    }
}
