package models

import (
	"encoding/json"
	"github.com/jinzhu/gorm"
)

type WalletRecommendCategory struct {
	ID         int             `gorm:"primary_key;auto_increment" json:"id"`
	Name       json.RawMessage `json:"name"`
	Sort       uint32          `gorm:"not null;default:1" json:"sort"`
	WalletType uint8           `gorm:"not null;default:1" json:"wallet_type"`
	Status     uint8           `gorm:"not null;default:1" json:"status"`
	PlatformId int             `gorm:"not null;default:0" json:"platform_id"`
}

/**
 * 通过id检查类别是否存在
 * @param id
 * @return
 */
func ExistCategoryById(id int) (bool, error) {
	var category WalletRecommendCategory
	err := db.Select("id").Where("id = ?", id).First(&category).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

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

	return false, nil
}

/**
 * 通过id获取指定类别信息
 * @param id
 * @return
 */
func GetWalletRecommendCategory(id int) (*WalletRecommendCategory, error) {
	var category WalletRecommendCategory
	err := db.Where("id = ?", id).First(&category).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

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

	return &category, nil
}

/**
 * 获取符合条件的信息
 * @return
 */
func GetWalletRecommendCurrencies(pageNum, pageSize int, maps interface{}) ([]*WalletRecommendCategory, error) {
	var categories []*WalletRecommendCategory

	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&categories).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return categories, nil
}

/**
 * 添加推荐类别信息
 * @param
 * @return
 */
func AddWalletRecommendCategory(data map[string]interface{}) (error) {
	category := WalletRecommendCategory{
		Name:       data["name"].(json.RawMessage),
		Sort:       data["sort"].(uint32),
		WalletType: data["wallet_type"].(uint8),
		Status:     data["status"].(uint8),
		PlatformId: data["platform_id"].(int),
	}
	if err := db.Create(&category).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 更新推荐类别信息
 * @param
 * @return
 */
func EditWalletRecommendCategory(id int, data interface{}) error {
	if err := db.Model(&WalletRecommendCategory{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 删除推荐类别信息
 * @param
 * @return
 */
func DeleteWalletRecommendCategory(id int) error {
	if err := db.Where("id = ?", id).Delete(WalletRecommendCategory{}).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 获取推荐类别数量
 * @param
 * @return
 */
func GetRecommendCategoryTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&WalletRecommendCategory{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}
