using BPA.SAAS.Manage.Application.Org.Dtos.Users;
using BPA.SAAS.Manage.Application.Org.Interface;
using BPA.SAAS.Manage.Application.Org.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.Org;
using Furion.LinqBuilder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BPA.SAAS.Manage.Application.Org.Services
{
    public class UserService : IUserService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public UserService(ISqlSugarClient db)
        {
            _db=db;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageUtil> UserPage(UserDtoPageInput input)
        {
            RefAsync<int> total = 0;
            var data =await _db.Queryable<BPA_Users>().LeftJoin<BPA_Company>((t, x) => t.GroupId == x.Id)
            .WhereIF(!input.Name.IsNullOrEmpty(), t => t.Name.Contains(input.Name))
            .WhereIF(!input.Account.IsNullOrEmpty(), t => t.Account.Contains(input.Account))
            .Where(t => t.IsDeleted != 1)
           .OrderBy(t => t.CreateAt, OrderByType.Desc)
            .Select((t, x) => new UserDtoOutput
            {
                Id = t.Id,
                Account = t.Account,
                AdminType = t.AdminType,
                CompanyName = x.Name,
                Name = t.Name,
                Phone = t.Phone,
                SysOrgId = t.SysOrgId,
                CreateAt=t.CreateAt
            }).ToPageListAsync(input.Current, input.PageSize,  total);
            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = data
            };
            return util;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> AddUser(UserDtoInput input)
        {
            var user = input.Adapt<BPA_Users>();
            user.Password = MD5Encryption.Encrypt("123456").ToLower();
            var check = _db.Queryable<BPA_Users>().First(t => t.Account == user.Account);
            if (check != null)
                throw Oops.Oh("登录账户不能重复");
            return await _db.Insertable(user).CallEntityMethod(t => t.Create()).ExecuteCommandAsync()> 0;
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> UpdateUser(UserDtoInput input)
        {
            var user = _db.Queryable<BPA_Users>().First(t => t.Account == input.Account);

            if (user == null)
                return false;
            user.Name = input.Name;
            user.Account = input.Account;
            user.Phone = input.Phone;
            user.SysOrgId = input.SysOrgId;
            var res =await _db.Updateable(user)
               .IgnoreColumns(t => t.Password)
               .IgnoreColumns(t => t.AdminType)
               .ExecuteCommandHasChangeAsync();
            return res;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> DeleteUser(List<string> input)
        {
            var resEntitites = _db.Queryable<BPA_Users>().In(input).ToList();
            var res =await _db.Deleteable(resEntitites).ExecuteCommandAsync();
            return res > 0;
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> Enable(string Id)
        {
            var resEntitites = _db.Queryable<BPA_Users>().In(Id).ToList();
            resEntitites.ForEach(x =>
            {
                x.Status = CommonStatus.ENABLE;
            });
            var res =await _db.Updateable(resEntitites).ExecuteCommandAsync();
            return res>0;
        }

        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> Disable(string Id)
        {
            var resEntitites = _db.Queryable<BPA_Users>().In(Id).ToList();
            resEntitites.ForEach(x =>
            {
                x.Status = CommonStatus.DISABLE;
            });
            var res = await _db.Updateable(resEntitites).ExecuteCommandAsync();
            return res > 0;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> ResetPwd(string Id)
        {
            var user = _db.Queryable<BPA_Users>().First(t => t.Id == Id);

            if (user == null)
                return false;
            string pwd = MD5Encryption.Encrypt("123456").ToLower();

            return await  _db.Updateable<BPA_Users>(t => t.Password == pwd).Where(t => t.Id == Id).ExecuteCommandHasChangeAsync();

        }

        /// <summary>
        /// 变更密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePwd(UserPwdDtoInput input)
        {
            input.NPwd = MD5Encryption.Encrypt(input.NPwd).ToLower();
            input.OPwd = MD5Encryption.Encrypt(input.OPwd).ToLower();

            return await _db.Updateable<BPA_Users>()
              .SetColumns(t => t.Password == input.NPwd)
              .Where(t => t.Password == input.OPwd)
              .Where(t => t.Account == input.Account)
              .ExecuteCommandHasChangeAsync();
        }
        /// <summary>
        /// 获取当前用户的角色
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public async Task<UserRoleDtoInput> GetUserRole(string UserId)
        {
            string[] sysRoles =await _db.Queryable<BPA_UserRole>().Where(t => t.SysUserId == UserId).Select(t => t.SysRoleId).ToArrayAsync();
            UserRoleDtoInput userRoleDtoInput = new UserRoleDtoInput();
            userRoleDtoInput.SysUserId = UserId;
            userRoleDtoInput.SysRoleId = sysRoles;
            return userRoleDtoInput;
        }
        /// <summary>
        /// 新增用户角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> AddUserRole(UserRoleDtoInput input)
        {
            List<BPA_UserRole> roles = new List<BPA_UserRole>();

            var dara = _db.Queryable<BPA_UserRole>().Where(x => x.SysUserId == input.SysUserId).ToList();

            _db.Deleteable<BPA_UserRole>(dara).ExecuteCommand(); //批量删除
            foreach (string SysRoleId in input.SysRoleId)
            {
                BPA_UserRole role = new BPA_UserRole();
                role.Id = Guid.NewGuid().ToString();
                role.SysUserId = input.SysUserId;
                role.SysRoleId = SysRoleId;
                roles.Add(role);
            }
            return await _db.Insertable(roles).ExecuteCommandAsync() > 0;

        }
    }
}
