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

namespace GxPress.Repository.Implement.Collection
{
    public class CollectionRepository : ICollectionRepository
    {
        private readonly Repository<Entity.Collection> _repository;
        private readonly Repository<Entity.Middle.Middle> _middleRepository;
        private readonly Repository<Entity.Analyze.Analyze> _analyzeRepository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypestr;
        public CollectionRepository(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<Entity.Collection>(database);
            _middleRepository = new Repository<Entity.Middle.Middle>(database);
            _analyzeRepository = new Repository<Entity.Analyze.Analyze>(database);
            _mapper = mapper;
        }

        public IDatabase Database => _repository.Database;
        public string TableName => _repository.TableName;
        public List<TableColumn> TableColumns => _repository.TableColumns;
        /// <summary>
        /// 添加收藏
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(Entity.Collection collection)
        {
            return await _repository.InsertAsync(collection);
        }

        /// <summary>
        /// 查询结果
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<CollectionListPageResult>> PageListAsync(CollectionPageSearchRequest request)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var items = await connection
                .QueryAsync<CollectionListPageResult, Entity.Collection, CollectionListPageResult>(GetCollectionSql(request),
                    (collectionListPageResult, collection) =>
                    {
                        if (collectionListPageResult == null)
                            throw new ArgumentNullException(nameof(collectionListPageResult));
                        //collectionListPageResult= _mapper.Map<CollectionListPageResult>(middle);
                        collectionListPageResult.Title = collection == null ? "" : collection.Title;
                        collectionListPageResult.CollectionDataId = collection?.CollectionDataId ?? 0;
                        collectionListPageResult.CollectionType = collection?.CollectionType ?? 0;
                        collectionListPageResult.SourceUserId = collection?.SourceUserId ?? 0;
                        collectionListPageResult.CollectionId = collection?.Id ?? 0;
                        return collectionListPageResult;
                    },
                    splitOn: "MiddleId,Id");

