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.Entity;
using GxPress.Repository.Interface.Note;
using GxPress.Request.App.Note;
using GxPress.Result.App.Note;
using Microsoft.Extensions.Options;

namespace GxPress.Repository.Implement.Note
{
    public class NoteRepository : INoteRepository
    {
        private readonly Repository<Entity.Note.Note> _repository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypestr;
        public NoteRepository(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.Note.Note>(database);
            _mapper = mapper;
        }

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

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

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

        public async Task<int> InsertAsync(Entity.Note.Note note)
        {
            return await _repository.InsertAsync(note);
        }

        public async Task<bool> UpdateAsync(Entity.Note.Note note)
        {
            return await _repository.UpdateAsync(note);
        }
        public async Task<bool> UpdateAsync(SqlKata.Query query)
        {
            return await _repository.UpdateAsync(query) > 0;
        }
        /// <summary>
        /// 获取笔记分页
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<NotePageListRequest>> NotePageListAsync(NoteSearchPageListRequest request)
        {

            var pagedList = new PagedList<NotePageListRequest>();
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var result =
                await connection
                    .QueryAsync<NotePageListRequest, Entity.Note.Note, User, Department, NotePageListRequest>(GetCollectionSql(request),
                        (notePageListRequest, note, user, department) =>
                        {
                            notePageListRequest.Title = note == null ? "" : note.Title;
                            notePageListRequest.Content = note == null ? "" : note.Content;
                            notePageListRequest.Name = user == null ? "" : user.Name;
                            notePageListRequest.AvatarUrl = user == null ? "" : StringUtils.AddDomainMin(user.AvatarUrl);
                            notePageListRequest.DepartmentName = department == null ? "" : department.Name;
                            notePageListRequest.ReadCount = note == null ? 0 : note.ReadCount;
                            notePageListRequest.NickName = user == null ? "" : user.Nick;
                            return notePageListRequest;
                        }, splitOn: "Title,Name,Name");

            pagedList.Items = result;
            pagedList.Total = await NotePageListCountAsync(GetCollectionSqlCount(request));
            return pagedList;
        }

        /// <summary>
        /// 集合
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetCollectionSql(NoteSearchPageListRequest request)
        {
            string sql = "";
            if (request.VisitUserId > 0)
            {
                sql =
                    $@"SELECT a.*,(SELECT GROUP_CONCAT(SourceName Separator'、') from tede_user_middle where MiddleType=4 and DataSourceId=a.MiddleSonId) as EnjoyUser,(SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 1) AS PraiseCount,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 1
                LIMIT 0 , 1) AS IsPraise,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_comment
                WHERE
                     ArticleId =  a.MiddleId and pid=0
                        AND TypeValue = 3) AS CommentCount,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 4) AS RetransmissionCount,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 4
                LIMIT 0 , 1) AS IsRetransmission,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 4
                LIMIT 0 , 1) AS IsCollect,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_analyze
                WHERE
                    UserId = {request.UserId} AND TypeValue = 3
                        AND SourceId = a.MiddleId
                        AND AnalyzeType = 4) AS CollectCount,
            (SELECT 
                    COUNT(1)
                FROM
                    ccpph.tede_middle
        WHERE
            ParentId = a.Id and IsDelete=0) FileCount, b.Title, b.Content,b.ReadCount,c.Name,c.AvatarUrl,c.Nick,d.Name FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_note b ON a.MiddleId = b.Id left join ccpph.tede_user c on c.Id=b.UserId left join ccpph.tede_department d on d.Id=c.DepartmentId
                        WHERE a.UserId = {request.VisitUserId} AND a.FolderType = 4 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}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                sql +=
                    $@" OR a.id IN(SELECT MiddleId FROM ccpph.tede_folder_user WHERE UserId = {request.UserId}) AND a.FolderType = 4 AND a.UserId = {request.VisitUserId}";
                if (request.FolderId == 0 && !string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" and a.ParentId={request.FolderId}  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else
                    sql += $" and a.ParentId={request.FolderId}";
                sql +=
                    $@" ORDER BY a.IsTop 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=4 and DataSourceId=a.MiddleSonId) as EnjoyUser,(SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 1) AS PraiseCount,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 1
        LIMIT 0 , 1) AS IsPraise,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_comment
        WHERE
            UserId = {request.UserId} AND ArticleId =  a.MiddleId
                AND TypeValue = 3) AS CommentCount,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 4) AS RetransmissionCount,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 4
        LIMIT 0 , 1) AS IsRetransmission,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 4
        LIMIT 0 , 1) AS IsCollect,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_analyze
        WHERE
            UserId = {request.UserId} AND TypeValue = 3
                AND SourceId = a.MiddleId
                AND AnalyzeType = 4) AS IsCollect,
    (SELECT 
            COUNT(1)
        FROM
            ccpph.tede_middle
        WHERE
            ParentId = a.Id and IsDelete=0) FileCount, b.Title, b.Content,b.ReadCount,c.Name,c.AvatarUrl,d.Name FROM ccpph.tede_middle a  LEFT JOIN ccpph.tede_note b ON a.MiddleId = b.Id left join ccpph.tede_user c on c.Id=b.UserId left join ccpph.tede_department d on d.Id=c.DepartmentId WHERE a.UserId = {request.UserId} AND a.FolderType = 4 AND a.IsDelete = 0";
                if (request.FolderId == 0 && !string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" and a.ParentId={request.FolderId}  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(NoteSearchPageListRequest request)
        {
            string sql = "";

            if (request.VisitUserId > 0)
            {
                sql =
                    $@"SELECT  count(1) FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_note b ON a.MiddleId = b.Id WHERE a.UserId = {request.VisitUserId} AND a.FolderType = 4 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}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                sql +=
                    $@" OR a.id IN(SELECT MiddleId FROM ccpph.tede_folder_user WHERE UserId = {request.UserId}) AND a.FolderType = 4 AND a.UserId = {request.VisitUserId}";
                if (request.FolderId == 0 && !string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" and a.ParentId={request.FolderId}  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else
                    sql += $" and a.ParentId={request.FolderId}";
            }
            else
            {
                sql =
                    $@"SELECT  count(1) FROM ccpph.tede_middle a LEFT JOIN ccpph.tede_note b ON a.MiddleId = b.Id left join ccpph.tede_user c on c.Id=b.UserId left join ccpph.tede_department d on d.Id=c.DepartmentId WHERE a.UserId = {request.UserId} AND a.FolderType = 4 AND a.IsDelete = 0";
                if (request.FolderId == 0 && !string.IsNullOrEmpty(request.SearchKey))
                    sql += $@"  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else if (!string.IsNullOrEmpty(request.SearchKey))
                    sql += $@" and a.ParentId={request.FolderId}  AND(b.Title LIKE '%{request.SearchKey}%' OR a.FolderName LIKE '%{request.SearchKey}%' or b.Content LIKE '%{request.SearchKey}%' or b.UserId in (select Id from tede_user where name like '%{request.SearchKey}%'))";
                else
                    sql += $" and a.ParentId={request.FolderId}";
            }

            return sql;
        }

        public async Task<int> NotePageListCountAsync(string sql)
        {
            var pagedList = new PagedList<NotePageListRequest>();
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var result =
                await connection
                    .ExecuteScalarAsync<int>(sql);
            return result;
        }
        /// <summary>
        /// 删除笔记
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(int id) => await _repository.DeleteAsync(id);
    }

}

