package app

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

var MailCtr = Ctr{
	"add": func(that *Context) {
		title := that.Req.FormValue("title")
		name := that.Req.FormValue("name")
		phone := that.Req.FormValue("phone")
		content := that.Req.FormValue("content")

		tp := ObjToInt(that.Req.FormValue("type"))
		show := ObjToInt(that.Req.FormValue("show"))

		if len(title) < 5 {
			that.Display(3, "标题过短")
			return
		}
		if len(name) < 2 {
			that.Display(3, "姓名错误")
			return
		}
		if len(phone) < 8 {
			that.Display(3, "联系方式错误")
			return
		}
		if len(content) < 10 {
			that.Display(3, "内容过短")
			return
		}

		data := Map{
			"sn":   Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
			"name": name, "title": title, "phone": phone, "content": content, "type": tp, "show": show,
			"modify_time[#]": "NOW()", "create_time[#]": "NOW()",
		}
		id := that.Db.Insert("mail", data)
		if id == 0 {
			that.Display(4, "创建失败")
			return
		}

		that.Display(0, "成功")
		return

	},
	"info": func(that *Context) {
		sn := that.Req.FormValue("sn")

		mail := that.Db.Get("mail", "*", Map{"sn": sn})

		that.Display(0, mail)
	},
	"list": func(that *Context) {
		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")

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

		where := Map{"state": 0, "show": 1}

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

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

		//if sort==""{
		//	where["ORDER"]=Slice{"sort DESC","push_time DESC"}
		//}
		//
		//if sort=="time"{
		where["ORDER"] = "create_time DESC"
		//}
		count := that.Db.Count("mail", where)
		mail := that.Db.Page(page, pageSize).PageSelect("mail", "*", where)

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

	},
}
