using System.Collections.Generic;
using AutoMapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Tools;
using GxPress.Repository.Interface.SystemRoleMenus;
using Microsoft.Extensions.Options;
using System.Transactions;
using System.Threading.Tasks;
using GxPress.Request.Role;

namespace GxPress.Repository.Implement.SystemRoleMenus
{
    public class SystemRoleMenusRepository : ISystemRoleMenusRepository
    {
        private readonly Repository<Entity.SystemRole.SystemRoleMenus> _repository;
        private readonly IMapper _mapper;

        public SystemRoleMenusRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Entity.SystemRole.SystemRoleMenus>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

        public async Task<IEnumerable<Entity.SystemRole.SystemRoleMenus>> GetAllAsync(int roleId)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(Entity.SystemRole.SystemRoleMenus.RoleId), roleId));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(SystemRoleMenusInRequest models)
        {
            try
            {
                using (var transactionScope = new TransactionScope())
                {
                    //删除
                    await _repository.DeleteAsync(Q.Where(nameof(Entity.SystemRole.SystemRoleMenus.RoleId), models.RoleId));
                    foreach (var item in models.SystemRoleMenuInRequest)
                    {
                        var model = new Entity.SystemRole.SystemRoleMenus();
                        model.RoleId = models.RoleId;
                        model.MenuId = item.MenuId;
                        await _repository.InsertAsync(model);
                    }
                    transactionScope.Complete();
                }
            }
            catch (System.Exception ex)
            {
                throw new Common.Exceptions.BusinessException(ex.Message);
            }
            return true;

        }
        public async Task<bool> DeleteAsync(int roleId)
        {
            return await _repository.DeleteAsync(Q.Where(nameof(Entity.SystemRole.SystemRoleMenus.RoleId), roleId)) > 0;
        }
    }
}