using System.Collections.Generic;
using System.Threading.Tasks;
using System.Transactions;
using AutoMapper;
using GxPress.Common.AppOptions;
using GxPress.Common.Exceptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Entity;
using GxPress.Repository.Interface;
using GxPress.Request.Thesaurus;
using Microsoft.Extensions.Options;
using Datory;
using Dapper;

namespace GxPress.Repository.Implement
{
    public class ThesaurusRepository : IThesaurusRepository
    {
        private readonly Repository<Thesaurus> _repository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypeStr;
        public ThesaurusRepository(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<Thesaurus>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;
        /// <summary>
        /// 查询词库名称是否存在
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(string account)
        {
            return await _repository.ExistsAsync(Q.Where(nameof(Thesaurus.ThesaurusName), account));
        }
        /// <summary>
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Thesaurus> GetAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

        public async Task<bool> InsertAsync(Thesaurus thesaurus)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                foreach (var item in StringUtils.StringCollectionToStringList(thesaurus.ThesaurusName))
                {
                    thesaurus.ThesaurusName = item;
                    await _repository.InsertAsync(thesaurus);
                }
                transactionScope.Complete();
            }
            return true;
        }

        public async Task<bool> UpdateAsync(Thesaurus thesaurus)
        {
            return await _repository.UpdateAsync(thesaurus);
        }
        /// <summary>
        /// 获取词库分页数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        public async Task<PagedList<Thesaurus>> GetPageList(ThesaurusPageSearchRequest request)
        {

            var pagedList = new PagedList<Thesaurus>
            {
                Total = await GetCountAsync(request)
            };
            var list = await GetPageListAsync(request);
            pagedList.Items = list;
            return pagedList;
        }

        /// <summary>
        /// 获取词库分页结果
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Thesaurus>> GetPageListAsync(ThesaurusPageSearchRequest request)
        {
            var query = Q.NewQuery();
            if (!string.IsNullOrEmpty(request.ThesaurusName))
                query.WhereLike(nameof(Thesaurus.ThesaurusName), request.ThesaurusName);
            if (request.ThesaurusType > 0)
                query.Where(nameof(Thesaurus.ThesaurusType), request.ThesaurusType);
            query.ForPage(request.Page, request.PerPage);
            return await _repository.GetAllAsync(query);
        }
        /// <summary>
        /// 获取词库条数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(ThesaurusPageSearchRequest request)
        {
            var query = Q.NewQuery();
            if (!string.IsNullOrEmpty(request.ThesaurusName))
                query.WhereLike(nameof(Thesaurus.ThesaurusName), request.ThesaurusName);
            if (request.ThesaurusType > 0)
                query.Where(nameof(Thesaurus.ThesaurusType), request.ThesaurusType);
            query.ForPage(request.Page, request.PerPage);
            return await _repository.CountAsync(query);
        }

        /// <summary>
        /// 获取随机数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<IEnumerable<Thesaurus>> GetTopListAsync(ThesaurusSearchRequest request)
        {
            var sql = $"SELECT * FROM ccpph.tede_thesaurus where ThesaurusType={request.ThesaurusType} ORDER BY rand() LIMIT 3";
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var items = await connection
                .QueryAsync<Thesaurus>(sql);
            return items;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await _repository.DeleteAsync(id);
        }

        public async Task<Thesaurus> GetDetailAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

        public async Task<bool> UpdateAsync(int id, Thesaurus request)
        {
            var thesaurus = await GetAsync(id);
            if (thesaurus == null)
                throw new BusinessException("词库不存在!");
            if (!string.IsNullOrEmpty(request.ThesaurusName))
                thesaurus.ThesaurusName = request.ThesaurusName;
            if (request.ThesaurusType > 0)
                thesaurus.ThesaurusType = request.ThesaurusType;
            return await _repository.UpdateAsync(thesaurus);
        }
    }
}
