using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Common.Extend;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Core;
using YBDevice.Entity;

namespace YBDevice.Application.SystemInfo
{
    /// <summary>
    /// 系统管理
    /// </summary>
    public class SystemService :ISystemService, ITransient
    {

        private readonly ISqlSugarRepository<YB_nMenu> repository;
        private readonly SqlSugarClient dbClient;
        private readonly OperatorModel currentUser;
        public SystemService(ISqlSugarRepository<YB_nMenu> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            currentUser = BaseInfoService.GetUserInfo();
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<List<YB_nMenu>> GetMenuListAsync(Guid roleId)
        {
            var data = new List<YB_nMenu>();
            var tempquery = dbClient.Queryable<YB_nMenu, YB_nRoleMenu>(
                (m, ra) => new object[] {
                            JoinType.Left,m.Id==ra.MenuId
                })
                .Where((m, ra) => ra.RoleId == roleId && m.Status == StatusType.Enabled)
                ;
            data = await tempquery
                .OrderBy((m,ra)=>m.SortCode,OrderByType.Asc)
                .ToListAsync();
            return data;
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<YB_nMenu>> GetMenuListAsync()
        {
            var modulequery = dbClient.Queryable<YB_nMenu>();
            return await modulequery.OrderBy(x => x.SortCode, OrderByType.Asc).ToListAsync();
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteMenuAsync(Guid id)
        {
            if (!await dbClient.Queryable<YB_nMenu>().AnyAsync(x => x.Id == id))
            {
                return new ResultInfo() { code = ResultState.FAIL, message = "此菜单未找到!" };
            }
            await dbClient.Deleteable<YB_nMenu>().Where(x => x.Id == id).ExecuteCommandAsync();
            await dbClient.Deleteable<YB_nMenu>().Where(x => x.ParentId == id).ExecuteCommandAsync();
            return new ResultInfo() { code = ResultState.SUCCESS, message = "删除成功!" };
        }


        /// <summary>
        /// 菜单编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitMenuFormAsync(YB_nMenu model)
        {
            if (model.Id == Guid.Empty)
            {
                model.CreateTime = DateTime.Now;
                model.Status = StatusType.Enabled;
                model.Id = IDGen.NextID();
                await dbClient.Insertable(model).ExecuteCommandAsync();
                return new ResultInfo() { code = ResultState.SUCCESS, message = "添加成功!" };
            }
            else
            {
                await dbClient.Updateable<YB_nMenu>().SetColumns(x => new YB_nMenu
                {
                    ParentId = model.ParentId,
                    Icon = model.Icon,
                    SortCode = model.SortCode,
                    Url = model.Url,
                    Name = model.Name,
                    Remark = model.Remark
                })
                 .Where(x => x.Id == model.Id)
                     .ExecuteCommandAsync();
                return new ResultInfo() { code = ResultState.SUCCESS, message = "修改成功!" };
            }
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_nMenu> DetailMenuAsync(Guid id)
        {
            return await dbClient.Queryable<YB_nMenu>().FirstAsync(x => x.Id == id);
        }

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_nRole>> GetRoleListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<YB_nRole>();
            if (param.queryParam != null && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    temquery = temquery.Where(conModels);
                }
            }
            string sorts = string.Format("{0} {1}", param.sort, param.order);
            var query = await temquery.OrderBy(sorts)
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<YB_nRole>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 角色信息修改
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitRoleFormAsync(RoleSubmitModel role)
        {
            if (role.Id == Guid.Empty)
            {
                role.CreateTime = DateTime.Now;
                role.Status = StatusType.Enabled;
                role.Remark = role.Remark.ToStr();
                role.Id = IDGen.NextID();
                await dbClient.Insertable<YB_nRole>(role)
                     .EnableDiffLogEvent(new AduitLogS2SDto
                     {
                         Title = AuditOpConst.AddRole
                     })
                    .ExecuteCommandAsync();
            }
            else
            {
                await dbClient.Updateable<YB_nRole>()
                     .SetColumns(x => new YB_nRole
                     {
                         Name = role.Name,
                         Remark = role.Remark
                     })
                     .EnableDiffLogEvent(new AduitLogS2SDto
                     {
                         Title = AuditOpConst.UpdateRole
                     })
                     .Where(x => x.Id == role.Id).ExecuteCommandAsync();
            }

            List<YB_nRoleMenu> roleAuthorizeEntitys = new List<YB_nRoleMenu>();
            foreach (var item in role.menuids)
            {
                roleAuthorizeEntitys.Add(new YB_nRoleMenu
                {
                    CreateTime = DateTime.Now,
                    RoleId = role.Id,
                    MenuId = item,
                    Id = IDGen.NextID()
                });
            }
            await dbClient.Deleteable<YB_nRoleMenu>().Where(t => t.RoleId == role.Id).ExecuteCommandAsync();
            if (roleAuthorizeEntitys.Count > 0)
            {
                await dbClient.Insertable(roleAuthorizeEntitys).ExecuteCommandAsync();
            }
            List<YB_nRoleAction> actionlist = new List<YB_nRoleAction>();
            foreach (var item in role.actionids)
            {
                actionlist.Add(new YB_nRoleAction
                {
                    ButtonId = item.ButtonId,
                    RoleId = role.Id,
                    MenuId = item.MenuId
                });
            }
            await dbClient.Deleteable<YB_nRoleAction>().Where(t => t.RoleId == role.Id).ExecuteCommandAsync();
            if (actionlist.Count > 0)
            {
                await dbClient.Insertable(actionlist).ExecuteCommandAsync();
            }
            return new ResultInfo { code = ResultState.SUCCESS, message = "成功" };
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<List<YB_nRole>> GetAllRoleListAsync(string keyword = "")
        {

            var temquery = dbClient.Queryable<YB_nRole>();
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                temquery = temquery.Where(e => e.Name.Contains(keyword));
            }
            var query = await temquery.OrderBy(e => e.CreateTime, OrderByType.Desc).ToListAsync();
            return query;
        }

        /// <summary>
        /// 获取指定角色菜单列表
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public async Task<RoleSubmitModel> GetFromJsonAsync(Guid keyValue)
        {
            var temquery = await dbClient.Queryable<YB_nRole>().FirstAsync(x => x.Id == keyValue);
            if (temquery == null)
            {
                return null;
            }

            return new RoleSubmitModel
            {
                Id = temquery.Id,
                Remark = temquery.Remark,
                Code = temquery.Code,
                Name = temquery.Name,
                menuids = await dbClient.Queryable<YB_nRoleMenu>().Where(e => e.RoleId == temquery.Id).Select(e => e.MenuId).ToListAsync()
            };
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteRoleFormAsync(Guid keyValue)
        {
            await dbClient.Deleteable<YB_nRole>().Where(e => e.Id == keyValue).ExecuteCommandAsync();
            await dbClient.Deleteable<YB_nRoleMenu>().Where(e => e.RoleId == keyValue).ExecuteCommandAsync();
            return new ResultInfo { code = ResultState.SUCCESS, message = "删除成功", data = null };
        }
        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RoleSubmitModel> DetailRoleAsync(Guid id)
        {
            if (id == Guid.Empty)
            {
                return new RoleSubmitModel() { menuids = new List<Guid>() };
            }
            var data = await dbClient.Queryable<YB_nRole>().FirstAsync(x => x.Id == id);
            return new RoleSubmitModel
            {
                Id = data.Id,
                Code = data.Code,
                Name = data.Name,
                Remark = data.Remark
            };
        }
        /// <summary>
        /// 菜单按钮列表
        /// </summary>
        /// <returns></returns>
        public async Task<PageParms<MenuActionS2SDto>> GetActionListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<YB_nMenuAction>();
            if (param.queryParam != null && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    temquery = temquery.Where(conModels);
                }
            }
            var query = await temquery
                .OrderBy(x => x.MenuId, OrderByType.Asc)
                .OrderBy(x => x.SortCode, OrderByType.Asc)
                .Select(x => new MenuActionS2SDto
                {
                    ActionName = x.ActionName,
                    ButtonId = x.ButtonId,
                    SortCode = x.SortCode,
                    ButtonName = x.ButtonName,
                    ControlName = x.ControlName,
                    Id = x.Id,
                    MenuId = x.MenuId
                })
                .Mapper((it, cache) =>
                {
                    var allmenu = cache.Get(list =>
                    {
                        List<Guid> ids = list.Select(x => x.MenuId).ToList();
                        ids = ids.IDistinctList();
                        return dbClient.Queryable<YB_nMenu>().Where(x => ids.Contains(x.Id)).ToList();
                    });
                    it.MenuName = allmenu.FirstOrDefault(x => x.Id == it.MenuId).Name;
                })
                 .ToPageListAsync(param.offset, param.limit, totalnum);
            return new PageParms<MenuActionS2SDto>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 角色菜单修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitMenuActionAsync(YB_nMenuAction data)
        {
            if (data.Id != Guid.Empty)
            {
                await dbClient.Updateable<YB_nMenuAction>().SetColumns(x => new YB_nMenuAction
                {
                    ActionName = data.ActionName,
                    SortCode = data.SortCode,
                    ButtonId = data.ButtonId,
                    ButtonName = data.ButtonName,
                    ControlName = data.ControlName,
                    MenuId = data.MenuId,
                    Type = data.Type
                }).Where(x => x.Id == data.Id)
                .ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "修改成功");
            }
            else
            {
                data.Id = IDGen.NextID();
                await dbClient.Insertable(data).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "添加成功");
            }
        }
        /// <summary>
        /// 删除角色菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteMenuActionAsync(Guid id)
        {
            if (!await dbClient.Queryable<YB_nMenuAction>().AnyAsync(x => x.Id == id))
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            await dbClient.Deleteable<YB_nMenuAction>().Where(x => x.Id == id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 菜单按钮详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<YB_nMenuAction> GetActionDetailAsync(Guid id)
        {
            return await dbClient.Queryable<YB_nMenuAction>().Where(x => x.Id == id).FirstAsync();
        }
        /// <summary>
        /// 角色的菜单按钮列表
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        public async Task<List<MenuActionListS2CDto>> GetMenuActionListAsync(Guid? id)
        {
            var tempquery = dbClient.Queryable<YB_nMenu>();
            if (!currentUser.IsSuper)
            {
                tempquery = tempquery.Where(x => x.IsSuper == 0);
            }
            var query = await tempquery
                .OrderBy(x => x.SortCode, OrderByType.Asc)
                .Select(x => new MenuActionListS2CDto
                {
                    Id = x.Id,
                    MenuName = x.Name,
                    ParentId = x.ParentId
                })
                .Mapper((it, cache) =>
                {
                    var alllist = cache.Get(list =>
                    {
                        var ids = list.Select(x => x.Id).ToList();
                        return dbClient.Queryable<YB_nMenuAction>().Where(x => ids.Contains(x.MenuId)).ToList();
                    });
                    it.ActionList = alllist.Where(x => x.MenuId == it.Id)
                    .OrderBy(x => x.SortCode)
                    .Select(x => new MenuActionItemS2SDto
                    {
                        Id = x.Id,
                        SortCode = x.SortCode,
                        ActionName = x.ActionName,
                        ButtonId = x.ButtonId,
                        ButtonName = x.ButtonName,
                        ControlName = x.ControlName,
                        MenuId = x.MenuId
                    }).ToList();
                })
                .ToListAsync();
            List<YB_nRoleMenu> rolemenulist = new List<YB_nRoleMenu>();
            List<YB_nRoleAction> roleactionlist = new List<YB_nRoleAction>();
            if (id.HasValue && id.Value != Guid.Empty)
            {
                rolemenulist = await dbClient.Queryable<YB_nRoleMenu>()
                    .Where(x => x.RoleId == id)
                    .ToListAsync();
                roleactionlist = await dbClient.Queryable<YB_nRoleAction>().Where(x => x.RoleId == id).ToListAsync();
            }
            List<MenuActionListS2CDto> returnlist = new List<MenuActionListS2CDto>();
            foreach (var item in query)
            {
                bool IsChecked = false;
                var data = new MenuActionListS2CDto
                {
                    Id = item.Id,
                    IsChecked = IsChecked,
                    MenuName = item.MenuName,
                    ParentId = item.ParentId
                };
                List<MenuActionItemS2SDto> actionlist = new List<MenuActionItemS2SDto>();
                if (rolemenulist.Any(x => x.MenuId == item.Id))
                {
                    IsChecked = true;
                }
                if (item.ActionList != null && item.ActionList.Count > 0)
                {
                    foreach (var item1 in item.ActionList)
                    {
                        bool IsActionChecked = false;
                        foreach (var itema in roleactionlist)
                        {
                            if (itema.ButtonId == item1.Id)
                            {
                                IsActionChecked = true;
                                break;
                            }
                        }
                        actionlist.Add(new MenuActionItemS2SDto
                        {
                            ActionName = item1.ActionName,
                            SortCode = item1.SortCode,
                            ButtonId = item1.ButtonId,
                            ButtonName = item1.ButtonName,
                            ControlName = item1.ControlName,
                            Id = item1.Id,
                            IsChecked = IsActionChecked,
                            MenuId = item1.MenuId
                        });
                    }
                }
                data.IsChecked = IsChecked;
                data.ActionList = actionlist;
                returnlist.Add(data);
            }
            return returnlist;
        }
    }
}
