using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Domain;

namespace Waste.Application
{
    /// <summary>
    /// 账户管理
    /// </summary>
    public class RoleService : IRoleService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<W_Role> repository;
        private readonly SqlSugarClient dbClient;

        public RoleService(ISqlSugarRepository<W_Role> sqlSugarRepository
           )
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> DeleteFormAsync(Guid keyValue)
        {
            await dbClient.Deleteable<W_Role>().Where(e => e.Id == keyValue).ExecuteCommandAsync();
            await repository.Change<W_RoleAuthorize>().Context.Deleteable<W_RoleAuthorize>().Where(e => e.RoleId == keyValue).ExecuteCommandAsync();
            return new ResultInfo { code = ResultState.SUCCESS, message = "删除成功", data = null };
        }
        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<RoleSubmitModel> DetailAsync(Guid id)
        {
            if (id == Guid.Empty)
            {
                return new RoleSubmitModel() { permissionId = new List<Guid>() };
            }
            var data = await dbClient.Queryable<W_Role>().FirstAsync(x => x.Id == id);
            return new RoleSubmitModel
            {
                Id = data.Id,
                EnCode = data.EnCode,
                Name = data.Name,
                Remark = data.Remark,
                permissionId = await repository.Change<W_RoleAuthorize>().Context.Queryable<W_RoleAuthorize>().Where(x => x.RoleId == id).Select(x => x.MenuId).ToListAsync()
            };
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageParms<W_Role>> GetListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            var temquery = dbClient.Queryable<W_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<W_Role>
            {
                page = param.offset,
                Items = query,
                totalnum = totalnum,
                limit = param.limit
            };
        }
        /// <summary>
        /// 信息提交
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitFormAsync(RoleSubmitModel role)
        {
            if (role.Id == Guid.Empty)
            {
                role.Id = IDGen.NextID();
                role.CreateTime = DateTime.Now;
                role.Remark = role.Remark.ToStr();
                await dbClient.Insertable<W_Role>(role).ExecuteCommandAsync();
            }
            else
            {
                await dbClient.Updateable<W_Role>()
                     .SetColumns(x => new W_Role
                     {
                         Name = role.Name,
                         Remark = role.Remark
                     })
                     .Where(x => x.Id == role.Id).ExecuteCommandAsync();
            }

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