package models

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

type SupportedCurrency struct {
	Model

	Id         int `json:"primary_key,omitempty"`
	PlatformId int `json:"platform_id"` //钱包ID
	CurrencyId int `json:"currency_id"` //法币ID
	Sort       int `json:"sort"`        //排序

	CurrencyInfo *Currency `gorm:"foreignkey:CurrencyId"`
}

func (c SupportedCurrency) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".coin_supported_currency"
}

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

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

	return false, nil
}

/**
 * 获取符合条件的信息总数
 * @param id
 * @return
 */
func GetSupportedCurrencyTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&SupportedCurrency{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

/**
 * 获取符合条件的信息
 * @param id
 * @return
 */
func GetSupportedCurrencies(pageNum, pageSize int, maps interface{}) ([]*SupportedCurrency, error) {
	var currencies []*SupportedCurrency

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

	return currencies, nil
}

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

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

	return &currency, nil
}

/**
 * 添加计价货币信息
 * @param
 * @return
 */
func AddSupportedCurrency(data map[string]interface{}) (error) {
	currency := SupportedCurrency{
		PlatformId: data["platform_id"].(int),
		CurrencyId: data["currency_id"].(int),
		Sort:       data["sort"].(int),
	}
	if err := db.Create(&currency).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 更新计价货币信息
 * @param
 * @return
 */
func EditSupportedCurrency(id int, data interface{}) error {
	if err := db.Model(&SupportedCurrency{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 删除计价货币信息
 * @param
 * @return
 */
func DeleteSupportedCurrency(id int) error {
	if err := db.Where("id = ?", id).Delete(SupportedCurrency{}).Error; err != nil {
		return err
	}

	return nil
}
