package models

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/cmd/chart-server/interanl/pkg/domain"
	"gorm.io/gorm"
	"gorm.io/plugin/soft_delete"
	"time"
)

type Chart struct {
	Id        int64  // ID
	Pid       int64  `gorm:"index:idx_chart_t_pid_sort"` // 父级ID
	Type      string // 类型
	Sort      int    `gorm:"index:idx_chart_t_pid_sort"` // 排序
	Name      string // 名称
	Group     string `gorm:"index:idx_chart_group"` // 分组
	Cover     string // 封面
	ChartType string

	TenantId  int64                 `gorm:"index:idx_chart_t_pid_sort"` // 租户ID
	CreatedAt int64                 `json:",omitempty"`
	UpdatedAt int64                 `json:",omitempty"`
	DeletedAt int64                 `json:",omitempty"`
	Version   int                   `json:",omitempty"`
	IsDel     soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt"`
}

func (m *Chart) TableName() string {
	return "chart"
}

func (m *Chart) BeforeCreate(tx *gorm.DB) (err error) {
	m.CreatedAt = time.Now().Unix()
	m.UpdatedAt = time.Now().Unix()
	return
}

func (m *Chart) BeforeUpdate(tx *gorm.DB) (err error) {
	m.UpdatedAt = time.Now().Unix()
	return
}

func (m *Chart) CacheKeyFunc() string {
	if m.Id == 0 {
		return ""
	}
	return fmt.Sprintf("%v:cache:%v:id:%v", domain.ProjectName, m.TableName(), m.Id)
}

func (m *Chart) CacheKeyFuncByObject(obj interface{}) string {
	if v, ok := obj.(*Chart); ok {
		return v.CacheKeyFunc()
	}
	return ""
}

func (m *Chart) CachePrimaryKeyFunc() string {
	if len("") == 0 {
		return ""
	}
	return fmt.Sprintf("%v:cache:%v:primarykey:%v", domain.ProjectName, m.TableName(), "key")
}