using System;
using System.Linq;
using FAuth.DataBase.Tables;
using FAuth.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace FAuth.Controllers.api
{
    /// <summary>
    /// 角色组角色对应
    /// </summary>
    public class RoleGroup_RoleController:ApiControllerBase<RoleGroup_RoleController>
    {
        public RoleGroup_RoleController(ILogger<RoleGroup_RoleController> logger,IServiceProvider service) : base(logger,service) {
        }

        /// <summary>
        /// 绑定角色组和角色
        /// </summary>
        /// <param name="roleGroupId">角色组编号</param>
        /// <param name="roleId">角色组</param>
        /// <returns>是否成功</returns>
        [HttpPost]
        public bool Binding(int roleGroupId,int roleId) {
            var rgQu = this.Db.RoleGroups.Where(m => m.Id == roleGroupId);
            if(!rgQu.Any()) {
                throw new ApiException("没有找到指定的角色组");
            }
            var rQu = this.Db.Roles.Where(m => m.Id == roleId);
            if(!rQu.Any()) {
                throw new ApiException("没有找到指定的角色");
            }
            var rgr = this.Db.RoleGroup_Roles.Where(m => m.RoleGroupId == roleGroupId && m.RoleId == roleId);
            if(!rgr.Any()) {
                this.Db.RoleGroup_Roles.Add(new RoleGroup_Role {
                    RoleGroupId = roleGroupId,
                    RoleId = roleId,
                });
                this.Db.SaveChangesAsync().Wait();
            }
            return true;
        }

        /// <summary>
        /// 角色组角色解除绑定
        /// </summary>
        /// <param name="roleGroupId">角色组编号</param>
        /// <param name="roleId">角色编号</param>
        /// <returns>是否成功</returns>
        [HttpPost]
        public bool Unbind(int roleGroupId,int roleId) {
            var rgQu = this.Db.RoleGroups.Where(m => m.Id == roleGroupId);
            if(!rgQu.Any()) {
                throw new ApiException("没有找到指定的角色组");
            }
            var rQu = this.Db.Roles.Where(m => m.Id == roleId);
            if(!rQu.Any()) {
                throw new ApiException("没有找到指定的角色");
            }
            var rgr = this.Db.RoleGroup_Roles.Where(m => m.RoleGroupId == roleGroupId && m.RoleId == roleId);
            if(rgr.Any()) {
                foreach(var item in rgr) {
                    this.Db.Entry(item).State = EntityState.Deleted;
                }
                this.Db.SaveChangesAsync().Wait();
            }
            return true;
        }
    }
}
