using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Datory;
using GxPress.Common.AppOptions;
using GxPress.Common.Page;
using GxPress.Common.Tools;
using GxPress.Repository.Interface.Order;
using GxPress.Request.Order;
using Microsoft.Extensions.Options;

namespace GxPress.Repository.Implement.Order
{
    public class OrderRepository : IOrderRepository
    {
        private readonly Repository<Entity.Order.Order> _repository;

        private readonly IMapper _mapper;
        public OrderRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
        {
            var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
            var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
            _repository = new Repository<Entity.Order.Order>(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<Entity.Order.Order>> GetAllOrderAsync(OrderSearchRequest request)
        {
            var result = new PagedList<Entity.Order.Order>();
            var query = Q.NewQuery();
            if (!string.IsNullOrEmpty(request.KeyWord))
                query.WhereLike(nameof(Entity.Order.Order.OrderNumber), $"%{request.KeyWord}%");
            if (request.PayWay > 0)
                query.Where(nameof(Entity.Order.Order.PayWay), request.PayWay);
            if (!string.IsNullOrEmpty(request.BeginTime) && !string.IsNullOrEmpty(request.EndTime))
            {
                if (DateTime.TryParse(request.BeginTime, out var BeginTime) && DateTime.TryParse(request.EndTime, out var EndTime))
                {
                    query.WhereTime(nameof(Entity.Order.Order.CreatedDate), ">", BeginTime);
                    query.WhereTime(nameof(Entity.Order.Order.CreatedDate), "<", EndTime);
                }
            }
            result.Total = await _repository.CountAsync(query);
            result.Items = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
            return result;
        }
    }
}