package charge_r

import (
	"git.hilo.cn/hilo-common/domain"
	"git.hilo.cn/hilo-common/mycontext"
	"git.hilo.cn/hilo-common/resource/config"
	"github.com/gin-gonic/gin"
	"hilo-group/domain/cache/user_c"
	"hilo-group/domain/model/diamond_m"
	"hilo-group/domain/service/diamond_s"
	"hilo-group/myerr/bizerr"
	"hilo-group/req"
	"hilo-group/resp"
)

// @Tags 充值
// @Summary 是否可以分享充值链接
// @Param externalId query string true "分享对象的external id"
// @Success 200
// @Router /v1/charge/share [get]
func CanShareChargeLink(c *gin.Context) (*mycontext.MyContext, error) {
	myContext := mycontext.CreateMyContext(c.Keys)

	userId, lang, err := req.GetUserIdLang(c, myContext)
	if err != nil {
		return myContext, err
	}

	extId := c.Query("externalId")
	model := domain.CreateModelContext(myContext)
	toUser, err := user_c.GetUserByExternalId(model, extId)
	if err != nil {
		return myContext, err
	}

	isDealer, err := diamond_m.IsDiamondDealer(model.DB(), userId)
	if err != nil {
		return myContext, err
	}
	if !isDealer {
		return myContext, bizerr.InvalidParameter
	}

	// 家族限制检查
	if err = diamond_s.NewDiamondService(myContext).CheckDealerTransferFamilyLimit(userId, toUser.ID, lang); err != nil {
		myContext.Log.Errorf("CanShareChargeLink err:%v", err)
		return myContext, err
	}
	type res struct {
		ShareUrl    string `json:"shareUrl"`
		ShareIcon   string `json:"shareIcon"`
		RechargeUrl string `json:"rechargeUrl"`
	}

	// 安卓3.8.0版本有bug,这里暂时兼容
	shareUrl := config.GetH5Config().AGENT_SHARE_URL
	deviceType, major, minor, _, err := req.GetAppVersion(c)
	if err != nil {
		return myContext, err
	}
	myUser, err := user_c.GetUserTinyById(model, userId)
	if err != nil {
		return myContext, err
	}
	if deviceType == "android" {
		if (major > 3) || (major == 3 && minor >= 8) {
			shareUrl = shareUrl + myUser.ExternalId
		}
	}
	rechargeUrl := config.GetH5Config().AGENT_SHARE_URL + myUser.ExternalId

	resp.ResponseOk(c, res{shareUrl, config.GetH5Config().AGENT_SHARE_ICON, rechargeUrl})
	return myContext, nil
}