package model

import (
	"context"
	"fmt"
	"ycc-server/common/globalkey"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ AgentClosureModel = (*customAgentClosureModel)(nil)

type (
	// AgentClosureModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAgentClosureModel.
	AgentClosureModel interface {
		agentClosureModel
		FindUnionPageListByPageWithTotal(ctx context.Context, agentId, subordinateId int64, page, pageSize int64) ([]*UnionDetail, int64, error)
	}

	customAgentClosureModel struct {
		*defaultAgentClosureModel
	}

	// UnionDetail 合并后的详情结构
	UnionDetail struct {
		Id         int64   `db:"id"`
		CreateTime string  `db:"create_time"`
		Amount     float64 `db:"amount"`
		Type       string  `db:"type"`
	}
)

// NewAgentClosureModel returns a model for the database table.
func NewAgentClosureModel(conn sqlx.SqlConn, c cache.CacheConf) AgentClosureModel {
	return &customAgentClosureModel{
		defaultAgentClosureModel: newAgentClosureModel(conn, c),
	}
}

// FindUnionPageListByPageWithTotal 获取合并后的分页列表
func (m *customAgentClosureModel) FindUnionPageListByPageWithTotal(ctx context.Context, agentId, subordinateId int64, page, pageSize int64) ([]*UnionDetail, int64, error) {
	// 构建UNION ALL查询
	deductionQuery := fmt.Sprintf(`
		SELECT id, create_time, amount, type 
		FROM agent_commission_deduction 
		WHERE agent_id = ? AND deducted_agent_id = ? AND del_state = ?
	`)

	rewardsQuery := fmt.Sprintf(`
		SELECT id, create_time, amount, type 
		FROM agent_rewards 
		WHERE agent_id = ? AND relation_agent_id = ? AND del_state = ?
	`)

	// 计算总记录数
	countQuery := fmt.Sprintf(`
		SELECT COUNT(*) FROM (
			%s
			UNION ALL
			%s
		) AS union_table
	`, deductionQuery, rewardsQuery)

	var total int64
	err := m.QueryRowNoCacheCtx(ctx, &total, countQuery, agentId, subordinateId, globalkey.DelStateNo, agentId, subordinateId, globalkey.DelStateNo)
	if err != nil {
		return nil, 0, errors.Wrapf(err, "查询总记录数失败")
	}

	// 构建分页查询
	if page < 1 {
		page = 1
	}
	offset := (page - 1) * pageSize

	unionQuery := fmt.Sprintf(`
		SELECT * FROM (
			%s
			UNION ALL
			%s
		) AS union_table
		ORDER BY create_time DESC
		LIMIT ? OFFSET ?
	`, deductionQuery, rewardsQuery)

	var resp []*UnionDetail
	err = m.QueryRowsNoCacheCtx(ctx, &resp, unionQuery,
		agentId, subordinateId, globalkey.DelStateNo,
		agentId, subordinateId, globalkey.DelStateNo,
		pageSize, offset)
	if err != nil {
		return nil, 0, errors.Wrapf(err, "查询分页数据失败")
	}

	return resp, total, nil
}
