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", limitStringLen(table.SQLName, 40), rand.Intn(1000000), limitStringLen(fmt.Sprintf("%d", ctx.CompanyId), 8))
	table.Context = ctx
	return table
}

func limitStringLen(s string, l int) string {
	result := s
	subLength := l / 2
	if len(result) > l {
		result = result[:subLength] + result[len(result)-subLength:]
	}
	return result
}

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

func (table *Table) ApplyDefaultModule() *Table {
	if table.TableType == CalculateTable.ToString() || table.TableType == SubProcessTable.ToString() {
		table.TableInfo.SetApplyOn(ModuleQuerySetCenter)
	}
	if table.TableType == SchemaTable.ToString() {
		table.TableInfo.SetApplyOn(ModuleQuerySetCenter | ModuleCalculateCenter)
	}
	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 (table *Table) Fields(includePK bool) []*Field {
	var fields []*Field

	if includePK && table.PK != nil {
		fields = append(fields, table.PK)
	}
	fields = append(fields, table.DataFields...)
	if table.TableType == SubTable.ToString() {
		fields = append(fields, table.ManualFields...)
	}
	table.fields = fields

	return table.fields
}

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

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

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

func TableTypesToStringList(list ...TableType) []string {
	var result = make([]string, 0)
	for _, item := range list {
		result = append(result, item.ToString())
	}
	return result
}

type Tables []*Table

func (tables Tables) ToMap() map[int]*Table {
	var result = make(map[int]*Table)
	for i := range tables {
		result[tables[i].TableId] = tables[i]
	}
	return result
}