package model

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"git.i2edu.net/i2/go-zero/core/stores/sqlc"
	"git.i2edu.net/i2/go-zero/core/stores/sqlx"
	"git.i2edu.net/i2/go-zero/core/stringx"
	"git.i2edu.net/i2/go-zero/tools/goctl/model/sql/builderx"
)

var (
	i2billMktQrFieldNames          = builderx.RawFieldNames(&I2billMktQr{})
	i2billMktQrRows                = strings.Join(i2billMktQrFieldNames, ",")
	i2billMktQrRowsExpectAutoSet   = strings.Join(stringx.Remove(i2billMktQrFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	i2billMktQrRowsWithPlaceHolder = strings.Join(stringx.Remove(i2billMktQrFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"
)

type (
	I2billMktQrModel interface {
		Insert(data I2billMktQr) (sql.Result, error)
		FindOne(id int64) (*I2billMktQr, error)
		Update(data I2billMktQr) error
		Delete(id int64) error
	}

	defaultI2billMktQrModel struct {
		conn  sqlx.SqlConn
		table string
	}

	I2billMktQr struct {
		MkId       string    `db:"mk_id" json:"mk_id"`
		DelFlag    int64     `db:"del_flag" json:"del_flag"`
		CreateTime time.Time `db:"create_time" json:"create_time"`
		Id         int64     `db:"id" json:"id"` // 主键
		Qr         string    `db:"qr" json:"qr"` // 二维码url
	}
)

func NewI2billMktQrModel(conn sqlx.SqlConn) I2billMktQrModel {
	return &defaultI2billMktQrModel{
		conn:  conn,
		table: "`i2bill_mkt_qr`",
	}
}

func (t *I2billMktQr) TableName() string {
	return "i2bill_mkt_qr"
}

func (m *defaultI2billMktQrModel) Insert(data I2billMktQr) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?)", m.table, i2billMktQrRowsExpectAutoSet)
	ret, err := m.conn.Exec(query, data.MkId, data.DelFlag, data.Qr)
	return ret, err
}

func (m *defaultI2billMktQrModel) FindOne(id int64) (*I2billMktQr, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", i2billMktQrRows, m.table)
	var resp I2billMktQr
	err := m.conn.QueryRow(&resp, query, id)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultI2billMktQrModel) Update(data I2billMktQr) error {
	query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, i2billMktQrRowsWithPlaceHolder)
	_, err := m.conn.Exec(query, data.MkId, data.DelFlag, data.Qr, data.Id)
	return err
}

func (m *defaultI2billMktQrModel) Delete(id int64) error {
	query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
	_, err := m.conn.Exec(query, id)
	return err
}
