package workers

import (
	"github.com/pingcap/dbaas/cost-metering-service/config"
	"github.com/pingcap/dbaas/cost-metering-service/db/entity"
	"github.com/pingcap/dbaas/cost-metering-service/log"
	"github.com/pingcap/dbaas/cost-metering-service/model/billing"
	"github.com/pingcap/dbaas/cost-metering-service/model/costcenter"
	"github.com/pingcap/dbaas/cost-metering-service/utils/timeutils"
	"go.uber.org/zap"
	"time"
)

var CalculateWorker = CalculateWorkerFunc

func CalculateWorkerFunc() {

	//if !config.Get().GetBool(config.EnableInvoiceWorker) {
	//	return
	//}
	costCenterModel := &costcenter.CostCenterModel{}
	costCenterList, err := costCenterModel.GetAllCostCenters()
	if err != nil {
		log.Error("failed to get costCenterList in worker.", zap.Error(err))
		return
	}
	for _, costCenter := range costCenterList {
		switch costCenter.Status {
		case entity.CostCenterStatus_NOT_STARTED, entity.CostCenterStatus_STARTED:
			continue
		case entity.CostCenterStatus_DONE:
			CalculateCost(costCenter.CostCenterOrgID)
		}
	}
	return
}
func CalculateCost(costCenterOrgID uint) {
	now := timeutils.GetNow()
	CalculateHours := "48" // config.Get().GetInt()
	CalculateDate := timeutils.GetDayDate(now.Add(-time.Hour * config.Get().GetDuration(CalculateHours)))
	err := (&billing.CalculateModel{}).CalculateCost(costCenterOrgID, CalculateDate)
	if err != nil {
		log.Error("failed to  CalculateCost in worker.", zap.Error(err), zap.Uint("cosCenterOrgID", costCenterOrgID), zap.Time("CalculateDate", CalculateDate))
	}
}
