package adminfinance

import (
	"context"

	"hfb_sys/backend/internal/timeutil"
)

func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*DashboardDTO, error) {
	dailyItems, err := r.dailyItems(ctx, query)
	if err != nil {
		return nil, err
	}
	summary, err := r.summary(ctx, query)
	if err != nil {
		return nil, err
	}
	pickup, err := r.pickupSummary(ctx, query)
	if err != nil {
		return nil, err
	}
	return &DashboardDTO{
		Summary:       *summary,
		DailyItems:    dailyItems,
		PickupSummary: *pickup,
		GeneratedAt:   timeutil.ShanghaiNow(),
	}, nil
}

// pickupSummary 线下提号统计，独立查询 admin_pickups 表，不混入正常订单口径。
func (r *Repository) pickupSummary(ctx context.Context, query DashboardQuery) (*PickupSummaryDTO, error) {
	db := r.db.WithContext(ctx)
	var row struct {
		SettledAmountCent int64
		ProfitAmountCent  int64
		CompletedCount    int64
	}
	if err := db.Table("admin_pickups").
		Select(`COALESCE(SUM(settle_amount_cent), 0) AS settled_amount_cent, COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent, COUNT(id) AS completed_count`).
		Where("status = ?", "completed").
		Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
		Scan(&row).Error; err != nil {
		return nil, err
	}
	var inProgress int64
	if err := db.Table("admin_pickups").Where("status = ?", "picking_up").Count(&inProgress).Error; err != nil {
		return nil, err
	}
	return &PickupSummaryDTO{
		SettledAmountCent: row.SettledAmountCent,
		ProfitAmountCent:  row.ProfitAmountCent,
		CompletedCount:    row.CompletedCount,
		InProgressCount:   inProgress,
	}, nil
}

func (r *Repository) summary(ctx context.Context, query DashboardQuery) (*FinanceSummaryDTO, error) {
	db := r.db.WithContext(ctx)
	var payment paymentSummaryRow
	if err := db.Table("payment_orders AS po").
		Select(`COALESCE(SUM(CASE WHEN po.biz_type IN ('order_pay') AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ('order_pay') AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS full_refund_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent <  COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS partial_refund_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count`,
			refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes()).
		Joins(`LEFT JOIN (
			SELECT order_id, MAX(amount_cent) AS amount_cent
			FROM payment_orders
			WHERE biz_type = 'order_pay' AND status = 'paid'
			GROUP BY order_id
		) AS orig ON orig.order_id = po.order_id`).
		Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate).
		Scan(&payment).Error; err != nil {
		return nil, err
	}

	var settlement settlementSummaryRow
	if err := db.Table("rental_orders AS ro").
		Select(`COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
				COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
				COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
				COUNT(ro.id) AS settled_order_count`).
		Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
		Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(db)).
		Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
		Scan(&settlement).Error; err != nil {
		return nil, err
	}

	var exceptionCount int64
	if err := db.Table("(?) AS d", r.financeDetailBaseQuery(ctx, DetailQuery{
		DateType:  "settled",
		StartDate: query.StartDate,
		EndDate:   query.EndDate,
	})).
		Where("finance_status <> ?", "normal").
		Count(&exceptionCount).Error; err != nil {
		return nil, err
	}

	// 预计收入:尚未结算订单的下单预估平台手续费之和,按下单时间落在查询区间内统计。
	var estimated estimatedIncomeRow
	if err := db.Table("rental_orders").
		Select(`COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
			COUNT(id) AS pending_settle_order_count`).
		Where("settlement_status NOT IN ?", settledSettlementStatuses()).
		Where("status NOT IN ?", nonBillableOrderStatuses()).
		Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
		Scan(&estimated).Error; err != nil {
		return nil, err
	}

	return &FinanceSummaryDTO{
		TotalFlowAmountCent:         payment.TotalFlowAmountCent,
		TotalRefundAmountCent:       payment.TotalRefundAmountCent,
		PendingRefundAmountCent:     payment.PendingRefundAmountCent,
		ChannelNetAmountCent:        payment.TotalFlowAmountCent - payment.TotalRefundAmountCent,
		PlatformIncomeAmountCent:    settlement.PlatformIncomeAmountCent,
		OwnerShouldIncomeAmountCent: settlement.OwnerShouldIncomeAmountCent,
		OwnerWalletIncomeAmountCent: settlement.OwnerWalletIncomeAmountCent,
		SettlementDiffAmountCent:    settlement.OwnerShouldIncomeAmountCent - settlement.OwnerWalletIncomeAmountCent,
		EstimatedIncomeAmountCent:   estimated.EstimatedIncomeAmountCent,
		SuccessfulPayCount:          payment.SuccessfulPayCount,
		SuccessfulRefundCount:       payment.FullRefundCount + payment.PartialRefundCount,
		FullRefundCount:             payment.FullRefundCount,
		PartialRefundCount:          payment.PartialRefundCount,
		PendingRefundCount:          payment.PendingRefundCount,
		SettledOrderCount:           settlement.SettledOrderCount,
		PendingSettleOrderCount:     estimated.PendingSettleOrderCount,
		FinancialExceptionCount:     exceptionCount,
	}, nil
}

