package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"path/filepath"
	"strconv"

	"redisdog/model"
)

type LogSysLogListRetData struct {
	Count int64
	List  []*model.SysLogRow
}

type LogSysLogListRet struct {
	Errno int                  `json:"errno"`
	Error string               `json:"error"`
	Data  LogSysLogListRetData `json:"data"`
}

func log_syslog(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "log", "syslog.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("syslog.tmpl").Funcs(TmplFuncMap).ParseFiles(files...)
	if err != nil {
		io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error()))
	} else {
		tmpl.Execute(resp, struct {
			Sess  *Session
			Req   *http.Request
			Title string
		}{
			sess,
			req,
			"系统错误日志",
		})
	}
}

func log_syslog_list(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	size, page, desc := 50, 1, true
	if sizeStr := req.Form.Get("size"); sizeStr != "" {
		if size, _ = strconv.Atoi(sizeStr); size <= 1 {
			size = 50
		}
	}
	if pageStr := req.Form.Get("page"); pageStr != "" {
		if page, _ = strconv.Atoi(pageStr); page < 1 {
			page = 1
		}
	}
	if orderStr := req.Form.Get("order"); orderStr != "" {
		if orderStr == "ASC" {
			desc = false
		}
	}
	mdl := model.NewSysLog(Db)
	cnt, err := mdl.Count()
	if err != nil {
		resp.Write(ERROR_RET(1, fmt.Sprintf("查询失败:%s", err.Error())))
	} else {
		logs, err := mdl.GetList(int64(size*(page-1)), int64(size), desc)
		if err != nil {
			resp.Write(ERROR_RET(1, fmt.Sprintf("查询失败:%s", err.Error())))
		} else {
			ret, _ := json.Marshal(LogSysLogListRet{Errno: 0, Error: "", Data: LogSysLogListRetData{Count: cnt, List: logs}})
			resp.Write(ret)
		}
	}
}
