// Code generated by go.ipao.vip/gen. DO NOT EDIT.
// Code generated by go.ipao.vip/gen. DO NOT EDIT.
// Code generated by go.ipao.vip/gen. DO NOT EDIT.

package models

import (
	"context"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"

	"go.ipao.vip/gen"
	"go.ipao.vip/gen/field"

	"gorm.io/plugin/dbresolver"
)

func newOrder(db *gorm.DB, opts ...gen.DOOption) orderQuery {
	_orderQuery := orderQuery{}

	_orderQuery.orderQueryDo.UseDB(db, opts...)
	_orderQuery.orderQueryDo.UseModel(&Order{})

	tableName := _orderQuery.orderQueryDo.TableName()
	_orderQuery.ALL = field.NewAsterisk(tableName)
	_orderQuery.ID = field.NewInt64(tableName, "id")
	_orderQuery.TenantID = field.NewInt64(tableName, "tenant_id")
	_orderQuery.UserID = field.NewInt64(tableName, "user_id")
	_orderQuery.Type = field.NewField(tableName, "type")
	_orderQuery.Status = field.NewField(tableName, "status")
	_orderQuery.Currency = field.NewField(tableName, "currency")
	_orderQuery.AmountOriginal = field.NewInt64(tableName, "amount_original")
	_orderQuery.AmountDiscount = field.NewInt64(tableName, "amount_discount")
	_orderQuery.AmountPaid = field.NewInt64(tableName, "amount_paid")
	_orderQuery.Snapshot = field.NewJSONB(tableName, "snapshot")
	_orderQuery.IdempotencyKey = field.NewString(tableName, "idempotency_key")
	_orderQuery.PaidAt = field.NewTime(tableName, "paid_at")
	_orderQuery.RefundedAt = field.NewTime(tableName, "refunded_at")
	_orderQuery.RefundForced = field.NewBool(tableName, "refund_forced")
	_orderQuery.RefundOperatorUserID = field.NewInt64(tableName, "refund_operator_user_id")
	_orderQuery.RefundReason = field.NewString(tableName, "refund_reason")
	_orderQuery.CreatedAt = field.NewTime(tableName, "created_at")
	_orderQuery.UpdatedAt = field.NewTime(tableName, "updated_at")
	_orderQuery.CouponID = field.NewInt64(tableName, "coupon_id")

	_orderQuery.fillFieldMap()

	return _orderQuery
}

type orderQuery struct {
	orderQueryDo orderQueryDo

	ALL                  field.Asterisk
	ID                   field.Int64
	TenantID             field.Int64
	UserID               field.Int64
	Type                 field.Field
	Status               field.Field
	Currency             field.Field
	AmountOriginal       field.Int64
	AmountDiscount       field.Int64
	AmountPaid           field.Int64
	Snapshot             field.JSONB
	IdempotencyKey       field.String
	PaidAt               field.Time
	RefundedAt           field.Time
	RefundForced         field.Bool
	RefundOperatorUserID field.Int64
	RefundReason         field.String
	CreatedAt            field.Time
	UpdatedAt            field.Time
	CouponID             field.Int64 // 使用的优惠券ID (0表示未使用)

	fieldMap map[string]field.Expr
}

func (o orderQuery) Table(newTableName string) *orderQuery {
	o.orderQueryDo.UseTable(newTableName)
	return o.updateTableName(newTableName)
}

func (o orderQuery) As(alias string) *orderQuery {
	o.orderQueryDo.DO = *(o.orderQueryDo.As(alias).(*gen.DO))
	return o.updateTableName(alias)
}

func (o *orderQuery) updateTableName(table string) *orderQuery {
	o.ALL = field.NewAsterisk(table)
	o.ID = field.NewInt64(table, "id")
	o.TenantID = field.NewInt64(table, "tenant_id")
	o.UserID = field.NewInt64(table, "user_id")
	o.Type = field.NewField(table, "type")
	o.Status = field.NewField(table, "status")
	o.Currency = field.NewField(table, "currency")
	o.AmountOriginal = field.NewInt64(table, "amount_original")
	o.AmountDiscount = field.NewInt64(table, "amount_discount")
	o.AmountPaid = field.NewInt64(table, "amount_paid")
	o.Snapshot = field.NewJSONB(table, "snapshot")
	o.IdempotencyKey = field.NewString(table, "idempotency_key")
	o.PaidAt = field.NewTime(table, "paid_at")
	o.RefundedAt = field.NewTime(table, "refunded_at")
	o.RefundForced = field.NewBool(table, "refund_forced")
	o.RefundOperatorUserID = field.NewInt64(table, "refund_operator_user_id")
	o.RefundReason = field.NewString(table, "refund_reason")
	o.CreatedAt = field.NewTime(table, "created_at")
	o.UpdatedAt = field.NewTime(table, "updated_at")
	o.CouponID = field.NewInt64(table, "coupon_id")

	o.fillFieldMap()

	return o
}

