package backend

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

func GetTrusteeshipCoins(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()
		}
	}

	trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func AddTrusteeshipCoin(c *gin.Context) {
	trusteeship_coin := validate_service.TrusteeshipCoin{}
	c.ShouldBindJSON(&trusteeship_coin)

	//方法一
	if ok, errors := validate_service.ValidateInputs(trusteeship_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

	var platform_id int
	platform_id = user.UserInfo.PlatformId
	if ("administrator" == group) {
		if trusteeship_coin.PlatformId != 0 {
			platform_id = trusteeship_coin.PlatformId
		}
	}

	for _, id := range strings.Split(trusteeship_coin.Cid, ",") {
		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
		}

		trusteeshipCoinValidate := trusteeship_coin_service.TrusteeshipCoin{
			PlatformId: platform_id,
			Cid:        coin_id,
		}
		total, err := trusteeshipCoinValidate.Count()
		if err != nil || total > 0 {
			continue
		}

		trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
			Cid:        coin_id,
			PlatformId: platform_id,
			Sort:       trusteeship_coin.Sort,
		}

		trusteeshipCoinService.Add()
	}

	handler.SendResponse(c, nil, nil)
}

func EditTrusteeshipCoin(c *gin.Context) {
	trusteeship_coin := validate_service.EditTrusteeshipCoin{}
	c.ShouldBindJSON(&trusteeship_coin)

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

	trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{
		Id:   trusteeship_coin.Id,
		Sort: trusteeship_coin.Sort,
	}

	exists, err := trusteeshipCoinService.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) {
		trusteeship_coin_model := trusteeship_coin_service.TrusteeshipCoin{Id: trusteeship_coin.Id}
		trusteeship_coin, _ := trusteeship_coin_model.Get()
		if trusteeship_coin.PlatformId != user.UserInfo.PlatformId {
			handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
			return
		}
	}

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

	handler.SendResponse(c, nil, nil)
}

func DeleteTrusteeshipCoin(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
	}

	trusteeshipCoinService := trusteeship_coin_service.TrusteeshipCoin{Id: id}
	exists, err := trusteeshipCoinService.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) {
		trusteeship_coin, _ := trusteeshipCoinService.Get()
		if trusteeship_coin.PlatformId != user.UserInfo.PlatformId {
			handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
			return
		}
	}
	err = trusteeshipCoinService.Delete()
	if err != nil {
		handler.SendResponse(c, errno.ErrDeleteCoin, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}
