package backend

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/coin_service"
	"bwallet/validate_service"
	"github.com/Unknwon/com"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func GetWalletCoinRelationCoinRelations(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	var platform_id string
	if ("administrator" == group) {
		platform_id = c.DefaultQuery("platform_id", "1")
	} else {
		platform_id = strconv.Itoa(user.UserInfo.PlatformId)
	}
	name := ""
	if arg := c.Query("name"); arg != "" {
		name = c.Query("name")
	}

	platform := ""
	if arg := c.Query("platform"); arg != "" {
		platform = c.Query("platform")
	}

	chain := ""
	if arg := c.Query("chain"); arg != "" {
		chain = c.Query("chain")
	}

	coinService := coin_service.Coin{
		Name:       name,
		Chain:      chain,
		Platform:   platform,
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	total, err := coinService.Count()
	if err != nil {
		handler.SendResponse(c, errno.ErrCountCoin, nil)
		return
	}

	coins, err := coinService.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = coins
	data["total"] = total

	handler.SendResponse(c, nil, data)
}

/**
 * 添加币种钱包对应关系
 * @param
 * @return
 */
func AddWalletCoinRelationCoinRelation(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	platform_id := user.UserInfo.PlatformId
	coin_relation := validate_service.WalletCoinRelateion{}
	c.ShouldBindJSON(&coin_relation)

	if ("administrator" != group && platform_id != coin_relation.PlatformId) {
		handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
		return
	}

	//方法一
	if ok, errors := validate_service.ValidateInputs(coin_relation); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	for _, id := range strings.Split(coin_relation.CoinId, ",") {
		if id == "" {
			continue
		}
		coin_id, err := strconv.Atoi(id)
		if (nil != err) {
			continue
		}
		coinService := coin_service.Coin{
			Id: coin_id,
		}
		exists, err := coinService.ExistById()
		if err != nil || !exists {
			continue
		}

		coin_exist, _ := coinService.Get()
		platform_id_arr := strings.Split(coin_exist.PlatformId, ",")
		is_exist := false
		for _, exist_platform_id := range platform_id_arr {
			if util.ToInt(exist_platform_id) == coin_relation.PlatformId {
				is_exist = true
			}
		}
		if is_exist == false {
			coinService.PlatformId = coin_exist.PlatformId + "," + strconv.Itoa(coin_relation.PlatformId)
			coinService.UpdateCoinRelation()
		}
	}

	handler.SendResponse(c, nil, nil)
}

/**
 * 删除币种钱包对应关系
 * @param
 * @return
 */
func DeleteWalletCoinRelationCoinRelation(c *gin.Context) {
	var platform_id, coin_id int
	if arg := c.Query("platform_id"); arg != "" {
		platform_id = com.StrTo(c.Query("platform_id")).MustInt()
	}
	if arg := c.Query("coin_id"); arg != "" {
		coin_id = com.StrTo(c.Query("coin_id")).MustInt()
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	if ("administrator" != group) {
		if platform_id != user.UserInfo.PlatformId {
			handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
			return
		}
	}

	if (0 == platform_id || 0 == coin_id) {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	coinService := coin_service.Coin{
		Id: coin_id,
	}
	exists, err := coinService.ExistById()
	if err != nil || !exists {
		handler.SendResponse(c, errno.ErrCoinNotFound, nil)
		return
	}

	coin_exist, _ := coinService.Get()
	platform_id_arr := strings.Split(coin_exist.PlatformId, ",")

	var new_platform_id string
	for _, exist_platform_id := range platform_id_arr {
		if util.ToInt(exist_platform_id) == platform_id {
			continue
		}
		new_platform_id = strings.Join([]string{exist_platform_id, new_platform_id}, ",")
		new_platform_id = strings.TrimRight(new_platform_id, ",")
	}
	coinService.PlatformId = new_platform_id
	coinService.UpdateCoinRelation()

	handler.SendResponse(c, nil, nil)
}
