using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Service.DBServices
{
    /// <summary>
    /// 角色管理
    /// </summary>
    public partial class RoleApp : Repository<YB_Role>
    {
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<YB_Role>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_Role>();
                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_Role>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }
        /// <summary>
        /// 角色信息修改
        /// </summary>
        /// <param name="role"></param>
        /// <param name="permissionIds"></param>
        /// <param name="appletsPermissionIds"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitFormAsync(RoleSubmitModel role)
        {
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (role.Id == 0)
                {
                    role.CreateTime = DateTime.Now;
                    role.Status = 1;
                    role.Remark = role.Remark.ToStr();
                   role.Id= await dbClient.Insertable<YB_Role>(role).ExecuteReturnIdentityAsync();
                }
                else
                {
                    await dbClient.Updateable<YB_Role>()
                         .SetColumns(x => new YB_Role
                         {
                             Name = role.Name,
                             Remark = role.Remark
                         })
                         .Where(x => x.Id == role.Id).ExecuteCommandAsync();
                }

                List<YB_RoleMenu> roleAuthorizeEntitys = new List<YB_RoleMenu>();
                foreach (var item in role.permissionId)
                {
                    var itemId = item;
                    YB_RoleMenu roleAuthorizeEntity = new YB_RoleMenu
                    {
                        CreateTime = DateTime.Now,
                        RoleId = role.Id,
                        MenuId = itemId
                    };
                    roleAuthorizeEntitys.Add(roleAuthorizeEntity);
                }
                await dbClient.Deleteable<YB_RoleMenu>(t => t.RoleId == role.Id).ExecuteCommandAsync();
                if (roleAuthorizeEntitys.Count > 0)
                {
                    await dbClient.Insertable<YB_RoleMenu>(roleAuthorizeEntitys).ExecuteCommandAsync();
                }
                return new ResultInfo { code = ResultState.SUCCESS, message = "成功"};

            }
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<List<YB_Role>> GetAllListAsync(string keyword = "")
        {
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<YB_Role>();
                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(int keyValue)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = await dbClient.Queryable<YB_Role>().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,
                    permissionId = await dbClient.Queryable<YB_RoleMenu>().Where(e => e.RoleId == temquery.Id).Select(e => e.MenuId).ToListAsync()
                };
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteFormAsync(int keyValue)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                await dbClient.Deleteable<YB_Role>().Where(e => e.Id == keyValue).ExecuteCommandAsync();
                await dbClient.Deleteable<YB_RoleMenu>().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> DetailAsync(int id)
        {
            if(id <= 0)
            {
                return new RoleSubmitModel() { permissionId=new List<int>()};
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var data = await dbClient.Queryable<YB_Role>().FirstAsync(x => x.Id == id);
                return new RoleSubmitModel
                {
                    Id = data.Id,
                    Code = data.Code,
                    Name = data.Name,
                    Remark = data.Remark,
                    permissionId = await dbClient.Queryable<YB_RoleMenu>().Where(x => x.RoleId == id).Select(x => x.MenuId).ToListAsync()
                };
            }
        }
    }
}