func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]FinanceDailyDTO, error) {
	db := r.db.WithContext(ctx)
	payments := make([]dailyPaymentRow, 0)
	if err := db.Table("payment_orders AS po").
		Select(`DATE(po.created_at) AS date,
			COALESCE(SUM(CASE WHEN po.biz_type IN ('order_pay') AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
			COALESCE(SUM(CASE WHEN po.biz_type IN ('order_pay') AND po.status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent >= COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS full_refund_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' AND po.amount_cent <  COALESCE(orig.amount_cent, 0) THEN 1 ELSE 0 END), 0) AS partial_refund_count,
			COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count`,
			refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes()).
		Joins(`LEFT JOIN (
			SELECT order_id, MAX(amount_cent) AS amount_cent
			FROM payment_orders
			WHERE biz_type = 'order_pay' AND status = 'paid'
			GROUP BY order_id
		) AS orig ON orig.order_id = po.order_id`).
		Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate).
		Group("DATE(po.created_at)").
		Scan(&payments).Error; err != nil {
		return nil, err
	}

	settlements := make([]dailySettlementRow, 0)
	if err := db.Table("rental_orders AS ro").
		Select(`DATE(ro.settled_at) AS date,
				COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
				COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
				COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
				COUNT(ro.id) AS settled_order_count`).
		Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
		Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(db)).
		Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
		Group("DATE(ro.settled_at)").
		Scan(&settlements).Error; err != nil {
		return nil, err
	}

	// 每日预计收入:尚未结算订单的下单预估平台手续费,按下单日期归集,口径与 summary 一致。
	estimates := make([]dailyEstimatedRow, 0)
	if err := db.Table("rental_orders").
		Select(`DATE(created_at) AS date,
				COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent`).
		Where("settlement_status NOT IN ?", settledSettlementStatuses()).
		Where("status NOT IN ?", nonBillableOrderStatuses()).
		Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
		Group("DATE(created_at)").
		Scan(&estimates).Error; err != nil {
		return nil, err
	}

	itemsByDate := make(map[string]FinanceDailyDTO)
	for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
		date := day.Format("2006-01-02")
		itemsByDate[date] = FinanceDailyDTO{Date: date}
	}
	for _, row := range payments {
		date := dailyDateKey(row.Date)
		item := itemsByDate[date]
		item.Date = date
		item.TotalFlowAmountCent = row.TotalFlowAmountCent
		item.TotalRefundAmountCent = row.TotalRefundAmountCent
		item.PendingRefundAmountCent = row.PendingRefundAmountCent
		item.ChannelNetAmountCent = row.TotalFlowAmountCent - row.TotalRefundAmountCent
		item.SuccessfulPayCount = row.SuccessfulPayCount
		item.SuccessfulRefundCount = row.FullRefundCount + row.PartialRefundCount
		item.FullRefundCount = row.FullRefundCount
		item.PartialRefundCount = row.PartialRefundCount
		item.PendingRefundCount = row.PendingRefundCount
		itemsByDate[date] = item
	}
	for _, row := range settlements {
		date := dailyDateKey(row.Date)
		item := itemsByDate[date]
		item.Date = date
		item.PlatformIncomeAmountCent = row.PlatformIncomeAmountCent
		item.OwnerShouldIncomeAmountCent = row.OwnerShouldIncomeAmountCent
		item.OwnerWalletIncomeAmountCent = row.OwnerWalletIncomeAmountCent
		item.SettlementDiffAmountCent = row.OwnerShouldIncomeAmountCent - row.OwnerWalletIncomeAmountCent
		item.SettledOrderCount = row.SettledOrderCount
		itemsByDate[date] = item
	}
	for _, row := range estimates {
		date := dailyDateKey(row.Date)
		item := itemsByDate[date]
		item.Date = date
		item.EstimatedIncomeAmountCent = row.EstimatedIncomeAmountCent
		itemsByDate[date] = item
	}

	items := make([]FinanceDailyDTO, 0, len(itemsByDate))
	for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
		items = append(items, itemsByDate[day.Format("2006-01-02")])
	}
	return items, nil
}

type paymentSummaryRow struct {
	TotalFlowAmountCent     int64
	TotalRefundAmountCent   int64
	PendingRefundAmountCent int64
	SuccessfulPayCount      int64
	FullRefundCount         int64
	PartialRefundCount      int64
	PendingRefundCount      int64
}

type settlementSummaryRow struct {
	PlatformIncomeAmountCent    int64
	OwnerShouldIncomeAmountCent int64
	OwnerWalletIncomeAmountCent int64
	SettledOrderCount           int64
}

type estimatedIncomeRow struct {
	EstimatedIncomeAmountCent int64
	PendingSettleOrderCount   int64
}

type dailyPaymentRow struct {
	Date                    string
	TotalFlowAmountCent     int64
	TotalRefundAmountCent   int64
	PendingRefundAmountCent int64
	SuccessfulPayCount      int64
	FullRefundCount         int64
	PartialRefundCount      int64
	PendingRefundCount      int64
}

type dailySettlementRow struct {
	Date                        string
	PlatformIncomeAmountCent    int64
	OwnerShouldIncomeAmountCent int64
	OwnerWalletIncomeAmountCent int64
	SettledOrderCount           int64
}

type dailyEstimatedRow struct {
	Date                      string
	EstimatedIncomeAmountCent int64
}
