// @Time : 2020/10/29 8:31 下午
// @Author : bingee
package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// 是否存在
func IsExistByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) bool {
	o := orm.NewOrm()
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range where {
		qs = qs.Filter(expr, exprV)
	}
	return qs.Exist()
}

// 获取条数
func GetCountByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) (count int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range where {
		qs = qs.Filter(expr, exprV)
	}
	count, err = qs.Count()
	return
}

// 更新
func UpdateByExpr(ptrStructOrTableName interface{}, where, updateParams map[string]interface{}) error {
	o := orm.NewOrm()
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range where {
		qs = qs.Filter(expr, exprV)
	}
	_, err := qs.Update(updateParams)
	return err
}

// 删除
func DeleteByExpr(ptrStructOrTableName interface{}, where map[string]interface{}) error {
	o := orm.NewOrm()
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range where {
		qs = qs.Filter(expr, exprV)
	}
	_, err := qs.Delete()
	return err
}

// 插入
func InsertData(ptrStructOrTableName interface{}) error {
	o := orm.NewOrm()
	_, err := o.Insert(ptrStructOrTableName)
	return err
}

// 获取数据
func GetDataByExpr(ptrStructOrTableName interface{}, where map[string]interface{}, data interface{}, page ...int64) (err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range where {
		qs = qs.Filter(expr, exprV)
	}
	if len(page) > 1 {
		qs = qs.Limit(page[1], page[0])
	}
	_, err = qs.All(data)
	return err
}
