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

namespace GxPress.Repository.Implement
{
    public class FeedbackRepository : IFeedbackRepository
    {
        private readonly Repository<Feedback> _repository;
        private readonly Repository<User> _userRepository;
        private readonly IMapper _mapper;
        private readonly string _connectionString;
        private readonly string _databaseTypestr;
        public FeedbackRepository(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<Feedback>(database);
            _userRepository = new Repository<User>(database);
            _mapper = mapper;
        }

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

        /// <summary>
        /// 分页显示
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PagedList<FeedbackPageResult>> GetPagedList(FeedbackPageRequest request)
        {

            var sqlValue = "";
            //获取分页条数
            if (request.FeedbackType > 0)
                sqlValue += $" and a.FeedbackType={request.FeedbackType}";
            if (!string.IsNullOrWhiteSpace(request.KeyWord))
                sqlValue += $" and (b.Name like '%{request.KeyWord}%' or a.Content like '%{request.KeyWord}%')";
            if (!string.IsNullOrEmpty(request.BeginTime) && !string.IsNullOrEmpty(request.EndTime))
            {
                if (DateTime.TryParse(request.BeginTime, out var beginTime) && DateTime.TryParse(request.EndTime, out var endTime))
                {
                    if (endTime > beginTime)
                    {
                        sqlValue += $" and a.CreatedDate >='{beginTime.ToString("yyyy-MM-dd HH:mm:ss")}'";
                        sqlValue += $" and a.CreatedDate <='{endTime.ToString("yyyy-MM-dd HH:mm:ss")}'";
                    }
                }
            }
            var sql = $"SELECT a.*,b.Name FROM ccpph.tede_feedback a inner join ccpph.tede_user b on a.UserId=b.Id where 1=1 {sqlValue}";
            var countSql = $"SELECT count(1) FROM ccpph.tede_feedback a inner join ccpph.tede_user b on a.UserId=b.Id where 1=1 {sqlValue}";
            sql += $" order by a.CreatedDate desc  LIMIT {(request.Page - 1) * request.PerPage},{request.PerPage}";
            var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
            var database = new Database(databaseType, _connectionString);
            var connection = database.GetConnection();
            var items = await connection
                .QueryAsync<FeedbackPageResult, User, FeedbackPageResult>(sql,
                    (feedbackPageResult, user) =>
                    {
                        feedbackPageResult.Name = user == null ? "" : user.Name;
                        return feedbackPageResult;
                    },
                    splitOn: "Name");

            var total = await connection.ExecuteScalarAsync<int>(countSql);
            //获取分页条数
            var pagedList = new PagedList<FeedbackPageResult>
            {
                Total = total
            };

            pagedList.Items = items;
            return pagedList;
        }

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

        public async Task<int> InsertAsync(Feedback feedback)
        {
            return await _repository.InsertAsync(feedback);
        }
        /// <summary>
        /// 删除意见反馈
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(int id)
        {
            return await _repository.DeleteAsync(id);
        }
    }
}
