package main

import (
	"../cross"
	"../log"
	"../mod"
	"../nt"
	pb "../protos"
	"../utils"
	"go.uber.org/zap"
)

/// 救济金逻辑

const (
	DEF_ALMS_LIMIT = 10 // 默认低于多少钱可领取救济金
)

// 获取救济金配置
// 根据 vip 等级，返回 单次可领取金额和单日可领取次数
func __get_user_alms(vip int) (int64, int64) {
	if vip < 1 || vip > len(nt.DynConf.Vip) {
		log.Error("vip", zap.Int("vip", vip))
		return 0, 0
	}
	return nt.DynConf.Vip[vip-1].AlmsAmount * 100, int64(nt.DynConf.Vip[vip-1].AlmsTimesDaily)
}

// 根据玩家总金额(余额 + 银行) 得到可领取的救济金数额
// @return: amount, remain_times, ErrCode
// EXPLAIN: ErrCode 指示 amount 的有效性， remain_times 独立可用
func alms_status(guid uint64) (int64, int64, pb.ErrCode) {
	lvl, err := get_user_vip(guid)
	if err != nil {
		log.Error("alms_status", zap.Uint64("guid", guid), zap.Error(err))
		return 0, 0, pb.ErrCode_UNKNOWN
	}
	// 领取次数限制
	amount, total := __get_user_alms(int(lvl))
	cur, err := mod.GetUserAlms(guid)
	if nil != err {
		log.Error("alms_status", zap.Uint64("guid", guid), zap.Error(err))
		return 0, 0, pb.ErrCode_FAILED
	}
	if cur >= total {
		log.Debug("alms_status", zap.Uint64("guid", guid), zap.Int64("cur", cur), zap.Int64("total", total))
		return 0, 0, pb.ErrCode_EXHANSTED
	}
	remain_times := total - cur

	// 当前总金额
	arr, err := mod.GetUserAttrs(guid, "balance", "bank")
	if err != nil {
		log.Error("alms_status", zap.Uint64("guid", guid), zap.Error(err))
		return 0, remain_times, pb.ErrCode_FAILED
	}
	balance := utils.If_to_int64(arr[0], 0)
	bank := utils.If_to_int64(arr[1], 0)

	// 领取总余额限制
	var limit int64 = 0 // 领取金额限制
	ilimit, ok := nt.DynConf.Kv["alms_limit"]
	if ok {
		limit = utils.If_to_int64(ilimit, 0)
		if limit < 0 {
			limit = 0
		}
	}
	if balance+bank > limit {
		log.Debug("alms_status", zap.Uint64("guid", guid), zap.Int64("balance", balance), zap.Int64("bank", bank), zap.Int64("limit", limit))
		return 0, remain_times, pb.ErrCode_INSUFFICIENT
	}

	return amount, remain_times, pb.ErrCode_OK
}

// 领取救济金
// total: 总金额
// 返回领取后余额，领取金额，错误码
func alms_get(guid uint64) (int64, int64, pb.ErrCode) {
	amount, _, ec := alms_status(guid)
	if ec != pb.ErrCode_OK {
		return 0, 0, ec
	}
	// 绑定可领
	if !cross.IsBindUser(guid) {
		log.Warn("alms_get", zap.Uint64("guid", guid))
		return 0, 0, pb.ErrCode_UNBIND
	}
	// 增加领取限制
	err := mod.UpdateUserAlms(guid)
	if nil != err {
		log.Error("alms_get", zap.Uint64("guid", guid), zap.Error(err))
		return 0, 0, pb.ErrCode_FAILED
	}
	// 实际领取
	newBalance, err := mod.AddUserBalance(guid, amount)
	if nil != err {
		log.Error("alms_get", zap.Uint64("guid", guid), zap.Error(err))
		return 0, 0, pb.ErrCode_FAILED
	}
	return newBalance, amount, pb.ErrCode_OK
}
