using DapperExtensions;
using MWS.Data.InterFace;
using MWS.Library;
using MWS.Library.Common;
using MWS.Library.Common.MD5Poxy;
using MWS.Library.Common.Module;
using MWS.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MWS.Data.Manager
{
    public class UserManager : DapperHelper<User>, IUser
    {
        /// <summary>
        /// 登录系统
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <returns>信息</returns>
        public async Task<ResultModel> Login(string account, string password)
        {
            try
            {
                //password = CEncoder.Encode(password);

                var sqlStr = @"SELECT * FROM user WHERE account =@Account AND password =@Password";

                var task = await Task.Run(() =>
                {
                    return Query<User>(sqlStr, new { Account = account, Password = password });
                });
                bool result = task.Any();
                if (result)
                    return new ResultModel() { Success = result, Data = task.FirstOrDefault() };
                else
                    return new ResultModel() { Success = result, Message = "账号或密码错误,请确认!" };

            }
            catch (Exception ex)
            {  
                LogHelper.WriteLog("登录错误", ex);
                return new ResultModel() { Success = false, ErrorCode = ex.Message };
            }
        }



        /// <summary>
        /// 根据账户获取用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public async Task<User> GetModelByAccount(string account)
        {
            try
            {
                var sqlStr = @"SELECT * FROM user WHERE account = @Account";
                var task = await Task.Run(() =>
                {
                    return Query<User>(sqlStr, new { Account = account }).FirstOrDefault();
                });

                return task;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("账户获取账户信息", ex);
                return null;
            }
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="keyword">检索关键字</param>
        /// <param name="sortingProperty">排序字段 默认Id</param>
        /// <param name="ascending">是否升序 默认false</param>
        /// <returns></returns>
        public async Task<List<User>> GetModels(string keyword, string sortingProperty = "Id", bool ascending = false)
        {
            //条件 Eq 等于 Gt 大于 Ge 大于或等于 Lt 小于 Le 小于或等于 Like 模糊
            IList<IPredicate> predList = new List<IPredicate>();
            if (!keyword.IsNullOrEmptyOrWhiteSpace())
            {
                predList.Add(Predicates.Field<User>(p => p.UserName, Operator.Like, keyword));
                predList.Add(Predicates.Field<User>(p => p.Account, Operator.Like, keyword));
            }
            IPredicateGroup predGroup = Predicates.Group(GroupOperator.Or, predList.ToArray());
            //排序
            IList<ISort> sort = new List<ISort>
            {
                new Sort { PropertyName = sortingProperty, Ascending = ascending }
            };
            var task = await Task.Run(() =>
            {
                return GetAll<User>(predGroup, sort);
            });
            return task.ToList();
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="keyword">检索关键字</param>
        /// <param name="totalCount">总条数</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页尺寸</param>
        /// <param name="sortingProperty">排序字段 默认Id</param>
        /// <param name="ascending">是否升序 默认false</param>
        /// <returns></returns>
        public List<User> GetPagingModels(string keyword, out int totalCount, int pageIndex = 1, int pageSize = 20, string sortingProperty = "Id", bool ascending = false)
        {
            //条件 Eq 等于 Gt 大于 Ge 大于或等于 Lt 小于 Le 小于或等于 Like 模糊
            IList<IPredicate> predList = new List<IPredicate>();
            if (!keyword.IsNullOrEmptyOrWhiteSpace())
            {
                predList.Add(Predicates.Field<User>(p => p.UserName, Operator.Like, keyword));
                predList.Add(Predicates.Field<User>(p => p.Account, Operator.Like, keyword));
            }
            IPredicateGroup predGroup = Predicates.Group(GroupOperator.Or, predList.ToArray());
            //排序
            IList<ISort> sort = new List<ISort>
            {
                new Sort { PropertyName = sortingProperty, Ascending = ascending }
            };
            return GetPage<User>(predGroup, sort, pageIndex, pageSize, out totalCount).ToList();
        }

        public int UpdatePassWord(string account, string password)
        {
            try
            {
                var sqlStr = @"Update  user set password = @Password  WHERE account = @Account";
               
                return Execute<User>(sqlStr, new { Password=password, Account = account });
            
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("更新密码失败：", ex);
                return 0;
            }
        }

        public PageData<User> GetAll(string kewWord , int pageIndex, int pageSize)
        {
            PageData<User> pd = new PageData<User>()
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            try
            {
                string sql = "Select * From user WHERE 1 = 1 ";
                string countsql = "Select count(1) From user WHERE 1 = 1 ";
                string sqlWhe = "";
                if (!string.IsNullOrEmpty(kewWord))
                {
                    sqlWhe += " and username like '%"+ kewWord + "%' ";
                }
               
                sql += sqlWhe;
                // 查询条件
                sql += " order by Id ";
                countsql += sqlWhe;
                pd.TotalCount = Query<int>(countsql).SingleOrDefault();
                string pageSql = sql + " limit " + (pageIndex - 1) * pageSize + "," + pageSize;
                pd.Data = Query<User>(pageSql);
                return pd;
            }
            catch (Exception ex)
            {
                pd.Data = null;
                return pd;
            }
        }
        /// <summary>
        /// 获取总数
        /// </summary>
        /// <param name="kewWord"></param>
        /// <returns></returns>
        public int GetAllRecordsCount(string kewWord)
        {

            string countsql = "Select count(1) From user WHERE 1 = 1 ";
            string sqlWhe = "";
            if (string.IsNullOrEmpty(kewWord))
            {
                sqlWhe += " and username like '%" + kewWord + "%' ";
            }

            countsql += sqlWhe;
            return Query<int>(countsql).SingleOrDefault();
        }

        public int InsertUser(User user)
        {
            string sqlInsert = @"INSERT INTO user (role,username,account,password,islocked,time) VALUES (@Role,@UserName,@Account,@Password,@IsLocked,@CreationTime)";
            return Execute<int>(sqlInsert, new { Role = user.Role,UserName=user.UserName,Account=user.Account,Password=user.Password,IsLocked=user.IsLocked, CreationTime=user.Time });
        }
    }
}
