package backend

import (
	"bwallet/pkg/app"
	"bwallet/pkg/e"
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/chain_service"
	"bwallet/service/coin_service"
	"bwallet/service/recommend_coin_service"
	"bwallet/service/trusteeship_coin_service"
	"bwallet/service/wallet_service"
	"bwallet/validate_service"
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
)

func GetCoin(c *gin.Context) {
	id := com.StrTo(c.DefaultQuery("id", "0")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("ID必须大于0")
	if valid.HasErrors() {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	var platform_id int
	if ("administrator" == group) {
		platform_id = com.StrTo(c.DefaultQuery("platform_id", "1")).MustInt()
	} else {
		platform_id = user.UserInfo.PlatformId
	}
	coinService := coin_service.Coin{
		Id:         id,
		PlatformId: strconv.Itoa(platform_id),
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

	handler.SendResponse(c, nil, coin)
	return
}

func GetCoins(c *gin.Context) {
	valid := validation.Validation{}

	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")
	}

	//platform_id := ""
	//if arg := c.Query("platform_id"); arg != "" {
	//	platform_id = c.DefaultQuery("platform_id", "1")
	//}

	if valid.HasErrors() {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	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)
}

func AddCoin(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

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

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

	coinService := coin_service.Coin{
		Name:           coin.Name,
		Nickname:       coin.Nickname,
		Icon:           coin.Icon,
		Introduce:      coin.Introduce,
		Official:       coin.Official,
		Paper:          coin.Paper,
		Platform:       coin.Platform,
		Chain:          coin.Chain,
		Release:        coin.Release,
		AreaSearch:     coin.AreaSearch,
		PublishCount:   coin.PublishCount,
		CirculateCount: coin.CirculateCount,
		Decimals:       coin.Decimals,
		Address:        coin.Address,
		Treaty:         coin.Treaty,
		PlatformId:     "[]",
	}

	if err := coinService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrAddCoin, nil)
		return
	}
	handler.SendResponse(c, nil, nil)
}

func EditCoin(c *gin.Context) {
	coin := validate_service.EditCoin{}
	c.ShouldBindJSON(&coin)

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

	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

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

	coin_exist, _ := coin_model.Get()

	if ("administrator" != group) {
		if (strings.ToUpper(coin_exist.Platform) != strings.ToUpper(coin.Platform)) {
			handler.SendResponse(c, errno.ErrAuthCoin, nil)
			return
		}
	}

	coinService := coin_service.Coin{
		Id:             coin.Id,
		Name:           coin.Name,
		Nickname:       coin.Nickname,
		Icon:           coin.Icon,
		Introduce:      coin.Introduce,
		Official:       coin.Official,
		Paper:          coin.Paper,
		Platform:       coin.Platform,
		Chain:          coin.Chain,
		Release:        coin.Release,
		AreaSearch:     coin.AreaSearch,
		PublishCount:   coin.PublishCount,
		CirculateCount: coin.CirculateCount,
		Decimals:       coin.Decimals,
		Address:        coin.Address,
		PlatformId:     coin_exist.PlatformId,
		Treaty:         coin.Treaty,
	}

	if err := coinService.Edit(); err != nil {
		handler.SendResponse(c, errno.ErrUpdateCoin, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func DeleteCoin(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

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

	id := com.StrTo(c.DefaultQuery("id", "0")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("ID必须大于0")
	if valid.HasErrors() {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

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

	if !exists {
		handler.SendResponse(c, errno.ErrValidation, nil)
		return
	}

	err = coinService.Delete()
	if err != nil {
		handler.SendResponse(c, errno.ErrDeleteCoin, nil)
		return
	}

	recommendCoinService := recommend_coin_service.RecommendCoin{Cid: id}
	recommendCoinService.DeleteByCondition()
	trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{Cid: id}
	trusteeshipCoinService.DeleteTrusteeshipByCondition()
	handler.SendResponse(c, nil, nil)
}

func GetCoinsByPlatform(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)

	walletService := wallet_service.Wallet{
		Id: user.UserInfo.PlatformId,
	}
	wallet, _ := walletService.Get()

	chainService := chain_service.Chain{
		Id: wallet.ChainId,
	}
	chain, _ := chainService.Get()

	coinService := coin_service.Coin{
		PlatformId: util.ToString(user.UserInfo.PlatformId),
		Platform:   chain.Platform,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	column := []string{"id", "name"}
	coins, err := coinService.GetAllCoins(column)
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	handler.SendResponse(c, nil, coins)
}

func GetCoinChains(c *gin.Context) {
	appG := app.Gin{c}
	coinService := coin_service.Coin{}
	coins, err := coinService.GetCoinChains()
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_GET_COIN_FAIL, nil)
		return
	}

	data := make(map[string]interface{})
	var items [] string
	for _, value := range coins {
		if "" != value.Chain {
			items = append(items, value.Chain)
		}
	}

	data["items"] = items

	handler.SendResponse(c, nil, data)
}

func GetPrimaryChains(c *gin.Context) {
	data := make(map[string]interface{})
	data["items"] = [] string{"BTC", "ETH", "BTY", "DCR"}

	handler.SendResponse(c, nil, data)
}

func GetTypes(c *gin.Context) {
	data := make(map[string]interface{})
	data["items"] = [] string{"coins", "er c20/token"}

	handler.SendResponse(c, nil, data)
}
