package Nrestful

import (
	mysql "proxy/Nmysql"
	rds "proxy/Nredis"
	"proxy/config"
)

func handleOcsDeleteSubsRsp(req *RestRsp) {
}

func handleOcsUpdateSubsReq(req *RestRsp) {
	expNtfFlag := false
	var expiredDate int64= 0
	if req.UpdateSubsReq.OptFlag & 0x04 == 0x04 {
		expNtfFlag = true
		expiredDate = int64(req.UpdateSubsReq.ExpDateU32)
	}

	accountId := req.UpdateSubsReq.AccountIdU32
	if expNtfFlag {
		planId := req.UpdateSubsReq.PackageIdU32
		_ = mysql.InsertExpiredNotifySms(accountId, planId, expiredDate)
	} else {
		status := req.UpdateSubsReq.StatusU8
		_ = mysql.UpdateUserStatus2Mdb(accountId, status)
	}
}

func handleUpdatePlanUsage(req *RestRsp) {
	opFlag := false
	thisTimeAdded := req.UpdateBundleUsageReq.PlanValueAddThisTime
	if thisTimeAdded & 0x8000000000000000 == 0x8000000000000000 {
		opFlag = true
	}
	thisTimeAdded &= 0x7FFFFFFFFFFFFFFF

	totalValue := req.UpdateBundleUsageReq.PlanValue
	if totalValue <= 0 {
		return
	}

	usedValue := req.UpdateBundleUsageReq.PlanUsedValue
	serviceType := req.UpdateBundleUsageReq.ServiceType
	rateUsed, oldRateUsed := 0, 0
	sendNotifyFlag := false
	if bSendNotifySms(serviceType) {//(service_type == 2)//data only; 1: voice; 2: data; 3: sms;
		rateUsed = int(usedValue*100 / totalValue)
		if rateUsed > 75 {
			oldRateUsed = int((usedValue-thisTimeAdded)*100 / totalValue)
			if oldRateUsed <= 75 {
				sendNotifyFlag = true
				rateUsed = 75
			}
		}
	}

	updateExpiryDate := false
	if usedValue >= totalValue {
		usedValue = totalValue
		rateUsed = 100
		updateExpiryDate = true
		if false {
			sendNotifyFlag = true
		}
	}

	bundleId := req.UpdateBundleUsageReq.BundleId
	if serviceType == 2 {
		mysql.UpdateDataPlanInfo(bundleId, thisTimeAdded, opFlag)
	} else {
		mysql.UpdateVoiceAndSmsPlanInfo(serviceType, bundleId, usedValue, totalValue, updateExpiryDate)
	}

	if sendNotifyFlag {
		planId := req.UpdateBundleUsageReq.PlanId
		if !rds.CheckIfBundleLimitSent(planId, rateUsed) {
			accountId := req.UpdateBundleUsageReq.AccountId
			mysql.AddNotificationSms(accountId, planId, serviceType, updateExpiryDate, rateUsed)
			rds.SetPlanExpire(planId, rateUsed)
		}
	}
}

func bSendNotifySms(serviceType byte) bool {
	ntfCfg := &config.Config.BundleUsageNotify
	switch serviceType {
	case 1:
		if ntfCfg.Voice75Percent {
			return true
		}
	case 2:
		if ntfCfg.Data75Percent {
			return true
		}
	case 3:
		if ntfCfg.Sms75Percent {
			return true
		}
	default:
	}
	return true
}

