using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis;
using LuceneNet.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace LuceneNet.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }
        public ActionResult Find(string q,int p=1)
        {

            p = p > 0 ? p : 1;
            if (string.IsNullOrEmpty(q))
            {
                return View("Find");
            }
            else
            {
                ViewBag.SearchWord = q;
                List<Books> PageResult = Search(q, p);
                ViewBag.NowPages = ViewBag_PageCount;
                ViewBag.TotalPages = ViewBag_TotalHits;
                return View("Find", PageResult);
            }
        }
        public ActionResult Ajax(string q, int p=1)
        {
            p = p > 0 ? p : 1;
            if (string.IsNullOrEmpty(q))
            {
                return PartialView("Ajax");
            }
            else
            {
                ViewBag.SearchWord = q;
                List<Books> PageResult = Search(q, p);
                ViewBag.NowPages = ViewBag_PageCount;
                ViewBag.TotalPages = ViewBag_TotalHits;
                return PartialView("Ajax",PageResult);
            }
            
        }
        private static int ViewBag_TotalHits;
        private static int ViewBag_PageCount;
        public static List<Books> Search(string q, int p = 1)
        {
            //Stopwatch st = new Stopwatch();
            //st.Start();// 计时器
            if (p < 1)
            {
                p = 1;
            }
            if (string.IsNullOrEmpty(q))
            {
                return null;
            }
            string indexPath = AppDomain.CurrentDomain.BaseDirectory + "IndexData2";
            // "C:\\Users\\710-6\\Desktop\\LuceneNet\\LuceneNet\\LuceneNet\\IndexData2";
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader reader = IndexReader.Open(directory, true);
            IndexSearcher searcher = new IndexSearcher(reader);

            //关键词Or关系设置
            BooleanQuery queryOr = new BooleanQuery();
            Query query = null;
            //query = new TermQuery(new Term("content", q));
            //query.SetBoost(100F);
            //queryOr.Add(query, BooleanClause.Occur.SHOULD);
            string[] fileds = { "title", "content" };
            Lucene.Net.Util.Version version = Lucene.Net.Util.Version.LUCENE_29;
            Analyzer analyzer = new Lucene.Net.Analysis.PanGu.PanGuAnalyzer();
            QueryParser parser = new MultiFieldQueryParser(version, fileds, analyzer);
            foreach (string word in Filters.SplitContent.SplitWords(q))
            {
                query = parser.Parse(word);
                queryOr.Add(query, BooleanClause.Occur.SHOULD);//这里设置 条件为Or关系
                //query.Add(new Term("content", "C#"));//多个查询条件时 为且的关系
            }
            // TopScoreDocCollector盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(10000, true);
            // searcher.Search(query, null, collector);//根据query查询条件进行查询，查询结果放入collector容器

            searcher.Search(queryOr, null, collector);

            //searcher.Search(queryOr, , collector);

            // int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            // int pageSize = Request["rows"] == null ? 20 : int.Parse(Request["rows"]); // 分页
            // TopDocs 指定0到GetTotalHits() 即所有查询结果中的文档 如果TopDocs(20,10)则意味着获取第20-30之间文档内容 达到分页的效果
            int totalHits = (int)Math.Ceiling(Convert.ToDecimal(collector.GetTotalHits() / 9)); // collector.GetTotalHits()总记录数

            ViewBag_TotalHits = totalHits; // 总页码
            p = p > totalHits ? totalHits : p;
            ViewBag_PageCount = p; // 当前
            p = 9 * p - 9;
            ScoreDoc[] docs = collector.TopDocs(p, 9).scoreDocs;// 每次取9条数据  可以通过它实现LuceneNet搜索结果分页 TopDocs(a, b) a 开始位置 b 几条数据
            List<Books> PageResult = new List<Books>();
            for (int i = 0; i < docs.Length; i++)
            {
                int docId = docs[i].doc;
                Document doc = searcher.Doc(docId);

                Books Books = new Books();
                Books.Title = doc.Get("title");
                Books.ContentDescription = Filters.SplitContent.HightLight(q, doc.Get("content"));
                // 判断高亮之后的长度是否越界
                //if (System.Text.Encoding.Default.GetByteCount(doc.Get("content")) < 60)
                //{
                //    Page.ContentDescription += "<br /><br />";
                //}
                Books.Id = Convert.ToInt32(doc.Get("id"));
               
                PageResult.Add(Books);
            }
            //st.Stop();// 计时器结束
            return PageResult;
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
