package twong

import (
	"errors"
	"fmt"
	"git.wanbits.cc/sin/flytalk/config"
	"git.wanbits.cc/sin/flytalk/models"
	"git.wanbits.cc/sin/flytalk/tools"
	"git.wanbits.cc/sin/flytalk/user"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

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

var (
	db *gorm.DB
)

func InitDb() {
	dbc := config.C.Database
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		dbc.Username, dbc.Password, dbc.Server, dbc.Port, dbc.Db)
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("connect to twong database failed.")
	}
}

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)
}
