package app

import (
	. "code.hoteas.com/golang/hotime"
	. "code.hoteas.com/golang/hotime/common"
	"time"
)

var ArticleCtr = Ctr{
	"info": func(that *Context) {
		sn := that.Req.FormValue("sn")
		article := that.Db.Get("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "article.*,ctg_article.ctg_id AS sctg_id", Map{"ctg_article.sn": sn})
		if article == nil {
			that.Display(4, "找不到对应数据")
			return
		}
		ctgId := article.GetCeilInt64("sctg_id")
		ctg := that.Db.Get("ctg", "*", Map{"id": ctgId})
		parents := []Map{}
		parentId := ctg.GetCeilInt64("parent_id")
		article["tongji"] = that.Db.Select("ctg", "sn,name,img,parent_id", Map{"parent_id": parentId})
		for true {

			if parentId == 0 {
				break
			}

			parent := that.Db.Get("ctg", "sn,name,img,parent_id", Map{"id": parentId})
			if parent == nil {
				break
			}

			parents = append(parents, parent)
			parentId = parent.GetCeilInt64("parent_id")

		}

		ctg["parents"] = parents

		article["ctg"] = ctg
		that.Display(0, article)
	},
	"list": func(that *Context) {
		sn := that.Req.FormValue("ctg_sn") //ctgsn
		page := ObjToInt(that.Req.FormValue("page"))
		pageSize := ObjToInt(that.Req.FormValue("pageSize"))

		if page == 0 {
			page = 1
		}
		if pageSize == 0 {
			pageSize = 10
		}

		keywords := that.Req.FormValue("keywords")

		lunbo := ObjToInt(that.Req.FormValue("lunbo"))

		sort := that.Req.FormValue("sort")

		where := Map{"article.push_time[<]": time.Now().Format("2006-01-02 15:04"), "article.state": 0}
		if sn != "" {
			ctg := that.Db.Get("ctg", "id", Map{"sn": sn})
			if ctg != nil {
				where["ctg_article.ctg_id"] = ctg.GetCeilInt("id")
			}
		}

		startTime := that.Req.FormValue("start_time")   //ctgsn
		finishTime := that.Req.FormValue("finish_time") //ctgsn

		if lunbo != 0 {
			where["article.lunbo"] = lunbo
		}

		if len(startTime) > 5 {
			where["article.push_time[>=]"] = startTime
		}
		if len(finishTime) > 5 {
			where["article.push_time[<=]"] = finishTime
		}

		if keywords != "" {
			where["OR"] = Map{"article.title[~]": keywords, "article.description[~]": keywords, "article.author[~]": keywords, "article.sn[~]": keywords, "article.origin[~]": keywords, "article.url[~]": keywords}
		}

		if len(where) > 1 {
			where = Map{"AND": where}
		}

		if sort == "" {
			where["ORDER"] = Slice{"article.sort DESC", "article.push_time DESC"}
		}

		if sort == "time" {
			where["ORDER"] = "article.push_time DESC"
		}
		count := that.Db.Count("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, where)
		article := that.Db.Page(page, pageSize).PageSelect("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "ctg_article.sn,article.img,article.title,article.description,article.push_time,article.lunbo,article.author,article.origin,article.url", where)

		that.Display(0, Map{"count": count, "data": article})

	},
}
