package steal_rule

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

	"github.com/duke-git/lancet/v2/pointer"
)

func (r *sStealRule) Stats(ctx context.Context, input *model.MerchantHiddenConfigStatsInput) (list []*model.MerchantHiddenConfigStatsOutput, total int, err error) {
	recordColumn := dao.V1MerchantHiddenRecord.Columns()

	m := dao.V1MerchantHiddenRecord.Ctx(ctx).DB(config.GetDatabaseV1())
	if !pointer.IsNil(input) && input.DateRange != nil && len(input.DateRange) == 2 {
		m = m.WhereBetween(recordColumn.CreatedAt, input.DateRange[0].StartOfDay(), input.DateRange[1].EndOfDay())
	}

	combineRecordTable := func(column string) string {
		return utils.OrmTable(dao.V1MerchantHiddenRecord.Table(), column)
	}

	combineOrderTable := func(column string) string {
		return utils.OrmTable(dao.V1OrderInfo.Table(), column)
	}

	err = m.Fields(combineOrderTable(dao.V1OrderInfo.Columns().MerchantUid)).
		FieldSum(combineRecordTable(recordColumn.ActualAmount), "total_amount").
		FieldCount(combineRecordTable(recordColumn.Id), "total_count").
		FieldSum(fmt.Sprintf("CASE WHEN %s = 1 THEN %s ELSE 0 END", combineRecordTable(recordColumn.Status), combineRecordTable(recordColumn.ActualAmount)), "actual_amount").
		FieldSum(fmt.Sprintf("CASE WHEN %s = 1 THEN 1 ELSE 0 END", combineRecordTable(recordColumn.Status)), "actual_count").
		Fields(utils.OrmAs(fmt.Sprintf("DATE(%s)", combineRecordTable(recordColumn.CreatedAt)), "date")).
		LeftJoinOnFields(dao.V1OrderInfo.Table(), recordColumn.SourceOrderNo, "=", dao.V1OrderInfo.Columns().BankOrderId).
		Group(
			fmt.Sprintf("DATE(%s)", combineRecordTable(recordColumn.CreatedAt)),
			combineOrderTable(dao.V1OrderInfo.Columns().MerchantUid),
		).
		Page(input.Current, input.PageSize).
		OrderDesc(fmt.Sprintf("DATE(%s)", combineRecordTable(recordColumn.CreatedAt))).
		ScanAndCount(&list, &total, false)
	return
}
