package domain

import "time"

// Table 表
type Table struct {
	// 表Id
	TableId int `json:"tableId"`
	// 表类型 MainTable:主表 SideTable:副表 SubTable:分表  ExcelTable:Excel表
	TableType string `json:"tableType"`
	// 名称
	Name string `json:"name"`
	// 对应数据库名称
	SQLName string `json:"sqlName"`
	// 父级ID
	ParentId int `json:"parentId"`
	// 数据字段序号
	DataFieldIndex int `json:"dataFieldIndex"`
	// 主键字段
	PK *Field `json:"pK"`
	// 数据列
	DataFields []*Field `json:"dataFields"`
	// 手动添加的列
	ManualFields []*Field `json:"manualFields"`
	// 创建时间
	CreatedAt time.Time `json:"createdAt"`
	// 更新时间
	UpdatedAt time.Time `json:"updatedAt"`
	// 删除时间
	DeletedAt time.Time `json:"deletedAt"`
	// 版本
	Version int `json:"version"`

	fields []*Field // 所有列  // PKs + DataFields + ManualFields
	// 业务字段
	RowCount int `json:"rowCount,omitempty"`
	// 扩展
	Context *Context `json:"context"`
}

type TableRepository interface {
	Save(table *Table) (*Table, error)
	Remove(table *Table) (*Table, error)
	FindOne(queryOptions map[string]interface{}) (*Table, error)
	Find(queryOptions map[string]interface{}) (int64, []*Table, error)
}

func (table *Table) Identify() interface{} {
	if table.TableId == 0 {
		return nil
	}
	return table.TableId
}

func (table *Table) WithContext(ctx *Context) *Table {
	table.Context = ctx
	return table
}

func (table *Table) Update(data map[string]interface{}) error {
	return nil
}

func (t *Table) Fields(includePK bool) []*Field {
	var fields []*Field
	if len(t.fields) == 0 {
		if includePK {
			fields = append(fields, t.PK)
		}
		fields = append(fields, t.DataFields...)
		if t.TableType == SubTable.ToString() {
			fields = append(fields, t.ManualFields...)
		}
		t.fields = fields
	}
	return t.fields
}