package model

import (
	"sync/atomic"
	"time"

	"github.com/globalsign/mgo/bson"
	"mongo.games.com/goserver/core/logger"
)

var (
	WelfareLogDBName   = "log"
	WelfareLogCollName = "log_welfare"
)

const (
	WelfareBuyBlindBox = 0 // 购买盲盒
	WelfareBuyFirstPay = 1 // 购买首充
)

var COINEX_WelfLOBAL_SEQ = int64(0)

type WelfareItem struct {
	Type   int32  //类型 1:金币 2:钻石 3：道具
	ItemId int32  //道具id
	Num    int64  //数量
	Name   string //名称
}

type WelfareLog struct {
	LogId        bson.ObjectId  `bson:"_id"`
	SnId         int32          //玩家id
	Platform     string         //平台名称
	Channel      string         //渠道名称
	Promoter     string         //推广员
	PackageTag   string         //推广包标识
	Count        int64          //帐变数量
	TakeCount    int64          //消耗数量
	RestCount    int64          //钱包余额
	DiamondCount int64          //钻石余额
	Oper         string         //操作者
	Remark       string         //备注
	Time         time.Time      //时间戳
	Day          int32          //第几天领取
	Ver          int32          //数据版本(暂时不用)
	WType        int32          //福利类型
	LogType      int32          //log类型
	Item         []*WelfareItem //道具
	Discount     int64          //折扣（万分比）
	SeqNo        int64          //流水号(隶属于进程)
	Ts           int64          //时间戳
}

func NewWelfareLog() *WelfareLog {
	log := &WelfareLog{LogId: bson.NewObjectId()}
	return log
}

func NewWelfareLogEx(snid int32, count, takeCount, restCount, diamondCount, discount int64, day, ver, logType, wtype int32, itemd []*WelfareItem, oper, remark,
	platform, channel, promoter, packageid string) *WelfareLog {
	cl := NewWelfareLog()
	cl.SnId = snid
	cl.Platform = platform
	cl.Channel = channel
	cl.Promoter = promoter
	cl.Count = count
	cl.TakeCount = takeCount
	cl.RestCount = restCount
	cl.Day = day
	cl.DiamondCount = diamondCount
	cl.Discount = discount
	cl.Oper = oper
	cl.Remark = remark
	tNow := time.Now()
	cl.Time = tNow
	cl.Ver = ver
	cl.WType = wtype
	cl.LogType = logType
	cl.Item = itemd
	cl.PackageTag = packageid
	cl.SeqNo = atomic.AddInt64(&COINEX_WelfLOBAL_SEQ, 1)
	cl.Ts = tNow.Unix()
	return cl
}

func InsertWelfareLog(log *WelfareLog) (err error) {
	if rpcCli == nil {
		logger.Logger.Error("model.InsertWelfareLog rpcCli == nil")
		return
	}

	var ret bool
	err = rpcCli.CallWithTimeout("WelfareLogSvc.InsertWelfareLog", log, &ret, time.Second*30)
	if err != nil {
		logger.Logger.Warn("InsertWelfareLog error:", err)
	}
	return
}

type RemoveWelfareLogOneArg struct {
	Plt string
	Id  bson.ObjectId
}

func RemoveWelfareLogOne(plt string, id bson.ObjectId) error {
	if rpcCli == nil {
		logger.Logger.Error("model.RemoveWelfareLogOne rpcCli == nil")
		return nil
	}

	args := &RemoveCoinLogOneArg{
		Plt: plt,
		Id:  id,
	}
	var ret bool
	err := rpcCli.CallWithTimeout("WelfareLogSvc.RemoveWelfareLogOne", args, &ret, time.Second*30)
	if err != nil {
		logger.Logger.Warn("RemoveWelfareLogOne error:", err)
	}
	return err
}
