package service

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/model"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"time"
)

// Peripherals 周边活动
var Peripherals = new(sPeripherals)

type sPeripherals struct{}

func (s *sPeripherals) ReceiveCdk(ctx *gin.Context, req forms.PeripheralsReceiveCdk) serializer.Response {
	var (
		q        = query.Use(config.DB).RedeemCode
		pr       = query.Use(config.DB).RedeemPeripheralsReceived
		models   *model.RedeemCode
		prModels *model.RedeemPeripheralsReceived
		err      error
	)

	if err = pr.WithContext(ctx).Where(pr.Sn.Eq(req.Sn)).Where(pr.Openid.Eq(req.OpenId)).Scan(&prModels); err != nil {
		return serializer.Err(consts.CodeParamErr, "领取记录查询异常", err)
	}

	// 还没有，就给一个
	if prModels == nil {
		if err = q.WithContext(ctx).
			Where(q.Sn.Eq(req.Sn)).
			Where(q.Times.Gt(0)).
			Where(q.Columns(q.ID).NotIn(pr.WithContext(ctx).Select(pr.Cid).Where(pr.Sn.Eq(req.Sn)))).
			Scan(&models); err != nil {
			return serializer.Err(consts.CodeParamErr, "兑换码查询异常-2", err)
		}

		if models == nil {
			return serializer.Err(101, "兑换码已用尽", err)
		}

		var data model.RedeemPeripheralsReceived
		data.Cid = models.ID
		data.Sn = models.Sn
		data.Openid = req.OpenId
		data.CreatedAt = time.Now().Unix()

		if err = query.Use(config.DB).RedeemPeripheralsReceived.WithContext(ctx).Create(&data); err != nil {
			return serializer.Err(consts.CodeParamErr, "兑换码失败，请稍后重试！", err)
		}
		return serializer.Suc(models)
	}

	if err = q.WithContext(ctx).Where(q.ID.Eq(prModels.Cid)).Scan(&models); err != nil {
		return serializer.Err(consts.CodeParamErr, "兑换码查询异常", err)
	}

	if models == nil {
		return serializer.Err(consts.CodeParamErr, "兑换码不存在或已被删除", err)
	}
	return serializer.Suc(models)
}
