package game

import (
	"encoding/json"
	"server/db"
	"server/game/mod/item"
	"server/game/mod/msg"
	GoUtil "server/game_util"
	"server/pkg/github.com/name5566/leaf/log"
	"strings"
)

const (
	MAIL_SEND_TYPE_SERVER = 1
	MAIL_SEND_TYPE_USER   = 2
)

type MailMgr struct {
	*ServerMod
	list map[int]*ServerMail
}

type MailData struct {
	List map[int][]*msg.Msg
}

type ServerMail struct {
	Id             int
	Title          string
	Content        string
	TitleEn        string
	ContentEn      string
	TitlePtBr      string
	ContentPtBr    string
	TitleEsLatam   string
	ContentEsLatam string
	Items          []*item.Item
	Start_time     int64
	Register_time  int64
	End_time       int64
	Send_type      int
	Mail_type      int
	To_uids        []int
}

func (m *MailMgr) Init() {
	m.key = MAIL_MGR_KEY
	m.data = &MailData{
		List: make(map[int][]*msg.Msg),
	}
	m.list = make(map[int]*ServerMail)
	// 注册处理函数
	m.init()
	m.LoadMail(nil)
	m.RegisterHandler(msg.HANDLE_TYPE_MAIL_ADD, m.AddMail)
	m.RegisterHandler(msg.HANDLE_TYPE_MAIL_RELOAD, m.LoadMail)
}

func (m *MailMgr) AddMail(msg *msg.Msg) (interface{}, error) {
	ServerMail := msg.Extra.(*ServerMail)
	m.list[ServerMail.Id] = ServerMail
	return nil, nil
}

func (r *MailMgr) LoadMail(msg *msg.Msg) (interface{}, error) {
	// 从数据库加载邮件
	log.Debug("reload server mail")
	data := make([]*db.SqlServerMailStruct, 0)
	err := db.GetServerMailData(&data)
	if err != nil {
		log.Error("LoadMail error: %v", err)
		return nil, err
	}
	for _, v := range data {
		Uids := make([]int, 0)
		UidArr := strings.Split(v.To_uids, ",")
		for _, v := range UidArr {
			Uids = append(Uids, GoUtil.Int(v))
		}
		var items []interface{}
		json.Unmarshal([]byte(v.Items), &items)
		r.list[v.Id] = &ServerMail{
			Id:             v.Id,
			Title:          v.Title,
			Content:        v.Content,
			TitleEn:        v.TitleEn,
			ContentEn:      v.ContentEn,
			TitlePtBr:      v.TitlePtBr,
			ContentPtBr:    v.ContentPtBr,
			TitleEsLatam:   v.TitleEsLatam,
			ContentEsLatam: v.ContentEsLatam,
			Items:          item.ParseItem(items),
			Start_time:     v.Start_time,
			Register_time:  v.Register_time,
			End_time:       v.End_time,
			Mail_type:      v.Mail_type,
			Send_type:      v.Send_type,
			To_uids:        Uids,
		}
	}
	return nil, nil
}

func (r *MailMgr) Sync(Uid int, Register int64) []ServerMail {
	// 同步邮件
	Now := GoUtil.Now()
	list := make([]ServerMail, 0)
	for _, v := range r.list {
		if v.Start_time > 0 && v.Start_time > Now {
			continue
		}
		if v.End_time > 0 && v.End_time < Now {
			continue
		}
		if v.Register_time > 0 && v.Register_time < Register {
			continue
		}
		if v.Send_type == MAIL_SEND_TYPE_SERVER { //全服邮件
			list = append(list, *v)
		} else {
			if GoUtil.InArray(Uid, v.To_uids) {
				list = append(list, *v)
			}
		}
	}
	return list
}
