using System;
using System.Collections.Generic;
using Library;
using System.Linq;
using MySystem.MainModels;

namespace MySystem
{
    public class PosMerchantTradeSummaryDbconn
    {
        public readonly static PosMerchantTradeSummaryDbconn Instance = new PosMerchantTradeSummaryDbconn();
        public PosMerchantTradeSummaryDbconn()
        { }

        // TODO:读取很慢，感觉redis没生效

        #region 获取单个字段
        
        public decimal GetTrade(int MerchantId)
        {
            string key = "PosMerchantAmount:" + MerchantId; //总交易
            string obj = RedisDbconn.Instance.Get<string>(key);
            if (!string.IsNullOrEmpty(obj))
            {
                return decimal.Parse(function.CheckNum(obj));
            }
            decimal amt = 0;
            WebCMSEntities db = new WebCMSEntities();
            bool check = db.PosMerchantTradeSummay.Any(m => m.MerchantId == MerchantId);
            if (check)
            {
                amt = db.PosMerchantTradeSummay.Where(m => m.MerchantId == MerchantId).Sum(m => m.TradeAmount);
            }
            RedisDbconn.Instance.Set(key, amt.ToString());
            RedisDbconn.Instance.SetExpire(key, function.get_Random(3600, 7200));
            db.Dispose();
            return amt;
        }
        public decimal GetDateTimeTrade(int MerchantId, string TradeDate)
        {
            if (DateTime.Now.Day == 1 && TradeDate.Length == 6)
            {
                TradeDate = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            }
            string key = "PosMerchantAmount:" + MerchantId + ":" + TradeDate; //总交易
            string obj = RedisDbconn.Instance.Get<string>(key);
            if (!string.IsNullOrEmpty(obj))
            {
                return decimal.Parse(function.CheckNum(obj));
            }
            decimal amt = 0;
            WebCMSEntities db = new WebCMSEntities();
            if (TradeDate.Length == 8)
            {
                bool check = db.PosMerchantTradeSummay.Any(m => m.MerchantId == MerchantId && m.TradeDate == TradeDate);
                if (check)
                {
                    amt = db.PosMerchantTradeSummay.Where(m => m.MerchantId == MerchantId && m.TradeDate == TradeDate).Sum(m => m.TradeAmount);
                }
                RedisDbconn.Instance.Set(key, amt.ToString());
            }
            else
            { 
                bool check = db.PosMerchantTradeSummay.Any(m => m.MerchantId == MerchantId && m.TradeMonth == TradeDate);
                if (check)
                {
                    amt = db.PosMerchantTradeSummay.Where(m => m.MerchantId == MerchantId && m.TradeMonth == TradeDate).Sum(m => m.TradeAmount);
                }
                RedisDbconn.Instance.Set(key, amt.ToString());
            }
            RedisDbconn.Instance.SetExpire(key, function.get_Random(3600, 7200));
            db.Dispose();
            return amt;
        }
        #endregion

    }
}
