package models

import (
	orm "go-admin/common/global"
	"go-admin/logger"
	"time"
)

type HotSearch struct {
	Model

	Keyword string `json:"keyword"`           // 搜索内容
	Sort    uint32 `json:"sort" gorm:"index"` // 排序
}

func (*HotSearch) TableName() string {
	return "hot_search"
}

func (h *HotSearch) GetAll() ([]HotSearch, error) {
	var hots []HotSearch
	err := orm.Eloquent.Table(h.TableName()).Unscoped().Find(&hots).Error
	if err != nil && err != RecordNotFound {
		logger.Errorf("err:", err)
		return hots, err
	}
	return hots, nil
}

func (h *HotSearch) Modify() error {
	paraMap := make(map[string]interface{}, 0)
	if h.Keyword != "" {
		paraMap["keyword"] = h.Keyword
	}
	if h.Sort > 0 {
		paraMap["sort"] = h.Sort
	}
	err := orm.Eloquent.Table(h.TableName()).Unscoped().Where("id", h.ID).Updates(paraMap).Error
	if err != nil {
		logger.Errorf("err:", err)
		return err
	}
	return nil
}

func (h *HotSearch) Del(ids []uint32) error {
	err := orm.Eloquent.Table(h.TableName()).Unscoped().Where("id in (?)", ids).Delete(h).Error
	if err != nil {
		logger.Errorf("err:", err)
		return err
	}
	return nil
}

func (h *HotSearch) Create() error {
	h.CreatedAt = time.Now()
	h.UpdatedAt = time.Now()
	err := orm.Eloquent.Create(h).Error
	if err != nil {
		logger.Errorf("err:", err)
		return err
	}
	return err
}
