package backend

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

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

	var category_id uint8
	if arg := c.Query("category_id"); arg != "" {
		category_id = com.StrTo(c.Query("category_id")).MustUint8()
	}

	recommendCoinService := recommend_coin_service.RecommendCoin{
		PlatformId: platform_id,
		CategoryId: category_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

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

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

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

	handler.SendResponse(c, nil, data)
}

func AddRecommendCoin(c *gin.Context) {
	recommend_coin := validate_service.RecommendCoin{}
	c.ShouldBindJSON(&recommend_coin)

	//方法一
	if ok, errors := validate_service.ValidateInputs(recommend_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 recommend_coin.PlatformId != 0 {
			platform_id = recommend_coin.PlatformId
		}
	}

	for _, id := range strings.Split(recommend_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
		}

		recommendCoinValidate := recommend_coin_service.RecommendCoin{
			CategoryId: recommend_coin.CategoryId,
			PlatformId: platform_id,
			Cid:        coin_id,
		}
		total, err := recommendCoinValidate.Count()
		if err != nil || total > 0 {
			continue
		}

		recommendCoinService := recommend_coin_service.RecommendCoin{
			Cid:        coin_id,
			Sort:       recommend_coin.Sort,
			PlatformId: platform_id,
			CategoryId: recommend_coin.CategoryId,
		}

		recommendCoinService.Add()
	}

	handler.SendResponse(c, nil, nil)

	//自定义验证
	/*
		recommendCoinValidate := recommend_coin_service.RecommendCoin{
			CategoryId: recommend_coin.CategoryId,
			PlatformId: recommend_coin.PlatformId,
			Cid:        recommend_coin.Cid,
		}
		total, err := recommendCoinValidate.Count()
		if err != nil {
			handler.SendResponse(c, errno.ErrCountRecommendCoin, nil)
			return
		}
		if (total > 0) {
			handler.SendResponse(c, errno.ErrExistRecommendCoin, nil)
			return
		}

		token := c.Request.Header.Get("Token")
		authService := auth_service.Auth{Token: token}
		auth, _ := authService.GetUserInfo()
		group := auth.Group

		var platform_id int
		platform_id = auth.PlatformId
		if ("administrator" == group) {
			if recommend_coin.PlatformId != 0 {
				platform_id = recommend_coin.PlatformId
			}
		}

		recommendCoinService := recommend_coin_service.RecommendCoin{
			Cid:        recommend_coin.Cid,
			Sort:       recommend_coin.Sort,
			PlatformId: platform_id,
			CategoryId: recommend_coin.CategoryId,
		}

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

		handler.SendResponse(c, nil, nil)
	*/
}

func EditRecommendCoin(c *gin.Context) {
	recommend_coin := validate_service.EditRecommendCoin{}
	c.ShouldBindJSON(&recommend_coin)

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

	recommendCoinService := recommend_coin_service.RecommendCoin{
		Id:   recommend_coin.Id,
		Sort: recommend_coin.Sort,
	}

	exists, err := recommendCoinService.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) {
		recommend_coin_model := recommend_coin_service.RecommendCoin{Id: recommend_coin.Id}
		recommend_coin, _ := recommend_coin_model.Get()
		if recommend_coin.PlatformId != user.UserInfo.PlatformId {
			handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
			return
		}
	}

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

	handler.SendResponse(c, nil, nil)
}

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

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

	handler.SendResponse(c, nil, nil)
}
