// 实时数据
package controllers

import (
	"encoding/json"
	"box-gm/utils"
	"io/ioutil"
	"log"

	"github.com/astaxie/beego"
)

type RealTimeController struct {
	beego.Controller
}

// 主界面
// 通过c.Data[key]返回数据
// ace模板文件通过{{.key}}获取数据
func (c *RealTimeController) Get() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	//界面模板文件
	c.TplName = "welcome.tpl"
}

// 同步数据
func (c *RealTimeController) Post() {
	body, err := ioutil.ReadAll(c.Ctx.Request.Body)
	if err != nil {
		log.Printf("realtime post err[%v]", err)
		c.Data["json"] = map[string]interface{}{
			"code": "1",
			"msg":  "数据为空",
		}
		c.ServeJSON()
		return
	}
	var report []*utils.RTLogStruct
	json.Unmarshal(body, &report)

	for _, v := range report {
		// log.Printf("realtime  [%v]", v)
		utils.WriteLog(v)
	}

	c.Data["json"] = map[string]interface{}{
		"code": "0",
		"msg":  "上报数据成功",
	}
	c.ServeJSON()
}
