/**
* @Author: zou.yingbin
* @Create  : 2021/1/29 9:30
* @Modify  : 2021/1/29 9:30
 */

package utils

import "fmt"

// sql辅助构建工具

type SQLVal string

// String 返回自身字符串
func (r *SQLVal) String() string {
	return string(*r)
}

// FormatParam 格式化参数
func (r *SQLVal) FormatParam(a ...interface{}) {
	*r = SQLVal(fmt.Sprintf(r.String(), a...))
}

// And 增加and 条件
func (r *SQLVal) And(fieldName string, val interface{}) {
	if _, ok := val.(string); ok {
		*r = *r + SQLVal(fmt.Sprintf(" and %v = '%v'", fieldName, val))
	} else {
		*r = *r + SQLVal(fmt.Sprintf(" and %v = %v", fieldName, val))
	}
}

// And 增加and 条件, bAdd参数省了在外层写if语句
// 例如:  sqlId.AndEx("t.areauserid", r.areauserid, r.areauserid > 0)
// 如果没有bAdd参数，外层就得写if r.areauserid > 0 {...}
func (r *SQLVal) AndEx(fieldName string, val interface{}, bAdd bool) {
	if bAdd {
		r.And(fieldName, val)
	}
}

// 类似 AndEx, 但是不会为string类型加单引号
func (r *SQLVal) AndInterEx(fieldName string, val interface{}, bAdd bool) {
	if bAdd {
		*r = *r + SQLVal(fmt.Sprintf(" and %v = %v", fieldName, val))
	}
}

// Bigger 大于
func (r *SQLVal) Bigger(fieldName string, val interface{}) {
	*r = *r + SQLVal(fmt.Sprintf(" and %v > %v", fieldName, val))
}

// BiggerOrEq 大于等于
func (r *SQLVal) BiggerOrEq(fieldName string, val interface{}) {
	*r = *r + SQLVal(fmt.Sprintf(" and %v >= %v", fieldName, val))
}

// Less 小于等于
func (r *SQLVal) Less(fieldName string, val interface{}) {
	*r = *r + SQLVal(fmt.Sprintf(" and %v < %v", fieldName, val))
}

// LessOrEq 小于等于
func (r *SQLVal) LessOrEq(fieldName string, val interface{}) {
	*r = *r + SQLVal(fmt.Sprintf(" and %v <= %v", fieldName, val))
}

// Join 自由增加条件
func (r *SQLVal) Join(condition string) {
	*r = *r + SQLVal(condition)
}

// JoinEx  bJoin是否增加
func (r *SQLVal) JoinEx(bJoin bool, condition string) {
	if bJoin {
		r.Join(condition)
	}
}
