package backend

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

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

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if arg := c.Query("platform_id"); arg != "" {
			platform_id = com.StrTo(c.Query("platform_id")).MustInt()
		}
	}

	feeService := fee_service.Fee{
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	fees, err := feeService.GetAllCoinName()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	vals := []string{}
	for _,value := range fees {
		if "" == value.CoinName {
			continue
		}
		vals = append(vals, value.CoinName)
	}

	handler.SendResponse(c, nil, vals)
}

func GetTransactionFees(c *gin.Context) {

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

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if arg := c.Query("platform_id"); arg != "" {
			platform_id = com.StrTo(c.Query("platform_id")).MustInt()
		}
	}

	feeService := fee_service.Fee{
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func EditTransactionFees(c *gin.Context) {
	fee := validate_service.EditFee{}
	c.ShouldBindJSON(&fee)

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

	feeService := fee_service.Fee{
		Id:              fee.Id,
		Fees:            fee.Fees,
		FeesType:        fee.FeesType,
		TransactionFees: fee.TransactionFees,
	}

	exists, err := feeService.ExistById()
	if err != nil {
		handler.SendResponse(c, errno.ErrCoinNotFound, nil)
		return
	}
	if !exists {
		handler.SendResponse(c, errno.ErrCoinNotFound, nil)
		return
	}

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

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

	handler.SendResponse(c, nil, nil)
}
