package tools

import (
	"gorm.io/gen"
	"gorm.io/gorm"
	"strings"
)

type defaultModel struct{}

func (m *defaultModel) TableName() string {
	return "@@table"
}

// Table2Struct 自动生成结构体
// https://gorm.io/zh_CN/gen/database_to_structs.html
func Table2Struct(gormdb *gorm.DB, tabelName, modelName, outPath string) {
	g := gen.NewGenerator(gen.Config{
		OutPath:       outPath,
		FieldNullable: true,
		//Mode:          gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
	})

	g.UseDB(gormdb) // reuse your gorm db

	// 添加默认TableName方法
	g.WithOpts(gen.WithMethod((&defaultModel{}).TableName))

	g.ApplyBasic(
		// Generate struct `Employee` based on table `users`
		g.GenerateModelAs(tabelName, modelName, gen.FieldModify(func(field gen.Field) gen.Field {
			strs := strings.Split(field.Name, "_")
			for idx, str := range strs {
				strs[idx] = strings.ToUpper(str[:1]) + strings.ToLower(str[1:])
			}
			field.Name = strings.Join(strs, "")
			if t, ok := field.GORMTag["comment"]; ok {
				field.GORMTag["comment"] = []string{strings.Split(t[0], ";")[0]}
			}
			field.Tag["json"] = strings.ToLower(field.Name[:1]) + field.Name[1:]
			return field
		})),
	)
	// Generate the code
	g.Execute()
}
