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

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

        #region 获取单个字段
        public Products Get(int Id)
        {
            // string key = "Products:" + Id;
            // if (RedisDbconn.Instance.Exists(key))
            // {
            //     Products obj = RedisDbconn.Instance.Get<Products>(key);
            //     if (obj != null)
            //     {
            //         return obj;
            //     }
            // }
            WebCMSEntities db = new WebCMSEntities();
            Products orderPro = db.Products.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<int> GetList(int pageNum = 1, int pageSize = 10)
        {
            string key = "ProductsList";
            List<int> list = new List<int>();
            if (RedisDbconn.Instance.Exists(key))
            {
                list = RedisDbconn.Instance.GetList<int>(key, pageNum, pageSize);
                if (list.Count > 0)
                {
                    return list;
                }
            }
            List<int> newlist = new List<int>();
            RedisDbconn.Instance.GetLock(key + ":lock");
            WebCMSEntities db = new WebCMSEntities();
            var mysqllist = db.Products.Select(m => new { m.Id, m.Status, m.Sort }).Where(m => m.Status == 1).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
            if (mysqllist.Count > 0)
            {
                foreach (var sub in mysqllist)
                {
                    newlist.Add(sub.Id);
                }
                RedisDbconn.Instance.Clear(key);
                foreach (int sub in newlist)
                {
                    RedisDbconn.Instance.AddRightList(key, sub);
                }
                RedisDbconn.Instance.SetExpire(key, Library.function.get_Random(1800, 5400));
            }
            db.Dispose();
            RedisDbconn.Instance.ReleaseLock(key + ":lock");
            return newlist;
        }
        #endregion
    }
}
