/**
* @Author: zou.yingbin
* @Create  : 2021/1/13 10:51
* @Modify  : 2021/1/13 10:51
 */

package mtpcache

import (
	"mtp2_if/db"
	"mtp2_if/logger"
	"sync"
	"time"
)

var vUser userName

type userName struct {
	mtx  sync.RWMutex       // 锁
	data map[int64]userData // 数据[loginId]userData
	last time.Time
}

type userData struct {
	LOGINID   int64  `json:"LOGINID"  xorm:"'LOGINID'"`     // 登录ID
	LOGINCODE string `json:"LOGINCODE"  xorm:"'LOGINCODE'"` // 登录代码
	USERNAME  string `json:"USERNAME"  xorm:"'USERNAME'"`   // 用户名字
}

// 加载数据
func (r *userName) load() {
	now := time.Now()
	// 间隔3秒以上才重新加载
	if d := now.Sub(r.last); d.Seconds() < 3 {
		return
	}

	r.mtx.Lock()
	defer r.mtx.Unlock()
	e := db.GetEngine()
	if e == nil {
		return
	}

	sqlId := "select l.loginid, l.logincode, s.username" +
		"  from loginaccount l" +
		"  left join systemmanager s" +
		"    on l.logincode = s.logincode" +
		" where s.username is not null"

	sData := make([]userData, 0)
	s := e.SQL(sqlId)
	if err := s.Find(&sData); err != nil {
		logger.GetLogger().Errorf("cache load usrname, %v", err)
	} else {
		r.data = make(map[int64]userData)
		for i := range sData {
			r.data[sData[i].LOGINID] = sData[i]
		}
		r.last = time.Now()
	}
}

func (r *userName) name(loginId int64) string {
	r.mtx.RLock()
	defer r.mtx.RUnlock()

	if r.data == nil {
		return ""
	}

	if v, ok := r.data[loginId]; ok {
		return v.USERNAME
	}
	return ""
}

func (r *userName) loginCode(loginId int64) string {
	r.mtx.RLock()
	defer r.mtx.RUnlock()

	if r.data == nil {
		return ""
	}

	if v, ok := r.data[loginId]; ok {
		return v.LOGINCODE
	}
	return ""
}

// 根据登录ID获取名称
func GetUserNameByLoginId(loginId int64) string {
	if v := vUser.name(loginId); v != "" {
		return v
	} else {
		vUser.load()
	}

	return vUser.name(loginId)
}

// 根据登录ID获取登录代码
func GetLoginCodeByLoginId(loginId int64) string {
	if v := vUser.loginCode(loginId); v != "" {
		return v
	} else {
		vUser.load()
	}

	return vUser.loginCode(loginId)
}
