package domain

import (
	"fmt"
	"math/rand"
	"strings"
	"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"`
	// 默认排序列
	//OrderFields []*Field `json:"orderFields"`
	// 创建时间
	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"`
	// 表信息
	TableInfo *TableInfo `json:"tableInfo"`
}

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) TableIdString() string {
	return fmt.Sprintf("%v", table.TableId)
}

func (table *Table) WithContext(ctx *Context) *Table {
	rand.Seed(time.Now().Unix())
	table.SQLName = fmt.Sprintf("%v_t%v_c%v", table.SQLName, rand.Intn(1000000), ctx.CompanyId)
	table.Context = ctx
	return table
}

func (table *Table) WithPrefix(prefix string) *Table {
	table.SQLName = fmt.Sprintf("%v_%v", strings.ToLower(prefix), table.SQLName)
	return table
}

func (table *Table) WithParentId(parentId int) *Table {
	table.ParentId = parentId
	return table
}

func (table *Table) WithDataFieldIndex(dataFieldIndex int) *Table {
	table.DataFieldIndex = dataFieldIndex
	return table
}

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

func (t *Table) Fields(includePK bool) []*Field {
	var fields []*Field

	if includePK && t.PK != nil {
		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
}

func (t *Table) MatchField(field *Field) (*Field, bool) {
	if len(t.fields) == 0 {
		t.fields = t.Fields(true)
	}
	mField := (Fields)(t.fields).ToMap()
	if v, ok := mField[field.Name]; ok {
		return v, true
	}
	return nil, false
}

func (t *Table) DependencyTables() []int {
	if t.TableInfo == nil {
		return []int{}
	}
	return t.TableInfo.DependencyTables
}

func (t *Table) AssertTableType(types ...TableType) bool {
	for _, item := range types {
		if t.TableType == item.ToString() {
			return true
		}
	}
	return false
}