// 实时数据
package controllers

import (
	"box-gm/models"
	"fmt"

	"github.com/astaxie/beego"
)

type BanIPController struct {
	beego.Controller
}

func (c *BanIPController) Get() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}
	c.Data["username"] = userinfo.(*LoginInfo).Username
	c.Data["token"] = models.GetToken()
	userPermission := models.GetPermission(userinfo.(*LoginInfo).Username)
	if (userPermission & (1 << uint(models.ModelSystem))) == 0 {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	c.Data["ipList"] = models.GetBanIPInfo()
	c.TplName = "banip.tpl"
}

func (c *BanIPController) Post() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}
	ip := c.GetString("ip")
	if ip == "" {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "请输入正确IP地址"}
		c.ServeJSON()
		return
	}

	u := new(models.BanIPInfo)
	u.IP = ip
	err := models.AddBanIPInfo(u)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "新增IP封禁"}
	c.ServeJSON()
}

func (c *BanIPController) Delete() {
	userinfo := c.GetSession("user")
	if userinfo == nil {
		c.Ctx.Redirect(302, "/accountlogin")
		return
	}

	ip := c.GetString("ip")
	err := models.DelBanIPInfoByIP(ip)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &map[string]interface{}{"status": true, "info": fmt.Sprintf("IP[%s]解封", ip)}
	c.ServeJSON()
}
