/**
* @Author: zou.yingbin
* @Create  : 2021/1/13 14:07
* @Modify  : 2021/1/13 14:07
 */

package mtpcache

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

var vUsrMgr userAccountMgr

// 用户缓存
type userAccountMgr struct {
	mtx  sync.RWMutex         //锁
	data map[int64]usrAccData //数据[userId]accountName
	last time.Time
}

type usrAccData struct {
	USERID       int64  `json:"userid"  xorm:"'USERID'"`             // 用户ID
	USERTYPE     int32  `json:"usertype"  xorm:"'USERTYPE'"`         // 账户类型 -  1:交易所 2:机构 3:会员子机构 4:经纪人 5:投资者 6:客户
	ACCOUNTNAME  string `json:"accountname"  xorm:"'ACCOUNTNAME'"`   // 账户名称(机构名称)
	PARENTUSERID int64  `json:"parentuserid"  xorm:"'PARENTUSERID'"` // 所属机构ID
	MEMBERUSERID int64  `json:"memberuserid"  xorm:"'MEMBERUSERID'"` // 所属会员ID
	ROOTUSERID   int64  `json:"rootuserid"  xorm:"'ROOTUSERID'"`     // 根用户ID
	NICKNAME     string `json:"nickname"  xorm:"'NICKNAME'"`         // 昵称
}

func init() {
	go func() {
		time.Sleep(time.Second * 3)
		vUsrMgr.load(0)
	}()
}

// 加载数据, userId=0时， 加载所有记录
func (r *userAccountMgr) load(userId int64) {
	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 t.USERID," +
		"       t.USERTYPE," +
		"       t.ACCOUNTNAME," +
		"       t.PARENTUSERID," +
		"       t.MEMBERUSERID," +
		"       t.ROOTUSERID," +
		"       u.nickname" +
		"  from useraccount t" +
		"  left join userinfo u" +
		"    on t.userid = u.userid" +
		" where 1 = 1"
	if userId > 0 {
		sqlId += fmt.Sprintf(" and t.userid = %v", userId)
	}
	sData := make([]usrAccData, 0)
	s := e.SQL(sqlId)
	if err := s.Find(&sData); err != nil {
		logger.GetLogger().Errorf("cache load useraccount, %v", err)
	} else {
		if userId == 0 || r.data == nil {
			r.data = make(map[int64]usrAccData)
		}
		for i := range sData {
			r.data[sData[i].USERID] = sData[i]
		}
		r.last = time.Now()
	}
}

func (r *userAccountMgr) get(userId int64) string {
	r.mtx.RLock()
	defer r.mtx.RUnlock()

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

	now := time.Now()
	// 用户名可能会修改, 间隔5分钟失效, 返回空, 需要重新加载
	if d := now.Sub(r.last); d.Seconds() > 300 {
		return ""
	}

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

// getEx 返回 accountname, nickname
func (r *userAccountMgr) getEx(userId int64) (string, string) {
	r.mtx.RLock()
	defer r.mtx.RUnlock()

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

	now := time.Now()
	// 用户名可能会修改, 间隔5分钟失效, 返回空, 需要重新加载
	if d := now.Sub(r.last); d.Seconds() > 300 {
		return "", ""
	}

	if v, ok := r.data[userId]; ok {
		return v.ACCOUNTNAME, v.NICKNAME
	}
	return "", ""
}

func (r *userAccountMgr) getData(userId int64) (usrAccData, bool) {
	r.mtx.RLock()
	defer r.mtx.RUnlock()
	if r.data == nil {
		return usrAccData{}, false
	}
	v, ok := r.data[userId]
	return v, ok
}

// GetUserNameByUserId 根据UserId获取名称
func GetUserNameByUserId(userId int64) string {
	if userId == 0 {
		return ""
	}
	if v := vUsrMgr.get(userId); v != "" {
		return v
	} else {
		vUsrMgr.load(userId)
	}

	return vUsrMgr.get(userId)
}

// GetUserNameAndNickName 获取名称和昵称
func GetUserNameAndNickName(userId int64) (string, string) {
	if userId == 0 {
		return "", ""
	}
	if userName, nickName := vUsrMgr.getEx(userId); userName != "" {
		return userName, nickName
	} else {
		vUsrMgr.load(userId)
	}

	return vUsrMgr.getEx(userId)
}

// GetAreaUserId 获取所属机构id
func GetAreaUserId(userId int64, userType int32) (areaUserId int64) {
	if userId == 0 {
		return userId
	}
	if userType == 2 {
		areaUserId = userId
	} else {
		if v, ok := vUsrMgr.getData(userId); ok {
			if v.USERTYPE == 2 {
				areaUserId = v.USERID
			} else {
				areaUserId = v.ROOTUSERID
			}
			return
		} else {
			vUsrMgr.load(userId)
		}
		if v, ok := vUsrMgr.getData(userId); ok {
			if v.USERTYPE == 2 {
				areaUserId = v.USERID
			} else {
				areaUserId = v.ROOTUSERID
			}
		}
	}
	return
}

// IsAreaUserId 是否是机构id
func IsAreaUserId(userId int64) bool {
	areaUserId := GetAreaUserId(userId, 0)
	return areaUserId == userId
}
