package models

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

type WalletCoinRelation struct {
	Model

	PlatformId int `json:"platform_id"` //钱包ID
	CoinId     int `json:"coin_id"`     //币种ID

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

func (c WalletCoinRelation) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_coin_relation"
}

/**
 * 获取符合条件的信息总数
 * @param id
 * @return
 */
func GetWalletCoinRelationTotal(maps interface{}) (int, error) {
	var count int

	relation_map := make(map[string]interface{})
	coin_map := make(map[string]interface{})
	for key, value := range maps.(map[string]interface{}) {
		if ("platform_id" == key || "coin_id" == key) {
			relation_map[key] = value
		}

		if ("condition" == key) {
			for k, v := range value.(map[string]interface{}) {
				coin_map[k] = v
			}
		}
	}

	if err := db.Model(&WalletCoinRelation{}).Where(relation_map).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

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

	relation_map := make(map[string]interface{})
	coin_map := make(map[string]interface{})
	for key, value := range maps.(map[string]interface{}) {
		if ("platform_id" == key || "coin_id" == key) {
			relation_map[key] = value
		}

		if ("condition" == key) {
			for k, v := range value.(map[string]interface{}) {
				coin_map[k] = v
			}
		}
	}

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

	return coins, nil
}

/**
 * 添加币种钱包对应关系
 * @param
 * @return
 */
func AddWalletCoinRelation(data map[string]interface{}) (error) {
	wallet_coin_relateion := WalletCoinRelation{
		PlatformId: data["platform_id"].(int),
		CoinId:     data["coin_id"].(int),
	}
	if err := db.Create(&wallet_coin_relateion).Error; err != nil {
		return err
	}

	return nil
}

/**
 * 删除钱包币关系
 * @param
 * @return
 */
func DeleteWalletCoinRelation(platform_id, coin_id int) error {
	if err := db.Where("platform_id = ? and coin_id = ?", platform_id, coin_id).Delete(WalletCoinRelation{}).Error; err != nil {
		return err
	}

	return nil
}
