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

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

        #region 获取列表
        public List<UserAccountRecord> GetList(int UserId, string Kind, string TradeMonth, int pageNum = 1, int pageSize = 10)
        {
            string key = "UserAccountList:" + UserId + ":" + Kind + ":" + TradeMonth;
            List<UserAccountRecord> list = new List<UserAccountRecord>();
            if (RedisDbconn.Instance.Exists(key))
            {
                list = RedisDbconn.Instance.GetList<UserAccountRecord>(key, pageNum, pageSize);
                if (list.Count > 0)
                {
                    return list;
                }
            }
            WebCMSEntities db = new WebCMSEntities();
            DateTime start = DateTime.Parse(TradeMonth.Substring(0, 4) + "-" + TradeMonth.Substring(4, 2) + "-01 00:00:00");
            DateTime end = start.AddMonths(1);
            IQueryable<UserAccountRecord> mysqllist = db.UserAccountRecord;
            if (Kind == "1")
            {
                mysqllist = mysqllist.Where(m => m.UserId == UserId && m.CreateDate >= start && m.CreateDate < end && (m.ChangeType == 0 || m.ChangeType == 50 || m.ChangeType == 112));
            }
            else
            {
                mysqllist = mysqllist.Where(m => m.UserId == UserId && m.CreateDate >= start && m.CreateDate < end && m.ChangeType == 2 && m.Status == 1);
            }
            List<UserAccountRecord> newlist = new List<UserAccountRecord>();
            var resultlist = mysqllist.OrderByDescending(m => m.Id).ToList();
            if (resultlist.Count > 0)
            {
                foreach (var sub in resultlist)
                {
                    newlist.Add(sub);
                }
                RedisDbconn.Instance.Clear(key);
                foreach (var sub in newlist)
                {
                    RedisDbconn.Instance.AddRightList(key, sub);
                }
                RedisDbconn.Instance.SetExpire(key, Library.function.get_Random(60, 120));
            }
            db.Dispose();
            return newlist;
        }
        #endregion

    }
}