func (o *orderQuery) QueryContext(ctx context.Context) (*orderQuery, *orderQueryDo) {
	return o, o.orderQueryDo.WithContext(ctx)
}

func (o *orderQuery) WithContext(ctx context.Context) *orderQueryDo {
	return o.orderQueryDo.WithContext(ctx)
}

func (o orderQuery) TableName() string { return o.orderQueryDo.TableName() }

func (o orderQuery) Alias() string { return o.orderQueryDo.Alias() }

func (o orderQuery) Columns(cols ...field.Expr) gen.Columns { return o.orderQueryDo.Columns(cols...) }

func (o *orderQuery) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
	_f, ok := o.fieldMap[fieldName]
	if !ok || _f == nil {
		return nil, false
	}
	_oe, ok := _f.(field.OrderExpr)
	return _oe, ok
}

func (o *orderQuery) fillFieldMap() {
	o.fieldMap = make(map[string]field.Expr, 19)
	o.fieldMap["id"] = o.ID
	o.fieldMap["tenant_id"] = o.TenantID
	o.fieldMap["user_id"] = o.UserID
	o.fieldMap["type"] = o.Type
	o.fieldMap["status"] = o.Status
	o.fieldMap["currency"] = o.Currency
	o.fieldMap["amount_original"] = o.AmountOriginal
	o.fieldMap["amount_discount"] = o.AmountDiscount
	o.fieldMap["amount_paid"] = o.AmountPaid
	o.fieldMap["snapshot"] = o.Snapshot
	o.fieldMap["idempotency_key"] = o.IdempotencyKey
	o.fieldMap["paid_at"] = o.PaidAt
	o.fieldMap["refunded_at"] = o.RefundedAt
	o.fieldMap["refund_forced"] = o.RefundForced
	o.fieldMap["refund_operator_user_id"] = o.RefundOperatorUserID
	o.fieldMap["refund_reason"] = o.RefundReason
	o.fieldMap["created_at"] = o.CreatedAt
	o.fieldMap["updated_at"] = o.UpdatedAt
	o.fieldMap["coupon_id"] = o.CouponID
}

func (o orderQuery) clone(db *gorm.DB) orderQuery {
	o.orderQueryDo.ReplaceConnPool(db.Statement.ConnPool)
	return o
}

func (o orderQuery) replaceDB(db *gorm.DB) orderQuery {
	o.orderQueryDo.ReplaceDB(db)
	return o
}

type orderQueryDo struct{ gen.DO }

func (o orderQueryDo) Debug() *orderQueryDo {
	return o.withDO(o.DO.Debug())
}

func (o orderQueryDo) WithContext(ctx context.Context) *orderQueryDo {
	return o.withDO(o.DO.WithContext(ctx))
}

func (o orderQueryDo) ReadDB() *orderQueryDo {
	return o.Clauses(dbresolver.Read)
}

func (o orderQueryDo) WriteDB() *orderQueryDo {
	return o.Clauses(dbresolver.Write)
}

func (o orderQueryDo) Session(config *gorm.Session) *orderQueryDo {
	return o.withDO(o.DO.Session(config))
}

func (o orderQueryDo) Clauses(conds ...clause.Expression) *orderQueryDo {
	return o.withDO(o.DO.Clauses(conds...))
}

func (o orderQueryDo) Returning(value interface{}, columns ...string) *orderQueryDo {
	return o.withDO(o.DO.Returning(value, columns...))
}

func (o orderQueryDo) Not(conds ...gen.Condition) *orderQueryDo {
	return o.withDO(o.DO.Not(conds...))
}

func (o orderQueryDo) Or(conds ...gen.Condition) *orderQueryDo {
	return o.withDO(o.DO.Or(conds...))
}

func (o orderQueryDo) Select(conds ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Select(conds...))
}

func (o orderQueryDo) Where(conds ...gen.Condition) *orderQueryDo {
	return o.withDO(o.DO.Where(conds...))
}

