package db

import (
	"context"
	"time"
	"youngee_b_api/consts"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"

	"github.com/issue9/conv"

	"github.com/sirupsen/logrus"
)

// CreatePayRecord 新增
func CreatePayRecord(ctx context.Context, enterpriseId string, payment float64, balance float64, payType int64, projectId string) (*int64, error) {
	db := GetReadDB(ctx)
	payRecord := gorm_model.EnterprisePayRecord{
		EnterpriseID: enterpriseId,
		Payment:      payment,
		Balance:      balance,
		PayType:      payType,
		PayAt:        time.Now(),
		ProjectID:    projectId,
	}
	err := db.Create(&payRecord).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call CreatePayRecord error,err:%+v", err)
		return nil, err
	}

	return &payRecord.ID, nil
}

func GetRechargeRecord(ctx context.Context, enterpriseID string, confirmAt string, method int) (*http_model.RechargeRecordPreview, error) {
	db := GetReadDB(ctx)
	// 根据企业id过滤
	db = db.Debug().Model(gorm_model.YounggeeRechargeRecord{}).Where("enterprise_id = ? and status = 2", enterpriseID)
	if method == 2 {
		db = db.Debug().Model(gorm_model.YounggeeRechargeRecord{}).Where("invoice_status = 2")
	}
	if confirmAt != "" {
		db = db.Where("confirm_at like ?", confirmAt+"%")
	}
	var rechargeRecords []gorm_model.YounggeeRechargeRecord
	db = db.Order("confirm_at desc").Find(&rechargeRecords)
	RechargeRecordPreview := http_model.RechargeRecordPreview{}
	for _, rechargeRecord := range rechargeRecords {
		RechargeRecordData := new(http_model.RechargeRecordData)
		RechargeRecordData.RechargeId = rechargeRecord.RechargeID
		RechargeRecordData.RechargeAmount = conv.MustString(rechargeRecord.RechargeAmount)
		RechargeRecordData.RechargeAmountReal = conv.MustString(rechargeRecord.RechargeAmount)
		RechargeRecordData.TransferVoucher = conv.MustString(rechargeRecord.TransferVoucherUrl)
		RechargeRecordData.PayMethod = consts.GetRechargeMethod(rechargeRecord.RechargeMethod)
		RechargeRecordData.ConfirmAt = conv.MustString(rechargeRecord.ConfirmAt)[0:19]
		RechargeRecordPreview.RechargeRecordData = append(RechargeRecordPreview.RechargeRecordData, RechargeRecordData)
	}
	return &RechargeRecordPreview, nil
}
