advance.go 2.7 KB
package domain

import (
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/util/advance"
)

type (
	Model struct {
		Columns   []advance.Column  `json:"columns"`
		MapColumn advance.MapColumn `json:"-"`
		Name      string            `json:"name"`
	}
	ModelInterface interface {
		ModelName() string
		Columns() []advance.Column
	}
)

var registerModels = make(map[string]Model)

// AdvancedQuerySql 高级查询语句生成
func AdvancedQuerySql(model string, quires advance.AdvancedQueries) string {
	if len(quires) == 0 {
		return ""
	}
	fixQueries := mergeDuplicateQueries(model, quires)
	sql, err := advance.AdvancedQuerySql(fixQueries)
	if err != nil {
		log.Logger.Error(err.Error())
	}
	return sql
}

func mergeDuplicateQueries(model string, quires advance.AdvancedQueries) []advance.AdvancedQuery {
	m, ok := GetModel(model)
	response := make([]advance.AdvancedQuery, 0)
	mapResponse := make(map[string]advance.AdvancedQuery)
	if !ok {
		return response
	}
	for i := range quires {
		c, ok := m.MapColumn[quires[i].Column.Column]
		if !ok {
			continue
		}
		quires[i].Column = c
		if q, ok := mapResponse[c.Column]; ok {
			q.Exprs = append(q.Exprs, quires[i].Exprs...)
		} else {
			mapResponse[c.Column] = quires[i]
		}
	}
	for _, v := range mapResponse {
		response = append(response, v)
	}
	return response
}

func NewModel(m ModelInterface) Model {
	return Model{
		Name:      m.ModelName(),
		Columns:   m.Columns(),
		MapColumn: advance.NewMapColumn(m.Columns()),
	}
}

func RegisModel(m Model) {
	if _, ok := registerModels[m.Name]; ok {
		panic("register modes exists:" + m.Name)
	}
	registerModels[m.Name] = m
}

func GetModel(name string) (Model, bool) {
	m, ok := registerModels[name]
	return m, ok
}

/*User*/
type UserModel struct{}

// 实现接口 ModelInterface
func (u UserModel) ModelName() string { return "user" }
func (u UserModel) Columns() []advance.Column {
	return []advance.Column{
		{
			Column:    "userCode",
			Name:      "用户编号",
			DbAlias:   "user_code",
			ValueType: advance.ValueChars,
		},
		{
			Column:    "userName",
			Name:      "姓名",
			DbAlias:   "ext->>'userName'",
			ValueType: advance.ValueChars,
		},
		{
			Column:    "phone",
			Name:      "手机号",
			DbAlias:   "ext->>'phone'",
			ValueType: advance.ValueChars,
		},
		{
			Column:    "depName",
			Name:      "所属部门",
			DbAlias:   "ext->>'depName'",
			ValueType: advance.ValueChars,
		},
		{
			Column:    "status",
			Name:      "状态",
			DbAlias:   "enable_status",
			ValueType: advance.ValueNumber,
		},
		{
			Column:    "orgName",
			Name:      "组织机构",
			DbAlias:   "ext->>'orgName'",
			ValueType: advance.ValueChars,
		},
	}
}