using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using GxPress.Common.AppOptions;
using GxPress.Common.Exceptions;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.EnumConst;
using GxPress.Repository.Interface;
using GxPress.Request.App.GroupUser;
using GxPress.Request.App.Middle;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using SqlKata;
using Datory;
using Dapper;

namespace GxPress.Repository.Implement
{
    public class GroupUserRepository : IGroupUserRepository
    {
        private readonly Repository<GroupUser> _repository;
        private readonly IMapper _mapper;
        private readonly IWebHostEnvironment _environment;
        private readonly Repository<Group> _groupRepository;
        private readonly string _connectionString;
        private readonly string _databaseTypeStr;
        public GroupUserRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper,
            IWebHostEnvironment environment)
        {
            _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
            _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
            var databaseType =
                StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<GroupUser>(database);
            _groupRepository = new Repository<Group>(database);
            _environment = environment;
            _mapper = mapper;
        }

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

        /// <summary>
        /// 修改角色权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(GroupUserUpRequest request)
        {
            if (request.RoleId == GroupUserRoleTyeConst.SuperAdmin)
                throw new BusinessException("已存在");
            return await _repository.UpdateAsync(Q.Set(nameof(GroupUser.GroupUserRoleId), request.RoleId)
                       .Where(nameof(GroupUser.Id), request.Id)) > 0;
        }

        public async Task<bool> DeleteAsync(Query query)
        {
            return await _repository.DeleteAsync(query) > 0;
        }


        /// <summary>
        /// 根据小组ID获取成员
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<GroupUser>> FindGroupUserAsync(GroupUserFindRequest request)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(GroupUser.GroupId), request.GroupId));
        }
        /// <summary>
        /// 插入用户
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="groupId"></param>
        /// <param name="groupUserRoleId"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(int userId, int groupId, GroupUserRoleTyeConst groupUserRoleId)
        {
            GroupUser groupUser = new GroupUser { GroupId = groupId, UserId = userId, GroupUserRoleId = groupUserRoleId, IsUDisturb = false };
            return await _repository.InsertAsync(groupUser);
        }


        public async Task<GroupUser> GetAsync(Query q)
        {
            return await _repository.GetAsync(q);
        }

        public async Task<IEnumerable<GroupUser>> GetAllAsync(Query q)
        {
            return await _repository.GetAllAsync(q);
        }

        public async Task<int> InsertAsync(GroupUser groupUser)
        {
            return await _repository.InsertAsync(groupUser);
        }

        public async Task<bool> InsertAsync(List<GroupUser> groupUsers)
        {
            string sql = @"INSERT INTO `ccpph`.`tede_group_user`
                                                            (`Guid`,
                                                            `CreatedDate`,
                                                            `LastModifiedDate`,
                                                            `GroupId`,
                                                            `UserId`,
                                                            `GroupUserRoleId`,
                                                            `IsUDisturb`)
                                                            VALUES";
            if (groupUsers.Count == 0)
                return false;
            foreach (var item in groupUsers)
            {
                var guId = Guid.NewGuid().ToString();
                var createdDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                var IsUDisturb = item.IsUDisturb ? 1 : 0;
                sql += $@"('{guId}','{createdDate}','{createdDate}',{item.GroupId},{item.UserId},{item.GroupUserRoleId.GetHashCode()},{IsUDisturb}),";
            }
            sql = sql.Remove(sql.Length - 1, 1);
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var result = await connection.ExecuteAsync(sql);
            return result > 0;
        }
        /// <summary>
        /// 设置用户是否免打扰
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> SetIsUDisturbAsync(int groupId, int userId)
        {
            var groupUser = await _repository.GetAsync(Q.Where(nameof(GroupUser.GroupId), groupId)
                .Where(nameof(GroupUser.UserId), userId));
            return await _repository.UpdateAsync(Q.Set(nameof(GroupUser.IsUDisturb), !groupUser.IsUDisturb)
                       .Where(nameof(GroupUser.GroupId), groupId)
                       .Where(nameof(GroupUser.UserId), userId)) > 0;
        }
    }
}
