package service

import (
	"encoding/json"
	"errors"
	"time"

	"tower_api/dao"
)

type NoticeService struct {
}

func NewNoticeService() *NotifyService {
	return &NotifyService{}
}

func (n *NotifyService) GetNewest(specialId int) *NoticeShow {
	show := NoticeShow{}
	//1 从缓存中读取
	cache := dao.GetSingleNoticeFromCache(specialId)
	if cache != "" {
		//有可能是空json,空数据也缓存，防止没有消息不停读库
		err := json.Unmarshal([]byte(cache), &show)
		if err == nil {
			return &show
		}
	}
	//2 没有则读库
	curUnix := time.Now().Unix()
	notice := dao.GetSingleNotice(curUnix, specialId)
	//3 读取到数据写缓存(无论是否获取到消息，都缓存起来，哪怕缓存空对象)
	show.Title = notice.Title
	show.Content = notice.Content
	showByte, err := json.Marshal(&show)
	if err == nil {
		dao.CacheSingleNotice(string(showByte), specialId)
	}
	return &show
}

// GetPlayerRealTcpId 获取用户真实的TCP_ID(跨服合服了)
func (n *NotifyService) GetPlayerRealTcpId(playerId int) (int, error) {
	// 找出玩家对应的区服信息
	tcpInfo := dao.FindTcpInfoByPlayerId(playerId)
	if tcpInfo.TcpId == 0 {
		return 0, errors.New("未获取到用户的TCP_ID")
	}
	if tcpInfo.CrossId > 0 {
		//获取跨服对应的tcp信息,若当前跨服设置了tcp信息，则使用跨服的tcp信息
		crossTcp := dao.GetTcpByCrossId(tcpInfo.CrossId)
		if crossTcp.TcpId > 0 {
			return crossTcp.TcpId, nil
		}
	}
	return tcpInfo.TcpId, nil
}

type NoticeShow struct {
	Title, Content string
}
