package twong

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/wenstudio/gofly/config"
	"github.com/wenstudio/gofly/models"
	"github.com/wenstudio/gofly/tools"
	"github.com/wenstudio/gofly/user"
)

/**
美天旺的 iuser 实现
同时可能支持所有基于 crmeb 的应用
*/

const twong_confile = config.Dir + "twong.json"

var (
	Db *gorm.DB
)

func init() {
	mysql := config.CreateMysql(twong_confile)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database)
	var err error
	Db, err = gorm.Open("mysql", dsn)
	if err != nil {
		panic("美天旺数据库连接失败!")
	}
	Db.SingularTable(true)
	Db.LogMode(false)
	//DB.SetLogger(tools.Logger())
	Db.DB().SetMaxIdleConns(3)
	Db.DB().SetMaxOpenConns(30)
}

type TwUser struct {
	Uid      uint64
	Nickname string
	Avatar   string
}

type Twong struct{}

func NewTwongUser() user.IUser {
	return &Twong{}
}

func (self *Twong) GetVisitorInfo(key interface{}) (*models.Visitor, error) {
	uid, ok := key.(uint64)
	if !ok {
		return nil, errors.New("参数错误")
	}
	var u TwUser
	Db.Where("uid=?", uid).First(&u)
	if u.Uid != uid {
		return nil, errors.New("用户不存在")
	}

	return &models.Visitor{
		Name:      u.Nickname,
		Avator:    u.Avatar,
		VisitorId: self.GenVisitorId(key),
	}, nil
}

func (self *Twong) GetKeFuInfo(key interface{}) (*models.User, error) {
	return nil, nil
}

func (self *Twong) GenVisitorId(key interface{}) string {
	// 用 md5 就行?
	uid, ok := key.(uint64)
	if !ok {
		panic("bad uid")
	}
	suid := fmt.Sprintf("%v", uid)
	return tools.Md5(suid)
}
