package db

import (
	"applet/app/db/model"
	"applet/app/utils/logx"
	"xorm.io/xorm"
)

type QrcodeBatchDb struct {
	Db *xorm.Engine `json:"db"`
}

func (qrcodeBatchDb *QrcodeBatchDb) Set() { // set方法
	qrcodeBatchDb.Db = Db
}

func (qrcodeBatchDb *QrcodeBatchDb) GetQrcodeBatchById(id int) (m *model.QrcodeBatch, err error) {
	m = new(model.QrcodeBatch)
	has, err := qrcodeBatchDb.Db.Where("id =?", id).Get(m)
	if err != nil {
		return nil, logx.Error(err)
	}
	if has == false {
		return nil, nil
	}
	return m, nil
}

func (qrcodeBatchDb *QrcodeBatchDb) DeleteQrcodeBatchBySession(session *xorm.Session, id int) (delResult int64, err error) {
	m := new(model.QrcodeBatch)
	delResult, err = session.Where("id =?", id).Delete(m)
	return
}

func (qrcodeBatchDb *QrcodeBatchDb) GeLastId() (m *model.QrcodeBatch, err error) {
	m = new(model.QrcodeBatch)
	has, err := qrcodeBatchDb.Db.OrderBy("id Desc").Get(m)
	if err != nil {
		return nil, logx.Error(err)
	}
	if has == false {
		return nil, nil
	}
	return m, nil
}

func (qrcodeBatchDb *QrcodeBatchDb) GetQrcodeBatchByName(name string) (m *model.QrcodeBatch, err error) {
	m = new(model.QrcodeBatch)
	has, err := qrcodeBatchDb.Db.Where("name =?", name).Get(m)
	if err != nil {
		return nil, logx.Error(err)
	}
	if has == false {
		return nil, nil
	}
	return m, nil
}

func (qrcodeBatchDb *QrcodeBatchDb) List(page, limit int) (m []*model.QrcodeBatch, total int64, err error) {
	total, err = qrcodeBatchDb.Db.Desc("id").Limit(limit, (page-1)*limit).FindAndCount(&m)
	return
}

func (qrcodeBatchDb *QrcodeBatchDb) AddBySession(session *xorm.Session, m *model.QrcodeBatch) (err error) {
	_, err = session.InsertOne(m)
	return
}