package Nmysql

import (
	l4g "proxy/logger"
)

func UpdateDataPlanInfo(bundleId uint32, thisTimeAdded uint64, opFlag bool) error {
	var sqlStr string
	if !opFlag {
		sqlStr = "UPDATE ratable_history SET `VALUE`= `VALUE`+?  WHERE ID=?;"
	} else {
		sqlStr = "UPDATE ratable_history SET `VALUE`= `VALUE`-?  WHERE ID=?;"
	}
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec(thisTimeAdded, bundleId)
	if err != nil {
		l4g.MysqlLog.Errorf("UpdateDataPlanInfo for bundle[%d], added[%d], op[%t] error: %v", bundleId, thisTimeAdded, opFlag, err)
		return err
	}

	l4g.MysqlLog.Debugf("UpdateDataPlanInfo for bundle[%d], added[%d], op[%t] succ!", bundleId, thisTimeAdded, opFlag)
	return nil
}

func UpdateVoiceAndSmsPlanInfo(serviceType byte, bundleId uint32, usedValue uint64, totalValue uint64, updateExpiryDate bool) error {
	var sqlStr string
	var value uint64
	if updateExpiryDate {
		sqlStr = "UPDATE ratable_history SET `VALUE`=? WHERE ID=?;"
		value = totalValue
	} else {
		sqlStr = "UPDATE ratable_history SET `VALUE`=? WHERE ID=?;"
		value = usedValue
	}
	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec(value, bundleId)
	if err != nil {
		l4g.MysqlLog.Errorf("UpdateVoiceAndSmsPlanInfo for bundle[%d], value[%d] error: %v", bundleId, value, err)
		return err
	}

	l4g.MysqlLog.Debugf("UpdateVoiceAndSmsPlanInfo for bundle[%d], value[%d] succ!", bundleId, value)
	return nil
}

func AddNotificationSms(accountId uint32, planId uint32, serviceType byte, updateExpiryDate bool, rateUsed int) error {
	var sqlStr string= "INSERT into tb_sync_msg SET msg_type=2, rate_type=?, acct_id=?, rate_value=?, state=1, ofr_inst_id=?;"
	rate := rateUsed
	//if updateExpiryDate {
	//	rate = 100
	//}

	stmt, _ := MySqlDb.Prepare(sqlStr)
	defer stmt.Close()

	_, err := stmt.Exec(serviceType, accountId, rate, planId)
	if err != nil {
		l4g.MysqlLog.Errorf("AddNotificationSms for plan[%d], acct[%d], type[%d], rate[%d/100] error: %v", planId, accountId, serviceType, rate, err)
		return err
	}

	l4g.MysqlLog.Debugf("AddNotificationSms for plan[%d], acct[%d], type[%d], rate[%d/100] succ!", planId, accountId, serviceType, rate)
	return nil
}
