namespace BPA.MES.Base.Application
{
    /// <summary>
    /// 名    称 ：授权服务 
    /// 创 建 人 ：yangxiao  
    /// 创建时间 ：2023/3/2 16:11:04 
    /// 描    述 ：授权服务数据维护 
    /// </summary>
    [ApiDescriptionSettings(Name = "Authorize", KeepName = true, SplitCamelCase = true, KeepVerb = true)]
    public class AuthorizeService : IAuthorizeService, ITransient, IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISqlSugarClient db;
        private readonly ISqlSugarClient _dbContext;
        public AuthorizeService(ISqlSugarClient db, IHttpContextAccessor httpContextAccessor)
        {
            this.db = db;
            _dbContext = db;
            _httpContextAccessor = httpContextAccessor;
        }
        #region 当前用户
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        [AllowAnonymous]
        public async Task<bool> Login(AccountInput input)
        {
            var Info = await db.Queryable<AccountEntity>().FirstAsync(t => t.Account == input.Account && t.Pwd == input.Pwd);
            if (Info == null)
                throw Oops.Bah("请输入正确的账号和密码");
            var User = await db.Queryable<EmployeeEntity>().FirstAsync(t => t.Id == Info.EmployeeId);
            if (User == null)
            {
                throw Oops.Bah("账号没有权限");
            }
            //return ResolveService<IJwtService>().CreateAccessToken(new UserIdentity
            //{
            //    Id = User.Id,
            //    UserName = User.Name,
            //    IsAdmin = User.IsAdmin,
            //});

            // 生成Token令牌
            //var accessToken = await _jwtBearerManager.CreateTokenAdmin(user);
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
            {
                {ClaimConst.CLAINM_USERID, User.Id},
                {ClaimConst.CLAINM_NAME,User.Name},
                {ClaimConst.CLAINM_ISAUTH,User.IsAdmin},
            },20);
            // 设置Swagger自动登录
            _httpContextAccessor.HttpContext.SigninToSwagger(accessToken);
            // 生成刷新Token令牌
            var refreshToken =
                JWTEncryption.GenerateRefreshToken(accessToken, 25);

            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = accessToken;
            // 设置刷新Token令牌
            _httpContextAccessor.HttpContext.Response.Headers["x-access-token"] = refreshToken;
            return true;
        }
        /// <summary>
        /// 获取个人信息
        /// </summary>
        /// <returns></returns>
        public async Task<object> GetUserInfo()
        {
            string userId = App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var user = await db.Queryable<EmployeeEntity>().LeftJoin<RoleEntity>((t, x) => t.TB_RoleId == x.Id)
                    .Where((t, x) => t.Id == userId).Select((t, x) => new
                    {
                        RoleName = x.Name,
                        RoleType = x.RoleType,
                        Id = t.Id,
                        UserName = t.Name
                    }).FirstAsync();


            var menus = (await GetJurisdictionItemsAsync())?.Menus;
            return new
            {
                Menus = menus,
                UserInfo = new
                {
                    UserId = user?.Id,
                    user?.RoleName,
                    user?.UserName
                }
            };
        }
        [HttpGet]
        public async Task<List<string>> MultipleModuleAuthorityAsync()
        {
            return (await GetJurisdictionItemsAsync())?.AuthorizationCodes;
        }
        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        async Task<UserRoleCacheDto> GetJurisdictionItemsAsync()
        {

            string userId = App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var result = new UserRoleCacheDto();

            result.AuthorizationCodes = (await GetAuthorityModuleIdsAsync(userId)) ?? new List<string>();

            if (result.AuthorizationCodes.HasVal())
            {
                var temp = await db.Queryable<ModuleEntity>().Where(t => t.Category == 1 || t.Category == 2 || t.Category == 3)
                      .Where(t => result.AuthorizationCodes.Contains(t.Id) && !t.IsDisabled).OrderBy(t => t.ParentId)
                     .ToListAsync();

                result.Menus = temp.Adapt<List<UserMenu>>().BuildTree();
            }

            result.Menus = result.Menus ?? new List<UserMenu>();

            return result;
        }
        /// <summary>
        /// 获取权限模块编号
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        async Task<List<string>> GetAuthorityModuleIdsAsync(string userId)
        {
            List<string> moduleIds = null;

            var user = await db.Queryable<EmployeeEntity>().Where(m => m.Id == userId).FirstAsync();

            if (user == null)
            {
                return moduleIds;
            }

            //超管用户
            if (user.IsAdmin)
            {
                moduleIds = await db.Queryable<ModuleEntity>()
                    .OrderBy(m => m.ParentId).OrderBy(m => m.Name)
                    .ToListAsync(m => m.Id);
            }
            else
            {
                moduleIds = await GetAuthorityModuleIdsAsync((category) =>
                {
                    if (category == 1)
                    {
                        return user.Id;
                    }
                    if (category == 2)
                    {
                        return user.TB_RoleId;
                    }
                    else
                    {
                        throw new NotImplementedException("无效授权类别");
                    }
                });
            }

            return moduleIds;
        }
        /// <summary>
        /// 获取账户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<SqlSugarPagedList<AccountOutput>> AccountPageList(AccountQueryPageInput input)
        {
          var entity = await _dbContext.Queryable<AccountEntity>()
                .ToPagedListAsync(input.PageIndex,input.PageSize);
            SqlSugarPagedList<AccountOutput> output = entity.Adapt<SqlSugarPagedList<AccountOutput>>();
            return output;
        }

        /// <summary>
        /// 添加账户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> AddAccount(AccountAddInput input)
        {
            var entity = input.Adapt<AccountEntity>();
            return await _dbContext.Insertable(entity).ExecuteCommandIdentityIntoEntityAsync();
        }
        /// <summary>
        /// 修改账户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAccount(AccountUpdateInput input) {
            var entity = input.Adapt<AccountEntity>();
            return await _dbContext.Updateable(entity).ExecuteCommandHasChangeAsync();
        }
        /// <summary>
        /// 删除账户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> DelAccount(AccountDelInput input) {
            var entity = input.Adapt<AccountEntity>();
            return await _dbContext.Deleteable(entity).Where(x=>x.Id==input.Id).ExecuteCommandHasChangeAsync();
        }
        /// <summary>
        /// 获取授权模块编号
        /// </summary>
        /// <param name="getObjectId"></param>
        /// <returns></returns>
        [HttpGet]
        async Task<List<string>> GetAuthorityModuleIdsAsync(Func<int, string> getObjectId)
        {
            for (int index = 1; index <= 2; index++)
            {
                var objectId = getObjectId(index);
                var templateIds = await db.Queryable<AuthorizeTemplateMapEntity>().LeftJoin<AuthorizeTemplateEntity>((t, x) => t.TemplateId == x.Id)
                    .Where((t, x) =>  t.AuthorizeType == index && t.ObjectId == objectId).ToListAsync(t => t.TemplateId);

                if (!templateIds.HasVal() || templateIds.Count == 0)
                {
                    continue;
                }
                return await db.Queryable<AuthorizeTemplateItemEntity>().LeftJoin<ModuleEntity>((t, x) => t.TB_ModuleId == x.Id)
                    .Where((t, x) =>  templateIds.Contains(t.TB_TemplateId))
                    .GroupBy((t, x) => t.TB_ModuleId).ToListAsync(t => t.TB_ModuleId);
            }
            return null;
        }
        #endregion


        #region 角色
        [HttpPost]
        public async Task<bool> AddRole(RoleAddInput input)
        {
            var check = await db.Queryable<RoleEntity>().FirstAsync(t => t.Name == input.Name);
            if (check != null) throw Oops.Bah ("角色名称不能重复");
            var model = input.Adapt<RoleEntity>();
            model.RoleType = 2;
            return await db.Insertable(model).ExecuteCommandAsync() > 0;
        }
        [HttpPost]
        public async Task<bool> EditRole(RoleUpdateInput input)
        {
            if (!await db.Queryable<RoleEntity>().Where(it => it.Id == input.Id).AnyAsync())
                throw Oops.Bah("角色不存在或已被删除");
            if (await _dbContext.Queryable<RoleEntity>().Where(it => it.Id != input.Id && it.Name == input.Name).AnyAsync())
                throw Oops.Bah("角色名称已经存在");
            return await _dbContext.Updateable<RoleEntity>(input).Where(a => a.Id == input.Id).ExecuteCommandHasChangeAsync();
        }
        [HttpGet]
        public async Task<bool> RemoveRole(string input)
        {
            return await db.Updateable<RoleEntity>().Where(t => t.Id == input).ExecuteCommandHasChangeAsync();
        }
        [HttpGet]
        public async Task<RoleOutput> GetRole(string input)
        {
            var entity = await db.Queryable<RoleEntity>().FirstAsync(t => t.Id == input);
            return entity.Adapt<RoleOutput>();
        }
        [HttpGet]
        public async Task<List<RoleOutput>> GetRoleList()
        {
            var entity = await db.Queryable<RoleEntity>().Where(t => t.RoleType != 1).ToListAsync();
            return entity.Adapt<List<RoleOutput>>();
        }
        [HttpPost]
        public async Task<SqlSugarPagedList<RoleOutput>> QueryRole(RoleQueryPageInput input)
        {
            var eneity = await db.Queryable<RoleEntity>()
                 .WhereIF(!string.IsNullOrEmpty(input.Keyword), t => t.Name.Contains(input.Keyword))
                 .Select<RoleOutput>()
                 .ToPagedListAsync(input.PageIndex, input.PageSize);
            return eneity;
        }
        #endregion

        #region 模块
        [HttpPost]
        public async Task<bool> AddModule(ModuleAddInput input)
        {
            input.ParentId = input.ParentId ?? string.Empty;
            input.Id = null;
            return (await db.Insertable(input.Adapt<ModuleEntity>()).ExecuteCommandAsync()) > 0;
        }
        [HttpPost]

        public async Task<bool> EditModule(ModuleUpdateInput input)
        {
            if (!await db.Queryable<ModuleEntity>().Where(it => it.Id == input.Id ).AnyAsync())
            {
                throw Oops.Bah("模块不存在或已被删除");
            }
            input.ParentId = input.ParentId ?? string.Empty;
            return await db.Updateable<ModuleEntity>(input).Where(a => a.Id == input.Id).ExecuteCommandHasChangeAsync();
        }
        [HttpGet]

        public async Task RemoveModule(string input)
        {
            var list = await db.Queryable<ModuleEntity>().Where(it => it.ParentId == input).ToListAsync();
            if (list.HasVal())
            {
                foreach (var item in list)
                {
                    await RemoveModule(item.Id);
                }
            }
            await _dbContext.Updateable<ModuleEntity>().Where(it => it.Id == input).ExecuteCommandAsync();
        }
        [HttpPost]
        public async Task<List<ModuleTreeOutput>> GetTreeGrid(ModuleTreeQueryInput input)
        {
            var list = new List<ModuleTreeOutput>();

            var datas = await db.Queryable<ModuleEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.Name), t => t.Name.Contains(input.Name))
                .OrderBy(it => it.ParentId)
                .OrderBy(it => it.Name)
                .ToListAsync();

            var modules = datas.Adapt<List<ModuleTreeOutput>>();

            if (modules.HasVal())
            {
                foreach (var item in modules.Where(it => it.Category == 1))
                {
                    item.Children = modules.Where(it => it.ParentId == item.Id && it.Category == 2).OrderBy(it => it.Sort).ToList();
                    foreach (var view in item.Children)
                    {
                        view.Children = modules.Where(it => it.ParentId == view.Id && it.Category == 3).OrderBy(it => it.Sort).ToList();
                    }

                    list.Add(item);
                }
            }
            return list;
        }
        #endregion

        #region 授权模板
        [HttpPost]
        public async Task<bool> AddAuthorTemp(AuthorizeTemplateAddInput input)
        {
            if (await db.Queryable<AuthorizeTemplateEntity>().Where(it => it.Name == input.Name && it.IsDeleted == false).AnyAsync())
                throw Oops.Bah("模板名称已经存在");
            var data = await db.Insertable(input.Adapt<AuthorizeTemplateEntity>()).ExecuteCommandAsync();
            return data > 0;
        }
        [HttpPost]
        public async Task<bool> EditAuthorTemp(AuthorizeTemplateUpdateInput input)
        {
            if (!await db.Queryable<AuthorizeTemplateEntity>().Where(it => it.Id == input.Id && it.IsDeleted == false).AnyAsync())
                throw Oops.Bah("模板不存在或已被删除");
            if (await db.Queryable<AuthorizeTemplateEntity>().Where(it => it.Id != input.Id && it.Name == input.Name && it.IsDeleted == false).AnyAsync())
                throw Oops.Bah("模板名称已经存在");
            return await db.Updateable<AuthorizeTemplateEntity>(input).Where(a => a.Id == input.Id).ExecuteCommandHasChangeAsync();
        }
        [HttpGet]
        public async Task<bool> RemoveAuthorTemp(string input)
        {
            var f1 = await db.Updateable<AuthorizeTemplateEntity>().SetColumns(t => t.IsDeleted == true).Where(t => t.Id == input).ExecuteCommandHasChangeAsync();
            var f2 = await db.Updateable<AuthorizeTemplateItemEntity>().SetColumns(T => T.IsDeleted == true).Where(t => t.TB_TemplateId == input).ExecuteCommandHasChangeAsync();
            return f1 && f2;
        }
        [HttpPost]
        public async Task<SqlSugarPagedList<AuthorizeTemplateOutput>> QueryAuthorTemp(AuthorizeTemplateQueryPageInput input)
        {
            RefAsync<int> Total = 0;
            var data = await db.Queryable<AuthorizeTemplateEntity>().Where(t => !t.IsDeleted)
                   .WhereIF(!string.IsNullOrEmpty(input.Keyword), t => t.Name.Contains(input.Keyword))
                   .OrderByDescending(t => t.CreateAt)
                   .Select<AuthorizeTemplateOutput>()
                   .ToPagedListAsync(input.PageIndex, input.PageSize);
            return data;
        }
        public async Task<AuthorizeTemplateOutput> GetAuthorTemp(string input)
        {
            var data = await db.Queryable<AuthorizeTemplateEntity>().Where(it => it.Id == input && it.IsDeleted == false).FirstAsync();
            return data.Adapt<AuthorizeTemplateOutput>();
        }
        #endregion

        #region 授权模板详情
        [HttpGet]
        public async Task<List<AuthorModuleOutput>> GetModuleByTemplateId(string input)
        {
            List<AuthorModuleOutput> result = new List<AuthorModuleOutput>();
            var modules = await db.Queryable<ModuleEntity>().ToListAsync();
            var roots = modules.Adapt<List<AuthorModuleOutput>>();
            db.ThenMapper(roots, item =>
            {
                item.HasPermission = db.Queryable<AuthorizeTemplateItemEntity>().Where(m => m.TB_TemplateId == input && m.TB_ModuleId == item.Id).Any();
            });
            if (roots.HasVal())
            {
                foreach (var item in roots.Where(it => it.Category == 1))
                {
                    item.Childrens = roots.Where(it => it.ParentId == item.Id && it.Category == 2).OrderBy(it => it.Name).ToList();

                    foreach (var view in item.Childrens)
                    {
                        view.Childrens = roots.Where(it => it.ParentId == view.Id && it.Category == 3).OrderBy(it => it.Name).ToList();
                    }

                    result.Add(item);
                }
            }
            return result;
        }
        [HttpPost]
        public async Task<bool> EditTemplateItem(AuthorModuleItemUpdateInput input)
        {
            var temp = await db.Queryable<AuthorizeTemplateEntity>().FirstAsync(t => t.Id == input.TB_TemplateId && t.IsDeleted == false);
            await db.Updateable<AuthorizeTemplateItemEntity>().SetColumns(T => T.IsDeleted == true)
                .Where(t => t.TB_TemplateId == input.TB_TemplateId).ExecuteCommandHasChangeAsync();

            var entity = input.TB_ModuleIds.Distinct().ToList().ConvertAll(t => new AuthorizeTemplateItemEntity
            {
                TB_ModuleId = t,
                TB_TemplateId = input.TB_TemplateId
            });
            var res = await db.Insertable(entity).ExecuteCommandAsync();
            return res > 0;
        }
        [HttpPost]
        public async Task<List<AuthorizeOutput>> GetAuthorizeObjects(AuthorizeInput input)
        {
            List<AuthorizeOutput> result;
            if (input.Type == 2)
            {
                var temp = await db.Queryable<RoleEntity>()
                     .Where(t => t.RoleType != 1)
                     .Where(t => t.IsDeleted == false)
                     .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), t => t.Name.Contains(input.Keyword))
                     .OrderBy(t => t.RoleType)
                     .OrderBy(t => t.Name)
                     .ToListAsync();

                result = temp.Adapt<List<AuthorizeOutput>>();
                db.ThenMapper(result, item =>
                {
                    item.IsAuthorized = db.Queryable<AuthorizeTemplateMapEntity>()
                    .Where(m => m.TemplateId == input.TemplateId && m.AuthorizeType == input.Type && m.ObjectId == item.Id).Any();
                });
            }
            else
            {
                var temp = await db.Queryable<EmployeeEntity>()
                      .Where(t => t.IsAdmin == false)
                      .Where(t => t.IsDeleted == false)
                      .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), t => t.Name.Contains(input.Keyword))
                      .OrderBy(t => t.Name)
                      .ToListAsync();
                result = temp.Adapt<List<AuthorizeOutput>>();
                db.ThenMapper(result, item =>
                {
                    item.IsAuthorized = db.Queryable<AuthorizeTemplateMapEntity>().Where(t => t.IsDeleted == false)
                    .Where(m => m.TemplateId == input.TemplateId && m.AuthorizeType == input.Type && m.ObjectId == item.Id).Any();
                });
            }
            if (result.HasVal())
            {
                result = result.OrderByDescending(m => m.IsAuthorized).ThenBy(m => m.Name).ToList();
            }
            return result;
        }
        [HttpPost]
        public async Task<bool> RemoveAuthorize(AuthorizeInput input)
        {
            var objectIds = input.ObjectIds.Distinct().ToArray();
            return await db.Updateable<AuthorizeTemplateMapEntity>().SetColumns(t => t.IsDeleted == true)
                 .Where(it => it.TemplateId == input.TemplateId && it.AuthorizeType == input.Type && objectIds.Contains(it.ObjectId))
                 .ExecuteCommandHasChangeAsync();
        }
        [HttpPost]
        public async Task AddAuthorize(AuthorMapAddInput input)
        {
            foreach (var item in input.TemplateIds.Distinct())
            {
                if (!await _dbContext.Queryable<AuthorizeTemplateMapEntity>().AnyAsync(m => m.TemplateId == item && m.AuthorizeType == input.AuthorizeType && m.IsDeleted == false && m.ObjectId == input.ObjectId))
                {
                    await _dbContext.Insertable(new AuthorizeTemplateMapEntity()
                    {
                        TemplateId = item,
                        ObjectId = input.ObjectId,
                        AuthorizeType = input.AuthorizeType
                    }).ExecuteCommandAsync();
                }
            }
        }
        [HttpPost]
        public async Task<bool> SaveAuthorize(AuthorModulesAddInput input)
        {
            if (await db.Queryable<AuthorizeTemplateEntity>().Where(it => it.Name == input.TemplateName && it.IsDeleted == false).AnyAsync())
            {
                throw Oops.Bah("模板名称已经存在");
            }
            AuthorizeTemplateEntity Model = new AuthorizeTemplateEntity();
            Model.Name = input.TemplateName;
            List<AuthorizeTemplateItemEntity> templateItems = input.ModuleIds.ConvertAll(m => new AuthorizeTemplateItemEntity
            {
                TB_TemplateId = Model.Id,
                TB_ModuleId = m
            });
            try
            {
                db.Ado.BeginTran();
                var f1 = (await db.Insertable(Model).ExecuteCommandAsync()) > 0;
                var f2 = (await _dbContext.Insertable(templateItems).ExecuteCommandAsync()) > 0;
                db.Ado.CommitTran();
                return f1 && f2;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                return false;
            }
        }
        [HttpGet]
        public async Task<bool> RestoreAccountByUser(string input)
        {
            var Demo = "123456".ToMD5Encrypt();
            return await db.Updateable<AccountEntity>().SetColumns(t => t.Pwd == Demo)
                .Where(t => t.EmployeeId == input).ExecuteCommandHasChangeAsync();
        }
        [HttpPost]
        public async Task<bool> AddAccountByUser(AccountAddInput input)
        {
            var temp = await db.Queryable<AccountEntity>().FirstAsync(t => t.EmployeeId == input.TB_Employee_Id);
            if (temp != null)
            {
                //throw new BusinessException("该员工已绑定账户，请勿重复绑定");
                temp.Account = input.Account;
                return await db.Updateable(temp).ExecuteCommandAsync() > 0;
            }
            else
            {
                var model = input.Adapt<AccountEntity>();
                //默认123456
                model.Pwd = "123456".ToMD5Encrypt();
                return await db.Insertable(model).ExecuteCommandAsync() > 0;
            }
        }
        [HttpPost]
        public async Task<bool> EditAccountPwd(AccountUpdatePwdInput input)
        {
            var model = db.Queryable<AccountEntity>().First(t => t.Account == input.Account && t.Pwd == input.Pwd);
            if (model == null) throw Oops.Bah("原密码不正确");
            model.Pwd = input.NewPwd;
            return await db.Updateable(model).ExecuteCommandAsync() > 0;
        }
        [HttpGet]
        public async Task<AccountOutput> GetAccountByUser(string input)
        {
            var data = await db.Queryable<AccountEntity>().FirstAsync(t => t.EmployeeId == input);
            return data.Adapt<AccountOutput>();
        }

        [HttpPost]
        public async Task<bool> AddEmployee(EmployeeAddInput input)
        {
            var model = input.Adapt<EmployeeEntity>();
            model.IsAdmin = false;
            var temp = await db.Queryable<EmployeeEntity>().FirstAsync(t => t.Name.Equals(input.Name) && t.Phone.Equals(input.Phone) && t.IsDeleted == false);
            if (temp != null) throw Oops.Bah("该员工已经存在");
            return await db.Insertable(model).ExecuteCommandAsync() > 0;
        }
        [HttpPost]
        public async Task<bool> EditEmployee(EmployeeUpdateInput input)
        {
            var temp = await db.Queryable<EmployeeEntity>().FirstAsync(t => t.Id == input.Id);
            temp.Header = input.Header;
            temp.IdCard = input.IdCard;
            temp.Gender = input.Gender;
            temp.JoinDate = input.JoinDate;
            temp.OutDate = input.OutDate;
            temp.Name = input.Name;
            temp.Phone = input.Phone;
            temp.Stutas = input.Stutas;
            return await db.Updateable(temp).ExecuteCommandHasChangeAsync();
        }
        [HttpPost]
        public async Task<SqlSugarPagedList<EmployeeOutput>> QueryEmployee(EmployeeQueryPageInput input)
        {
         
            var entity = await db.Queryable<EmployeeEntity>()

                   .WhereIF(!string.IsNullOrEmpty(input.Keyword), t => t.Name.Contains(input.Keyword) || t.Phone.Contains(input.Keyword))
                   .WhereIF(input.Status > 0, t => t.Stutas == input.Status).WhereIF(input.Gender > 0, t => t.Gender == input.Gender)
                   .WhereIF(input.JoinDate.HasValue, t => t.JoinDate <= input.JoinDate.Value)
                   .Where(t => t.IsAdmin == false)
                   .Where(t => t.IsDeleted == false)
                   .Select(t => new EmployeeOutput()
                     {
                         Id = t.Id.SelectAll(),
                         IsAccount = SqlFunc.Subqueryable<AccountEntity>().Where(s => s.EmployeeId == t.Id).Any(),
                         Account = SqlFunc.Subqueryable<AccountEntity>().Where(s => s.EmployeeId == t.Id).Select(s => s.Account)
                     })
                   .ToPagedListAsync(input.PageIndex, input.PageSize);
            return entity;
        }
        [HttpGet]
        public async Task<bool> RemoveEmployee([FromQuery] string employeeId)
        {
            bool result = false;
            var entity =await db.Queryable<AccountEntity>().FirstAsync(x=>x.EmployeeId== employeeId);
           
            try
            {
                db.Ado.BeginTran();
                await db.Deleteable<EmployeeEntity>().Where(t => t.Id == employeeId).ExecuteCommandAsync();
                if (entity!=null)
                {
                    entity.EmployeeId = string.Empty;
                    await db.Updateable(entity).ExecuteCommandAsync();
                }
                db.Ado.CommitTran();
                result = true;
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                throw Oops.Bah("删除失败!");
            }
            return result;
        }
        [HttpGet]
        public async Task<List<EmployeeOutput>> EmployeeList()
        {
            var data = await db.Queryable<EmployeeEntity>().Where(t => t.IsAdmin == false).ToListAsync();
            return data.Adapt<List<EmployeeOutput>>();
        }
        #endregion
    }
}
