using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using Dapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Entity.Topic;
using GxPress.Repository.Interface.Topic;
using GxPress.Request.App.Topic;
using GxPress.Result.App.Topic;
using Microsoft.Extensions.Options;
using SqlKata;

namespace GxPress.Repository.Implement.Topic
{
    public class TopicGroupUserRepository:ITopicGroupUserRepository
    {
        private readonly Repository<TopicGroupUser> _repository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypestr;
        public TopicGroupUserRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            _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<TopicGroupUser>(database);
            _mapper = mapper;
        }
        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;
        public async Task<TopicGroupUser> GetAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

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

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(List<int> ids)
        {
            return await _repository.DeleteAsync(Q.WhereIn(nameof(TopicGroupUser.Id), ids))>0;
        }

        public async Task<bool> InsertAsync(TopicGroupUser topicGroupUser)
        {
            return await _repository.InsertAsync(topicGroupUser)>0;
        }

        /// <summary>
        /// 根据GroupId删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteGroupIdAsync(List<int> ids)
        {
            return await _repository.DeleteAsync(Q.WhereIn(nameof(TopicGroupUser.TopicGroupId), ids)) > 0;
        }
        /// <summary>
        /// 添加成员
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="topicGroupId"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(List<int> userIds, int topicGroupId)
        {
            try
            {
                using (TransactionScope transactionScope=new TransactionScope())
                {
                    //获取话题小组成员
                    var groupUsers =
                        await _repository.GetAllAsync(Q.Where(nameof(TopicGroupUser.TopicGroupId), topicGroupId));
                    foreach (var userId in userIds)
                    {
                        if (groupUsers.Any(n => n.UserId == userId))
                            continue;
                        var topicGroupUser = new TopicGroupUser {TopicGroupId = topicGroupId, UserId = userId};
                        await _repository.InsertAsync(topicGroupUser);
                    }
                    transactionScope.Complete();
                }
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
       

        /// <summary>
        /// 根据分组ID查询用户
        /// </summary>
        /// <param name="topicGroupIds"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicGroupUserResult>> GetTopicGroupUserById( int topicGroupId)
        {
            var result = new PagedList<TopicGroupUserResult>();
            string sql =
                $"SELECT a.*,b.Name,b.AvatarUrl FROM ccpph.tede_topic_group_user a inner join ccpph.tede_user b on a.UserId=b.Id where 1=1 and a.TopicGroupId={topicGroupId}";
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            result.Items =
                await connection
                    .QueryAsync<TopicGroupUserResult, User, TopicGroupUserResult>(sql,
                        (topicGroupUserResult, user) =>
                        {
                            topicGroupUserResult.Name = user.Name;
                            topicGroupUserResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
                            return topicGroupUserResult;
                        }, splitOn: "Name");
            result.Total = result.Items.Count();
            return result;
        }

        /// <summary>
        /// 根据分组ID和姓名查询用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<TopicGroupUserResult>> SearchTopicGroupUsersAsync(SearchTopicGroupUsersRequest request)
        {
            var result = new PagedList<TopicGroupUserResult>();
            string sql =
                $"SELECT a.*,b.Name,b.AvatarUrl FROM ccpph.tede_topic_group_user a inner join ccpph.tede_user b on a.UserId=b.Id where a.TopicGroupId={request.TopicGroupId} and b.Name like '%{request.Key}%'";
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            result.Items =
                await connection
                    .QueryAsync<TopicGroupUserResult, User, TopicGroupUserResult>(sql,
                        (topicGroupUserResult, user) =>
                        {
                            topicGroupUserResult.Name = user.Name;
                            topicGroupUserResult.AvatarUrl = StringUtils.AddDomain(user.AvatarUrl);
                            return topicGroupUserResult;
                        }, splitOn: "Name");
            result.Total = result.Items.Count();
            return result;
        }

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

        public async Task<int> CountAsync(Query query)
        {
            return await _repository.CountAsync(query);
        }

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