using System;
using System.Collections.Generic;
using Library;
using System.Linq;
using MySystem.Models.Main1;

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

        #region 获取单个字段
        public StoreHouse Get(int Id)
        {
            WebCMSEntities db = new WebCMSEntities();
            StoreHouse order = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
            if (order != null)
            {
            }
            db.Dispose();
            return order;
        }
        #endregion

        #region 获取列表
        public List<int> GetList(int UserId, int pageNum = 1, int pageSize = 10)
        {
            string key = "StoreHouseList:" + UserId;
            if (UserId == 0)
            { 
                key = "StoreHouseList";
            }
            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.StoreHouse.Select(m => new { m.Id, m.LaveNum, m.UserId, m.Status }).Where(m => m.Status > -1);
            if (UserId > 0)
            {
                mysqllist = mysqllist.Where(m => m.UserId == UserId);
            }
            else
            { 
                mysqllist = mysqllist.Where(m => m.LaveNum > 0);
            }
            var resultlist = mysqllist.OrderByDescending(m => m.Id).ToList();
            if (resultlist.Count > 0)
            {
                foreach (var sub in resultlist)
                {
                    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));                
                return newlist;
            }
            db.Dispose();
            RedisDbconn.Instance.ReleaseLock(key + ":lock");
            return newlist;
        }
        #endregion
    }
}