func (o orderQueryDo) Order(conds ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Order(conds...))
}

func (o orderQueryDo) Distinct(cols ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Distinct(cols...))
}

func (o orderQueryDo) Omit(cols ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Omit(cols...))
}

func (o orderQueryDo) Join(table schema.Tabler, on ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Join(table, on...))
}

func (o orderQueryDo) LeftJoin(table schema.Tabler, on ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.LeftJoin(table, on...))
}

func (o orderQueryDo) RightJoin(table schema.Tabler, on ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.RightJoin(table, on...))
}

func (o orderQueryDo) Group(cols ...field.Expr) *orderQueryDo {
	return o.withDO(o.DO.Group(cols...))
}

func (o orderQueryDo) Having(conds ...gen.Condition) *orderQueryDo {
	return o.withDO(o.DO.Having(conds...))
}

func (o orderQueryDo) Limit(limit int) *orderQueryDo {
	return o.withDO(o.DO.Limit(limit))
}

func (o orderQueryDo) Offset(offset int) *orderQueryDo {
	return o.withDO(o.DO.Offset(offset))
}

func (o orderQueryDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *orderQueryDo {
	return o.withDO(o.DO.Scopes(funcs...))
}

func (o orderQueryDo) Unscoped() *orderQueryDo {
	return o.withDO(o.DO.Unscoped())
}

func (o orderQueryDo) Create(values ...*Order) error {
	if len(values) == 0 {
		return nil
	}
	return o.DO.Create(values)
}

func (o orderQueryDo) CreateInBatches(values []*Order, batchSize int) error {
	return o.DO.CreateInBatches(values, batchSize)
}

// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (o orderQueryDo) Save(values ...*Order) error {
	if len(values) == 0 {
		return nil
	}
	return o.DO.Save(values)
}

func (o orderQueryDo) First() (*Order, error) {
	if result, err := o.DO.First(); err != nil {
		return nil, err
	} else {
		return result.(*Order), nil
	}
}

func (o orderQueryDo) Take() (*Order, error) {
	if result, err := o.DO.Take(); err != nil {
		return nil, err
	} else {
		return result.(*Order), nil
	}
}

func (o orderQueryDo) Last() (*Order, error) {
	if result, err := o.DO.Last(); err != nil {
		return nil, err
	} else {
		return result.(*Order), nil
	}
}

func (o orderQueryDo) Find() ([]*Order, error) {
	result, err := o.DO.Find()
	return result.([]*Order), err
}

func (o orderQueryDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*Order, err error) {
	buf := make([]*Order, 0, batchSize)
	err = o.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
		defer func() { results = append(results, buf...) }()
		return fc(tx, batch)
	})
	return results, err
}

func (o orderQueryDo) FindInBatches(result *[]*Order, batchSize int, fc func(tx gen.Dao, batch int) error) error {
	return o.DO.FindInBatches(result, batchSize, fc)
}

func (o orderQueryDo) Attrs(attrs ...field.AssignExpr) *orderQueryDo {
	return o.withDO(o.DO.Attrs(attrs...))
}

func (o orderQueryDo) Assign(attrs ...field.AssignExpr) *orderQueryDo {
	return o.withDO(o.DO.Assign(attrs...))
}

func (o orderQueryDo) Joins(fields ...field.RelationField) *orderQueryDo {
	for _, _f := range fields {
		o = *o.withDO(o.DO.Joins(_f))
	}
	return &o
}

func (o orderQueryDo) Preload(fields ...field.RelationField) *orderQueryDo {
	for _, _f := range fields {
		o = *o.withDO(o.DO.Preload(_f))
	}
	return &o
}

func (o orderQueryDo) FirstOrInit() (*Order, error) {
	if result, err := o.DO.FirstOrInit(); err != nil {
		return nil, err
	} else {
		return result.(*Order), nil
	}
}

func (o orderQueryDo) FirstOrCreate() (*Order, error) {
	if result, err := o.DO.FirstOrCreate(); err != nil {
		return nil, err
	} else {
		return result.(*Order), nil
	}
}

func (o orderQueryDo) FindByPage(offset int, limit int) (result []*Order, count int64, err error) {
	result, err = o.Offset(offset).Limit(limit).Find()
	if err != nil {
		return
	}

	if size := len(result); 0 < limit && 0 < size && size < limit {
		count = int64(size + offset)
		return
	}

	count, err = o.Offset(-1).Limit(-1).Count()
	return
}

