using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Service;
using Home.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq.Expressions;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.EntitiesExtension;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace Home.Controllers
{
    public class ArticleController : MvcBaseController
    {
        ArticleService m_ArticleServce;

        public ArticleController(ArticleService _ArticleServce)
        {
            m_ArticleServce = _ArticleServce;
        }


        [HttpGet]
        public async Task<IActionResult> Index([FromQuery]ArticleSearchModel request)
        {
            request = request ?? new ArticleSearchModel();
            Expression<Func<ArticleEntity, bool>> exp = m => 1 == 1;
            if (request.Catalog > 0)
            {
                exp = exp.And(m => m.CatalogId == request.Catalog);
            }      

            if (request.KeyWord.Has())
            {
                exp = exp.And(m => m.Title.Contains(request.KeyWord) || m.SubTitle.Contains(request.KeyWord));
            }

            var ret = await m_ArticleServce.Page(request.PageIndex, request.PageSize, exp);

            return View(ret);
        }


        [HttpGet]
        public async Task<IActionResult> Search([FromQuery]ArticleSearchModel request)
        {
            request = request ?? new ArticleSearchModel();
            Expression<Func<ArticleEntity, bool>> exp = m => 1 == 1;
            if (request.Catalog > 0)
            {
                exp = exp.And(m => m.CatalogId == request.Catalog);
            }

            if (request.KeyWord.Has())
            {
                exp = exp.And(m => m.Title.Contains(request.KeyWord) || m.SubTitle.Contains(request.KeyWord));
            }

            var ret = await m_ArticleServce.Page(request.PageIndex, request.PageSize, exp);

            return View(ret);
        }


        [HttpGet]
        public async Task<IActionResult> Info(int id)
        {
            var prev = await m_ArticleServce.Query(m => m.Id < id).OrderByDescending(m => m.Id).FirstOrDefaultAsync();
            var ret = await m_ArticleServce.GetById(id);
            var next = await m_ArticleServce.Query(m => m.Id > id).OrderBy(m => m.Id).FirstOrDefaultAsync();
            return View(new ArticleInfoMode()
            {

                Prev = prev,
                Info = ret,
                Next = next
            });
        }

        [HttpGet]
        public IActionResult TaoBao()
        {
            return View();
        }

    }
}
