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

namespace GxPress.Repository.Implement.Topic
{
    public class TopicGroupRepository : ITopicGroupRepository
    {
        private readonly Repository<TopicGroup> _repository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypestr;
        public TopicGroupRepository(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<TopicGroup>(database);
            _mapper = mapper;
        }
        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;

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

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="topicGroup"></param>
        /// <returns></returns>
        public async Task<bool> InsertAsync(TopicGroup topicGroup)
        {
            var id = await _repository.InsertAsync(topicGroup) > 0;
            return await _repository.UpdateAsync(Q.Set(nameof(TopicGroup.Sort), id).Where(nameof(TopicGroup.Id), id)) >
                   0;
        }

        /// <summary>
        /// 根据用户ID获取分组
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<IEnumerable<TopicGroup>> GetTopicGroupsAsync(int userId)
        {
            return await _repository.GetAllAsync(Q.Where(nameof(TopicGroup.UserId), userId)
                .OrderByDesc(nameof(TopicGroup.Sort)));
        }
        /// <summary>
        /// 修改分组名称
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(TopicGroupInRequest request)
        {
            return await _repository.UpdateAsync(Q.Set(nameof(TopicGroup.Name), request.Name)
                       .Where(nameof(TopicGroup.Id), request.Id)) > 0;
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="firstId"></param>
        /// <param name="secondId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> MoveSortAsync(int firstId, int secondId, int userId)
        {
            //获取第一个
            var topicGroupFirst = await _repository.GetAsync(firstId);
            //获取第二个数据
            var topicGroupSecond = await _repository.GetAsync(secondId);
            var sort = 0;
            var databaseType = _databaseTypestr.ToEnum<DatabaseType>(DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            if (topicGroupFirst.Sort < topicGroupSecond.Sort)
            {
                //修改第一个排序
                await _repository.UpdateAsync(Q.Set(nameof(TopicGroupUser.Sort), topicGroupSecond.Sort)
                    .Where(nameof(TopicGroup.Id), firstId));
                sort = topicGroupSecond.Sort;
                var sql =
                    $"update ccpph.tede_topic_group set Sort=Sort-1 where UserId={userId}  and Sort<={sort} and Id not in({firstId}) and id>0";
                return await connection.ExecuteAsync(sql) > 0;
            }
            else
            {
                //修改第一个排序
                await _repository.UpdateAsync(Q.Set(nameof(TopicGroupUser.Sort), topicGroupSecond.Sort)
                    .Where(nameof(TopicGroup.Id), firstId));
                sort = topicGroupSecond.Sort;
                var sql =
                    $"update ccpph.tede_topic_group set Sort=Sort+1 where UserId={userId}  and Sort>={sort} and Id not in({firstId}) and id>0";
                return await connection.ExecuteAsync(sql) > 0;
            }
        }

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