package models

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

type SupportedChain struct {
	Model

	Id         int `json:"primary_key,omitempty"`
	PlatformId int `json:"platform_id"` //钱包ID
	CoinId     int `json:"coin_id"`     //币种ID

	Coin *Coin `gorm:"ForeignKey:Id"`
}

func (c SupportedChain) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".coin_supported_chain"
}

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

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

	return false, nil
}

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

	return count, nil
}

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

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

	return chains, nil
}

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

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

	return &chain, nil
}

/**
 * 添加支持主链
 * @param
 * @return
 */
func AddSupportedChain(data map[string]interface{}) (error) {
	chain := SupportedChain{
		PlatformId: data["platform_id"].(int),
		CoinId:     data["coin_id"].(int),
	}
	fmt.Println(chain)
	if err := db.Create(&chain).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 删除支持主链信息
 * @param
 * @return
 */
func DeleteSupportedChain(id int) error {
	if err := db.Where("id = ?", id).Delete(SupportedChain{}).Error; err != nil {
		return err
	}

	return nil
}
