using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using WCS.BLL.Config;
using WCS.BLL.DbModels;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.BLL.Tool;
using WCS.DAL;
using WCS.DAL.Db.AuthDb;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.MXBackgroundThread;
using WCS.Model.ApiModel.User;

namespace WCS.BLL.Services.Service
{
    public class UserService : IUserService
    {
        public UserService() { }

        public async Task<ResponseCommon<List<UserBase>>> GetUsers(GetUsersRequest request)
        {
            try
            {
                var users = await AuthDbHelp.db.Queryable<UserBase>()
                        .WhereIF(!string.IsNullOrWhiteSpace(request.Info), o => o.LoginName.Contains(request.Info.Trim()))
                        .OrderBy(o => o.Id)
                        .ToListAsync();
                //返回内容密码处理
                if (users != null && users.Count > 0)
                {
                    users.ForEach(t =>
                    {
                        t.Password = "******";
                    });
                }
                var response = new ResponseCommon<List<UserBase>>()
                {
                    Code = 200,
                    Message = "success",
                    Data = users
                };
                return response;
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<List<UserBase>>()
                {
                    Code = 200,
                    Message = "success",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<object>> AddUser(AddUserRequest<UserModel> request)
        {
            try
            {
                var user = await AuthDbHelp.db.Queryable<UserBase>()
                                    .Where(t => t.LoginName == request.User.LoginName)
                                    .FirstAsync();
                if (request.AddOrUpdate == AddOrUpdate.Update)
                {
                    if (user == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"更新用户信息失败：用户{user.LoginName}不存在！",
                            Data = null
                        };
                    }
                    else
                    {
                        user.Password = request.User.Password;
                        user.LoginName = request.User.LoginName;
                        user.RoleIds = request.User.RoleIds;
                        var rowNum = await AuthDbHelp.db.Updateable(user).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"更新用户信息失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"更新用户信息成功！",
                                Data = null
                            };
                        }
                    }
                }

                else if (request.AddOrUpdate == AddOrUpdate.Add)
                {
                    if (user != null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"添加用户失败：用户{request.User.LoginName}已存在",
                            Data = null
                        };
                    }
                    else
                    {
                        var newUser = new UserBase()
                        {
                            LoginName = request.User.LoginName.ToLower(),
                            Password = request.User.Password,
                            RoleIds = request.User.RoleIds,
                            IsAdmin = request.User.IsAdmin,
                            Time = request.User.Time
                        };
                        var rowNum = await AuthDbHelp.db.Insertable(newUser).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"添加用户失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"添加用户成功！",
                                Data = null
                            };
                        }
                    }
                }
                else if (request.AddOrUpdate == AddOrUpdate.Delete)
                {
                    if (user == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"删除用户失败：用户{request.User.LoginName}不存在",
                            Data = null
                        };
                    }
                    else
                    {
                        var rowNum = await AuthDbHelp.db.Deleteable(user).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"删除用户失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"删除用户成功！",
                                Data = null
                            };
                        }
                    }
                }
                else
                {
                    var response = new ResponseCommon<Object>
                    {
                        Code = 300,
                        Message = "不支持的操作！",
                        Data = null
                    };
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }
        public async Task<ResponseCommon<List<RoleBase>>> GetRoles(GetUsersRequest request)
        {
            try
            {
                var users = await AuthDbHelp.db.Queryable<RoleBase>()
                        .WhereIF(!string.IsNullOrWhiteSpace(request.Info), o => o.Name.Contains(request.Info.Trim()))
                        .OrderBy(o => o.Id)
                        .ToListAsync();
                var response = new ResponseCommon<List<RoleBase>>()
                {
                    Code = 200,
                    Message = "success",
                    Data = users
                };
                return response;
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<List<RoleBase>>()
                {
                    Code = 200,
                    Message = "success",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<object>> AddRole(AddRoleRequest<RoleModel> request)
        {
            try
            {
                var Role = await AuthDbHelp.db.Queryable<RoleBase>()
                                    .Where(t => t.Name == request.Role.Name)
                                    .FirstAsync();
                if (request.AddOrUpdate == AddOrUpdate.Update)
                {
                    if (Role == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"更新角色信息失败：角色{Role.Name}不存在！",
                            Data = null
                        };
                    }
                    else
                    {
                        Role.IsAdmin = request.Role.IsAdmin;
                        Role.Name = request.Role.Name;
                        Role.Auths = request.Role.Auths;
                        Role.AuthNames = request.Role.AuthNames;
                        Role.Time = request.Role.Time;
                        var rowNum = await AuthDbHelp.db.Updateable(Role).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"更新角色信息失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"更新角色信息成功！",
                                Data = null
                            };
                        }
                    }
                }

                else if (request.AddOrUpdate == AddOrUpdate.Add)
                {
                    if (Role != null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"添加角色失败：角色{request.Role.Name}已存在",
                            Data = null
                        };
                    }
                    else
                    {
                        var newRole = new RoleBase()
                        {
                            Name = request.Role.Name,
                            Auths = request.Role.Auths,
                            IsAdmin = request.Role.IsAdmin,
                            Time = request.Role.Time
                        };
                        var rowNum = await AuthDbHelp.db.Insertable(newRole).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"添加角色失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"添加角色成功！",
                                Data = null
                            };
                        }
                    }
                }
                else if (request.AddOrUpdate == AddOrUpdate.Delete)
                {
                    if (Role == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"删除角色失败：角色{request.Role.Name}不存在",
                            Data = null
                        };
                    }
                    else
                    {
                        var isContains = AuthDbHelp.db.Queryable<UserBase>().Select(o => o.RoleIds).ToList().SelectMany(o => o).Contains(Role.Id);
                        if (isContains)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"删除角色失败：角色{request.Role.Name}已被用户使用！",
                                Data = null
                            };
                        }
                        var rowNum = await AuthDbHelp.db.Deleteable(Role).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"删除角色失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"删除角色成功！",
                                Data = null
                            };
                        }
                    }
                }
                else
                {
                    var response = new ResponseCommon<Object>
                    {
                        Code = 300,
                        Message = "不支持的操作！",
                        Data = null
                    };
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<UserBase>> UserLogin(UserLoginRequest request)
        {
            try
            {
                UserBase user = null;

                if (request.IsNoLogin)//不登录模式 不校验密码
                {
                    user = await AuthDbHelp.db.Queryable<UserBase>()
                                               .Where(t => t.LoginName == "admin")
                                               .FirstAsync();
                }
                else//登录模式需要校验密码
                {
                    //#region 盟讯公司登录接入系统接口
                    //if (LocalFile.Config.IsMx)
                    //{
                    //    #region 调用接口 接入盟讯公司登录
                    //    try
                    //    {
                    //        var body = new
                    //        {
                    //            uername = request.UserName,
                    //            password = request.PassWord,
                    //        };
                    //        var Result = ApiHelp.GetDataFromHttpShortTime<MXResponse>("http://192.168.2.23:9213/integrate/login/queryGenerLogin", body, "POST", true);
                    //        //账号密码验证成功
                    //        if (Result != null && Result.code == 200)
                    //        {
                    //            //判断系统中是否有对应用户
                    //            user = await AuthDbHelp.db.Queryable<UserBase>()
                    //             .Where(t => t.LoginName == request.UserName)
                    //             .FirstAsync();
                    //            //Mes登录成功后wcs这边也添加一个用户
                    //            if (user == null)
                    //            {
                    //                user = new UserBase()
                    //                {
                    //                    LoginName = request.UserName,
                    //                    Password = request.PassWord,
                    //                    RoleIds = new List<int>() { 2 },
                    //                    IsAdmin = false,
                    //                    Time = DateTime.Now,
                    //                };
                    //                await AuthDbHelp.db.Insertable(user).ExecuteCommandAsync();
                    //            }
                    //            else if (user.Password != request.PassWord)
                    //            {
                    //                user.Password = request.PassWord;
                    //                await AuthDbHelp.db.Updateable(user).ExecuteCommandAsync();
                    //            }
                    //        }
                    //        //账号密码验证失败
                    //        else
                    //        {

                    //        }
                    //    }
                    //    catch (Exception e)
                    //    {

                    //    }
                    //    #endregion
                    //}
                    //#endregion
                    if (user == null)
                        user = await AuthDbHelp.db.Queryable<UserBase>()
                                 .Where(t => t.LoginName == request.UserName.ToLower())
                                 .FirstAsync();
                    if (user == null)
                    {

                        return new ResponseCommon<UserBase>()
                        {
                            Code = 201,
                            Message = $"登录失败:用户名[{request.UserName}]不存在或密码输入错误！",
                            Data = null
                        };
                    }
                    else if (user.Password != request.PassWord)
                    {
                        return new ResponseCommon<UserBase>()
                        {
                            Code = 201,
                            Message = $"登录失败:密码错误！",
                            Data = null
                        };
                    }
                }

                //加载用户的权限
                if (user != null)
                {
                    if (user.IsAdmin)
                    {
                        user.GetRoles = await AuthDbHelp.db.Queryable<RoleBase>()
                                                   .OrderBy(o => o.Id)
                                                   .ToListAsync();
                    }
                    else if (user.RoleIds == null || !user.RoleIds.Any())
                    {
                        user.GetRoles = new List<RoleBase>();
                    }
                    else
                    {
                        user.GetRoles = await AuthDbHelp.db.Queryable<RoleBase>()
                                               .Where(t => user.RoleIds.Contains(t.Id))
                                               .OrderBy(o => o.Id)
                                               .ToListAsync();
                    }
                }

                //返回字串不返回密码
                user.Password = "***";
                request.PassWord = "***";

                var response = new ResponseCommon<UserBase>()
                {
                    Code = 200,
                    Message = "success",
                    Data = user
                };
                //登录成功
                if (request.DeviceType == "WCS前端" && request.GroupNames != null)
                {
                    var shelves = ShelfManager.Shelves.Where(t => request.GroupNames.Contains(t.GroupName))
                                        .ToList();
                    foreach (var shelf in shelves)
                    {
                        shelf.WebSocketIpAddress = request.WebSocketIpAddress;
                    }
                }

                return response;
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<UserBase>()
                {
                    Code = 300,
                    Message = $"登录失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }
    }
}