func (o orderQueryDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
	count, err = o.Count()
	if err != nil {
		return
	}

	err = o.Offset(offset).Limit(limit).Scan(result)
	return
}

func (o orderQueryDo) Scan(result interface{}) (err error) {
	return o.DO.Scan(result)
}

func (o orderQueryDo) Delete(models ...*Order) (result gen.ResultInfo, err error) {
	return o.DO.Delete(models)
}

// ForceDelete performs a permanent delete (ignores soft-delete) for current scope.
func (o orderQueryDo) ForceDelete() (gen.ResultInfo, error) {
	return o.Unscoped().Delete()
}

// Inc increases the given column by step for current scope.
func (o orderQueryDo) Inc(column field.Expr, step int64) (gen.ResultInfo, error) {
	// column = column + step
	e := field.NewUnsafeFieldRaw("?+?", column.RawExpr(), step)
	return o.DO.UpdateColumn(column, e)
}

// Dec decreases the given column by step for current scope.
func (o orderQueryDo) Dec(column field.Expr, step int64) (gen.ResultInfo, error) {
	// column = column - step
	e := field.NewUnsafeFieldRaw("?-?", column.RawExpr(), step)
	return o.DO.UpdateColumn(column, e)
}

// Sum returns SUM(column) for current scope.
func (o orderQueryDo) Sum(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("SUM(?)", column.RawExpr())
	if err := o.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Avg returns AVG(column) for current scope.
func (o orderQueryDo) Avg(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("AVG(?)", column.RawExpr())
	if err := o.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Min returns MIN(column) for current scope.
func (o orderQueryDo) Min(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("MIN(?)", column.RawExpr())
	if err := o.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// Max returns MAX(column) for current scope.
func (o orderQueryDo) Max(column field.Expr) (float64, error) {
	var _v float64
	agg := field.NewUnsafeFieldRaw("MAX(?)", column.RawExpr())
	if err := o.Select(agg).Scan(&_v); err != nil {
		return 0, err
	}
	return _v, nil
}

// PluckMap returns a map[key]value for selected key/value expressions within current scope.
func (o orderQueryDo) PluckMap(key, val field.Expr) (map[interface{}]interface{}, error) {
	do := o.Select(key, val)
	rows, err := do.DO.Rows()
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	mm := make(map[interface{}]interface{})
	for rows.Next() {
		var k interface{}
		var v interface{}
		if err := rows.Scan(&k, &v); err != nil {
			return nil, err
		}
		mm[k] = v
	}
	return mm, rows.Err()
}

// Exists returns true if any record matches the given conditions.
func (o orderQueryDo) Exists(conds ...gen.Condition) (bool, error) {
	cnt, err := o.Where(conds...).Count()
	if err != nil {
		return false, err
	}
	return cnt > 0, nil
}

// PluckIDs returns all primary key values under current scope.
func (o orderQueryDo) PluckIDs() ([]int64, error) {
	ids := make([]int64, 0, 16)
	pk := field.NewInt64(o.TableName(), "id")
	if err := o.DO.Pluck(pk, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// GetByID finds a single record by primary key.
func (o orderQueryDo) GetByID(id int64) (*Order, error) {
	pk := field.NewInt64(o.TableName(), "id")
	return o.Where(pk.Eq(id)).First()
}

// GetByIDs finds records by primary key list.
func (o orderQueryDo) GetByIDs(ids ...int64) ([]*Order, error) {
	if len(ids) == 0 {
		return []*Order{}, nil
	}
	pk := field.NewInt64(o.TableName(), "id")
	return o.Where(pk.In(ids...)).Find()
}

// DeleteByID deletes records by primary key.
func (o orderQueryDo) DeleteByID(id int64) (gen.ResultInfo, error) {
	pk := field.NewInt64(o.TableName(), "id")
	return o.Where(pk.Eq(id)).Delete()
}

// DeleteByIDs deletes records by a list of primary keys.
func (o orderQueryDo) DeleteByIDs(ids ...int64) (gen.ResultInfo, error) {
	if len(ids) == 0 {
		return gen.ResultInfo{RowsAffected: 0, Error: nil}, nil
	}
	pk := field.NewInt64(o.TableName(), "id")
	return o.Where(pk.In(ids...)).Delete()
}

func (o *orderQueryDo) withDO(do gen.Dao) *orderQueryDo {
	o.DO = *do.(*gen.DO)
	return o
}
