package model

import (
	"context"
	"fmt"
	"time"

	"xingfucha-server/common/globalkey"

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

var _ QueryUserRecordModel = (*customQueryUserRecordModel)(nil)

type (
	// QueryUserRecordModel is an interface to be customized, add more methods here,
	// and implement the added methods in customQueryUserRecordModel.
	QueryUserRecordModel interface {
		queryUserRecordModel
		FindOneByQueryNo(ctx context.Context, queryNo string) (*QueryUserRecord, error)
		CountByEncryptedIdCardIn72Hours(ctx context.Context, encryptedIdCard string) (int64, error)
	}

	customQueryUserRecordModel struct {
		*defaultQueryUserRecordModel
	}
)

// FindOneByQueryNo 根据 query_no 查询一条记录（query_no 与 order.order_no 一致）
func (m *customQueryUserRecordModel) FindOneByQueryNo(ctx context.Context, queryNo string) (*QueryUserRecord, error) {
	query := fmt.Sprintf("select %s from %s where `query_no` = ? and del_state = ? limit 1", queryUserRecordRows, m.table)
	var resp QueryUserRecord
	err := m.QueryRowNoCacheCtx(ctx, &resp, query, queryNo, globalkey.DelStateNo)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// CountByEncryptedIdCardIn72Hours 查询72小时内某个加密身份证号的已支付查询次数
func (m *customQueryUserRecordModel) CountByEncryptedIdCardIn72Hours(ctx context.Context, encryptedIdCard string) (int64, error) {
	// 计算72小时前的时间
	seventyTwoHoursAgo := time.Now().Add(-72 * time.Hour)

	// 关联 order 表，只统计已支付的订单
	query := fmt.Sprintf(`
		select count(*) 
		from %s qur
		inner join `+"`order`"+` o on qur.order_id = o.id
		where qur.id_card = ? 
		  and qur.create_time >= ? 
		  and qur.del_state = ?
		  and qur.order_id > 0
		  and o.status = 'paid'
		  and o.del_state = ?
	`, m.table)
	var count int64
	err := m.QueryRowNoCacheCtx(ctx, &count, query, encryptedIdCard, seventyTwoHoursAgo, globalkey.DelStateNo, globalkey.DelStateNo)
	if err != nil {
		return 0, err
	}
	return count, nil
}

// NewQueryUserRecordModel returns a model for the database table.
func NewQueryUserRecordModel(conn sqlx.SqlConn, c cache.CacheConf) QueryUserRecordModel {
	return &customQueryUserRecordModel{
		defaultQueryUserRecordModel: newQueryUserRecordModel(conn, c),
	}
}