            PagedList<CollectionListPageResult> result = new PagedList<CollectionListPageResult>
            {
                Total = await CountAsync(GetCollectionSqlCount(request)),
                Items = items
            };
            return result;
        }
        /// <summary>
        /// 集合
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetCollectionSql(CollectionPageSearchRequest request)
        {
            string sql = "";

            if (request.VisitUserId > 0)
            {

                sql =
                    $@"SELECT  a.*,(SELECT GROUP_CONCAT(SourceName Separator'、') from tede_user_middle where MiddleType=3 and DataSourceId=a.MiddleSonId) as EnjoyUser,(select count(1) from tede_middle where ParentId=a.Id) as FileCount, b.* FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_collection b ON a.MiddleId = b.Id WHERE a.UserId = {request.VisitUserId} AND a.FolderType = 3 AND a.IsDelete = 0";
                if (request.FolderId == 0)
                    sql += @" AND(a.RoleId = 1 OR a.RoleId = 3) AND a.ParentId = 0";
                else
                    sql += $" and a.ParentId={request.FolderId}";
                if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                sql +=
                    $@" OR a.id IN(SELECT MiddleId FROM ccpph.tede_folder_user WHERE UserId = {request.UserId}) AND a.FolderType = 3 AND a.UserId = {request.VisitUserId}";
                if (request.FolderId > 0)
                    sql += $" and a.ParentId={request.FolderId}";
                if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                sql +=
                    $@" ORDER BY a.IsTop DESC,a.Sort desc,a.AttributeValue desc, a.LastModifiedDate DESC";
                if (request.Page > 0)
                    sql += $" LIMIT {(request.Page - 1) * request.PerPage},{request.PerPage}";
            }
            else
            {
                sql =
                    $@"SELECT a.*,(SELECT GROUP_CONCAT(SourceName Separator'、') from tede_user_middle where MiddleType=3 and DataSourceId=a.MiddleSonId) as EnjoyUser,(select count(1) from tede_middle where ParentId=a.Id) as FileCount, b.* FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_collection b ON a.MiddleId = b.Id WHERE a.UserId = {request.UserId} AND a.FolderType = 3 AND a.IsDelete = 0";
                if (!string.IsNullOrEmpty(request.SearchKey) && request.FolderId > 0)
                {
                    sql += $" AND a.ParentId={request.FolderId}";
                    sql += $@" AND (b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                }
                else if (!string.IsNullOrEmpty(request.SearchKey))
                {
                    sql += $@" AND (b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                }
                else
                    sql += $" and a.ParentId={request.FolderId}";
                sql += $@" ORDER BY  a.IsTop DESC,a.Sort desc,a.AttributeValue desc, a.LastModifiedDate DESC";
                if (request.Page > 0)
                    sql += $" LIMIT {(request.Page - 1) * request.PerPage},{request.PerPage}";
            }

            return sql;
        }
        /// <summary>
        /// 条数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetCollectionSqlCount(CollectionPageSearchRequest request)
        {
            string sql = "";

            if (request.VisitUserId > 0)
            {

                sql =
                    $@"SELECT  count(1) FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_collection b ON a.MiddleId = b.Id WHERE a.UserId = {request.VisitUserId} AND a.FolderType = 3 AND a.IsDelete = 0";
                if (request.FolderId == 0)
                    sql += @" AND(a.RoleId = 1 OR a.RoleId = 3) AND a.ParentId = 0";
                else
                    sql += $" and a.ParentId={request.FolderId}";
                if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                sql +=
                    $@" OR a.id IN(SELECT MiddleId FROM ccpph.tede_folder_user WHERE UserId = {request.UserId}) AND a.FolderType = 3 AND a.UserId = {request.VisitUserId}";
                if (request.FolderId > 0)
                    sql += $" and a.ParentId={request.FolderId}";
                if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" AND (b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";

            }
            else
            {
                sql =
                    $@"SELECT count(1) FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_collection b ON a.MiddleId = b.Id WHERE a.UserId = {request.UserId} AND a.FolderType = 3 AND a.IsDelete = 0";
                if (!string.IsNullOrEmpty(request.SearchKey) && request.FolderId > 0)
                {
                    sql += $" AND a.ParentId={request.FolderId}";
                    sql += $@" AND (b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                }
                else if (!string.IsNullOrEmpty(request.SearchKey))
                {
                    sql += $@" AND (b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%')";
                }
                else
                    sql += $" and a.ParentId={request.FolderId}";
            }

            return sql;
        }
        public async Task<int> CountAsync(string sql)
        {

            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var items = await connection.ExecuteScalarAsync<int>(sql);
            return items;
        }
        /// <summary>
        /// 根据ID获取收藏数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Entity.Collection> GetAsync(int id)
        {
            return await _repository.GetAsync(id);
        }

        public async Task<Entity.Collection> GetAsync(SqlKata.Query query)
        {
            return await _repository.GetAsync(query);
        }

        public async Task<bool> DeleteAsync(Query query)
        {
            return await _repository.DeleteAsync(query) > 0;
        }
        /// <summary>
        /// 递归删除收藏包括文件夹下面的数据
        /// </summary>
        /// <param name="middleIds"></param>
        /// <returns></returns>
        public async Task<bool> RecursionDeleteAsync(List<int> middleIds)
        {
            foreach (var item in middleIds)
            {
                await DeleteParendIdAsync(item);
            }
            return true;
        }

        public async Task<bool> DeleteParendIdAsync(int parentId)
        {
            var middle = await _middleRepository.GetAsync(parentId);
            if (middle == null)
                return true;
            //删除middle
            await _middleRepository.DeleteAsync(middle.Id);
            //删除coll
            await _repository.DeleteAsync(middle.MiddleId);
            //删除收藏
            var query = new SqlKata.Query();
            query.Where(nameof(Entity.Analyze.Analyze.SourceId), middle.MiddleId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), 3).Where(nameof(Entity.Analyze.Analyze.UserId), middle.UserId);
            await _analyzeRepository.DeleteAsync(query);
            var middles = await _middleRepository.GetAllAsync(Q.Where(nameof(Entity.Middle.Middle.ParentId), parentId));
            if (middles.Count == 0)
                return true;
            foreach (var item in middles)
            {
                //删除middle
                await _middleRepository.DeleteAsync(item.Id);
                //删除coll
                await _repository.DeleteAsync(item.MiddleId);
                //删除收藏
                query = new SqlKata.Query();
                query.Where(nameof(Entity.Analyze.Analyze.SourceId), item.MiddleId).Where(nameof(Entity.Analyze.Analyze.AnalyzeType), 3).Where(nameof(Entity.Analyze.Analyze.UserId), middle.UserId);
                await _analyzeRepository.DeleteAsync(query);
                await DeleteParendIdAsync(item.Id);
            }
            return true;
        }
        public async Task<bool> DeleteAsync(int id)
        {
            return await _repository.DeleteAsync(id);
        }

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