package sys_user_payment

import (
	"context"
	"fmt"
	"kami/internal/dao"
	"kami/internal/model"
	"kami/utility/config"
)

func (s *sSysUserPayment) DailySummary(ctx context.Context, input model.SysUserPaymentDailySummaryInput) (total int, record []*model.SysUserRecord, err error) {
	m := dao.V1SysUserPaymentRecords.Ctx(ctx).DB(config.GetDatabaseV1()).
		FieldSum(fmt.Sprintf("CASE WHEN %s = 'deposit' THEN %s ELSE 0 END", dao.V1SysUserPaymentRecords.Columns().TransactionType, dao.V1SysUserPaymentRecords.Columns().Amount), "total_deposit_amount").
		FieldSum(fmt.Sprintf("CASE WHEN %s = 'deduction_return' THEN %s ELSE 0 END", dao.V1SysUserPaymentRecords.Columns().TransactionType, dao.V1SysUserPaymentRecords.Columns().Amount), "total_return_amount").
		FieldSum(fmt.Sprintf("CASE WHEN %s = 'consumption' THEN %s ELSE 0 END", dao.V1SysUserPaymentRecords.Columns().TransactionType, dao.V1SysUserPaymentRecords.Columns().Amount), "total_consume_amount").
		FieldSum(fmt.Sprintf("CASE WHEN %s = 'Manual Adjustment' THEN %s ELSE 0 END", dao.V1SysUserPaymentRecords.Columns().TransactionType, dao.V1SysUserPaymentRecords.Columns().Amount), "total_manual_handle_amount").
		Fields(fmt.Sprintf("DATE(`%s`.`%s`) AS %s", dao.V1SysUserPaymentRecords.Table(), dao.V1SysUserPaymentRecords.Columns().CreatedAt, dao.V1SysUserPaymentRecords.Columns().CreatedAt)).
		Fields(dao.V1SysUser.Columns().Username).
		Group(
			fmt.Sprintf("DATE(`%s`.`%s`)", dao.V1SysUserPaymentRecords.Table(), dao.V1SysUserPaymentRecords.Columns().CreatedAt),
			dao.V1SysUserPaymentRecords.Columns().UserId,
		).LeftJoinOnFields(dao.V1SysUser.Table(), dao.V1SysUserPaymentRecords.Columns().UserId, "=", dao.V1SysUser.Columns().Id)

	if input.Username != "" {
		m = m.Where(fmt.Sprintf("`%s`.`%s`='%s'", dao.V1SysUser.Table(), dao.V1SysUser.Columns().Username, input.Username))
	}
	if input.Date != "" {
		m = m.Where(fmt.Sprintf("DATE(`%s`.`%s`)='%s'", dao.V1SysUserPaymentRecords.Table(), dao.V1SysUserPaymentRecords.Columns().CreatedAt, input.Date))
	}
	err = m.OrderDesc(dao.V1SysUserPaymentRecords.Columns().CreatedAt).
		Page(input.Current, input.PageSize).
		ScanAndCount(&record, &total, false)
	return
}
