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

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

        #region 获取单个字段
        public ProductNormItem Get(int Id)
        {
            string key = "ProductNormItem:" + Id;
            if (RedisDbconn.Instance.Exists(key))
            {
                ProductNormItem obj = RedisDbconn.Instance.Get<ProductNormItem>(key);
                if (obj != null)
                {
                    return obj;
                }
            }
            WebCMSEntities db = new WebCMSEntities();
            ProductNormItem orderPro = db.ProductNormItem.FirstOrDefault(m => m.Id == Id);
            if (orderPro != null)
            {
                RedisDbconn.Instance.Set(key, orderPro);
                RedisDbconn.Instance.SetExpire(key, Library.function.get_Random(1800, 5400));
            }
            return orderPro;
        }
        #endregion


        #region 获取列表
        public List<ProductNormItem> GetList(int ProductId = 1, int pageNum = 1, int pageSize = 10)
        {
            string key = "ProductNormItem:" + ProductId;
            List<ProductNormItem> list = new List<ProductNormItem>();
            if (RedisDbconn.Instance.Exists(key))
            {
                list = RedisDbconn.Instance.GetList<ProductNormItem>(key, pageNum, pageSize);
                if (list.Count > 0)
                {
                    return list;
                }
            }
            List<ProductNormItem> newlist = new List<ProductNormItem>();
            WebCMSEntities db = new WebCMSEntities();
            var mysqllist = db.ProductNormItem.Where(m=>m.ProductId == ProductId).OrderByDescending(m => m.Id).ToList();
            if (mysqllist.Count > 0)
            {
                foreach (var sub in mysqllist)
                {
                    newlist.Add(sub);
                }
                RedisDbconn.Instance.Clear(key);
                foreach (ProductNormItem sub in newlist)
                {
                    RedisDbconn.Instance.AddRightList(key, sub);
                }
                RedisDbconn.Instance.SetExpire(key, Library.function.get_Random(1800, 5400));
            }
            db.Dispose();
            return newlist;
        }
        #endregion
    }
}
