using AutoMapper;
using Tiobon.Core.Common;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.IServices;
using Tiobon.Core.Model.Models;
using Tiobon.Core.Model.ViewModels;
using Tiobon.Core.Services.BASE;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Tiobon.Core.Services
{
    public class TiobonArticleServices : BaseServices<TiobonArticle>, ITiobonArticleServices
    {
        IMapper _mapper;
        public TiobonArticleServices(IMapper mapper)
        {
            this._mapper = mapper;
        }
        /// <summary>
        /// 获取视图博客详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<TiobonViewModels> GetTiobonDetails(long id)
        {
            // 此处想获取上一条下一条数据，因此将全部数据list出来，有好的想法请提出
            //var Tiobonlist = await base.Query(a => a.IsDeleted==false, a => a.bID);
            var TiobonArticle = (await base.Query(a => a.bID == id && a.bcategory == "技术博文")).FirstOrDefault();

            TiobonViewModels models = null;

            if (TiobonArticle != null)
            {
                models = _mapper.Map<TiobonViewModels>(TiobonArticle);

                //要取下一篇和上一篇，以当前id开始，按id排序后top(2)，而不用取出所有记录
                //这样在记录很多的时候也不会有多大影响
                var nextTiobons = await base.Query(a => a.bID >= id && a.IsDeleted == false && a.bcategory == "技术博文", 2, "bID");
                if (nextTiobons.Count == 2)
                {
                    models.next = nextTiobons[1].btitle;
                    models.nextID = nextTiobons[1].bID;
                }
                var prevTiobons = await base.Query(a => a.bID <= id && a.IsDeleted == false && a.bcategory == "技术博文", 2, "bID desc");
                if (prevTiobons.Count == 2)
                {
                    models.previous = prevTiobons[1].btitle;
                    models.previousID = prevTiobons[1].bID;
                }

                TiobonArticle.btraffic += 1;
                await base.Update(TiobonArticle, new List<string> { "btraffic" });
            }

            return models;

        }


        /// <summary>
        /// 获取博客列表
        /// </summary>
        /// <returns></returns>
        [Caching(AbsoluteExpiration = 10)]
        public async Task<List<TiobonArticle>> GetTiobons()
        {
            var Tiobonlist = await base.Query(a => a.bID > 0, a => a.bID);

            return Tiobonlist;

        }
    }
}
