using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using DapperORM;
using DapperORM.Common.Models;
using PushInfo.Core.Models.Tables;
using PushInfo.Core.IDAL;
namespace PushInfo.Core.DAL.MySql
{
    public class PushMessageDAL : BaseRepository<Push_Message>, IPushMessageDAL
    {
        #region 添加发送记录
        /// <summary>
        /// 添加发送记录
        /// </summary>
        /// <param name="obj">数据实体</param>
        /// <returns></returns>
        public ResultModel Add(Push_Message obj)
        {
            return InsertAsync(obj).Result;
        }
        #endregion

        #region 查询集合
        /// <summary>
        /// 查询集合
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <param name="select">查询字段</param>
        /// <param name="sort">排序</param>
        /// <returns></returns>
        public ResultModel<IEnumerable<Push_Message>> GetList(Expression<Func<Push_Message, bool>> where = null, Expression<Func<Push_Message, object>> select = null, IDictionary<string, bool> sort = null)
        {
            return FetchAsync(where, select, sort).Result;
        }
        #endregion

        #region 查询推送用户的最新一条记录
        /// <summary>
        /// 查询推送用户的最新一条记录
        /// </summary>
        /// <returns></returns>
        public ResultModel<IEnumerable<Push_Message>> GetUserLastPush()
        {
            string sql = @"select * 
                              from (select p.*,IF(@gid= User_Id , @rank:=@rank+1,@rank:=1)  as Sort,
		                                       @gid :=User_Id 
                                      from push_message p,(select @gid:=NULL,@rank:=0) D
                                     where  Is_Successed = 1 and Is_Deleted = 0
                                  ORDER BY User_Id,Send_Time DESC
                                   ) t1
                              where t1.Sort = 1";
            Dictionary<string, object> param = new Dictionary<string, object>();
            return QueryAsync<Push_Message>(sql, param).Result;
        }
        #endregion

        #region 局部更新
        /// <summary>
        /// 局部更新
        /// </summary>
        /// <param name="model">数据体</param>
        /// <param name="updateExp">更新字段</param>
        /// <param name="whereExp">更新条件</param>
        /// <returns></returns>
        public ResultModel UpdatePartail(Push_Message model, Expression<Func<Push_Message, object>> updateExp, Expression<Func<Push_Message, bool>> whereExp)
        => UpdatePartailAsync<Push_Message>(model, updateExp, whereExp).Result;
        #endregion
    }
}
