package controllers

import (
	"box-gm/models"
	"box-gm/utils"
	"fmt"
	"log"
	"time"

	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
)

type WelcomeController struct {
	beego.Controller
}

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

	c.Data["rolename"] = models.GetUserRoleName(username)
	c.Data["username"] = username
	c.Data["sharecode"] = models.GetUserShareCode(username)
	c.Data["token"] = models.GetToken()
	c.Data["sysTime"] = time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
	//界面模板文件
	c.TplName = "welcome.tpl"
}

func (c *WelcomeController) Post() {
	if !models.CheckToken(c.GetString("token")) {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "操作失败，请重新刷新界面"}
		c.ServeJSON()
		return
	}

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

	username := userinfo.(*LoginInfo).Username
	log.Printf("WelcomeController Post username[%s]", username)
	nUser := models.GetUserByUsername(username)
	if nUser == nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": fmt.Sprintf("用户[%s]已存在", username)}
		c.ServeJSON()
		return
	}

	sharecode := c.GetString("sharecode")
	log.Printf("WelcomeController Post sharecode[%s]", sharecode)
	// 校验邀请码
	pool := utils.GetAccountRedisPool()
	if pool == nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": "get redis pool fail"}
		c.ServeJSON()
		return
	}
	rd := pool.Get()
	defer rd.Close()
	result, _ := redis.Bool(rd.Do("sismember", "sharecode", sharecode))
	log.Printf("WelcomeController Post result[%v]", result)
	if result == true {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": fmt.Sprintf("邀请码[%s]已占有!", sharecode)}
		c.ServeJSON()
		return
	}

	nUser.ShareCode = sharecode
	_, err := models.UpdateUser(nUser)
	if err != nil {
		c.Data["json"] = &map[string]interface{}{"status": false, "info": err}
		c.ServeJSON()
		return
	}

	rd.Do("sadd", "sharecode", sharecode)
	rd.Do("sadd", "sharecode:promoter", sharecode)

	c.Data["json"] = &map[string]interface{}{"status": true, "info": "更新用户成功"}
	c.ServeJSON()

	go models.SaveLog(username, "修改账号推广码", &map[string]interface{}{"username": username, "ShareCode": nUser.ShareCode})
}
