package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
)

type News struct {
	Model

	Title      string `gorm:"size:255;not null;" json:"title"`
	Content    string `gorm:"not null;" json:"content"`
	Top        uint8  `gorm:"not null;default:0" json:"top"`
	Highlight  uint8  `gorm:"not null;default:0" json:"highlight"`
	PlatformId int    `gorm:"not null;default:1" json:"platform_id"`
	CreateTime int64  `gorm:"not null;" json:"create_time"`
}

func (w News) TableName() string {
	return setting.DatabaseSetting.Name_Coin + ".news"
}

func ExistNewsById(id int) (bool, error) {
	var news News
	err := db.Select("id").Where("id = ?", id).First(&news).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if news.ID > 0 {
		return true, nil
	}

	return false, nil
}

func GetNewsTotal(maps interface{}) (int, error) {
	var count int

	//if tmpmap, ok := maps.(map[string]interface{}); ok {
	//	_, ok = tmpmap["search_type"]
	//	if ok {
	//
	//	}
	//}
	if _, ok := maps.(map[string]interface{})["search_type"]; ok {
		if err := db.Model(&News{}).Where("platform_id in (?)", maps.(map[string]interface{})["search_type"]).Count(&count).Error; err != nil {
			return 0, err
		}
	} else {
		if err := db.Model(&News{}).Where(maps).Count(&count).Error; err != nil {
			return 0, err
		}
	}

	return count, nil
}

func GetNews(pageNum, pageSize int, maps interface{}) ([]*News, error) {
	var news []*News
	if _, ok := maps.(map[string]interface{})["search_type"]; ok {
		err := db.Where("platform_id in (?)", maps.(map[string]interface{})["search_type"]).Order("top desc").Order("create_time desc").Offset(pageNum).Limit(pageSize).Find(&news).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	} else {
		err := db.Where(maps).Order("top desc").Order("create_time desc").Offset(pageNum).Limit(pageSize).Find(&news).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	}

	return news, nil
}

func GetOneNews(maps interface{}) (*News, error) {
	var news News
	err := db.Where(maps).First(&news).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&news).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &news, nil
}

func AddNews(data map[string]interface{}) (error) {
	news := News{
		Title:      data["title"].(string),
		Content:    data["content"].(string),
		Top:        data["top"].(uint8),
		Highlight:  data["highlight"].(uint8),
		PlatformId: data["platform_id"].(int),
		CreateTime: data["create_time"].(int64),
	}
	if err := db.Create(&news).Error; err != nil {
		return err
	}

	return nil
}

func EditNews(id int, data interface{}) error {
	if err := db.Model(&News{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

func DeleteNews(id int) error {
	if err := db.Where("id = ?", id).Delete(News{}).Error; err != nil {
		return err
	}

	return nil
}
