package service

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/robfig/cron"
	http2 "net/http"
	"strconv"
	v1 "voucher/api/v1"
	"voucher/internal/biz"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/mixrepos"
	"voucher/internal/biz/timeslicequery"
	"voucher/internal/biz/vo"
	"voucher/internal/biz/wechatrepo"
	"voucher/internal/conf"
)

var _ v1.CmbHTTPServer = (*CmbService)(nil)

type CmbService struct {
	bc             *conf.Bootstrap
	cron           *cron.Cron
	VoucherBiz     *biz.VoucherBiz
	CmbMixRepo     mixrepos.CmbMixRepo
	WechatCpnRepo  wechatrepo.WechatCpnRepo
	timeSliceQuery *timeslicequery.Query
}

func NewCmbService(
	bc *conf.Bootstrap,
	cron *cron.Cron,
	VoucherBiz *biz.VoucherBiz,
	CmbMixRepo mixrepos.CmbMixRepo,
	WechatCpnRepo wechatrepo.WechatCpnRepo,
	timeSliceQuery *timeslicequery.Query,
) *CmbService {
	return &CmbService{
		bc:             bc,
		cron:           cron,
		VoucherBiz:     VoucherBiz,
		CmbMixRepo:     CmbMixRepo,
		WechatCpnRepo:  WechatCpnRepo,
		timeSliceQuery: timeSliceQuery,
	}
}

func (c *CmbService) GetResponse(ctx context.Context, replyBizContent []byte) (*v1.CmbReply, error) {

	req := &bo.CmbResponseBo{
		RespCode:   vo.CmbResponseStatusSuccess.GetValue(),
		RespMsg:    "成功",
		BizContent: string(replyBizContent),
	}

	reply, err := c.CmbMixRepo.GetResponse(ctx, req)
	if err != nil {
		log.Errorf("build cmb response fail: %v", err)
		return nil, err
	}

	return reply, nil
}

func (c *CmbService) OrderRetry(ctx context.Context, request *v1.OrderRetryRequest) (*v1.Empty, error) {

	return nil, c.VoucherBiz.OrderRetry(ctx, request.GetTransactionIds())
}

func (this *CmbService) RegisterTag(ctx http.Context) error {

	id := ctx.Vars().Get("id")
	if id == "" {
		return fmt.Errorf("id is empty")
	}

	int64Id, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		return err
	}

	if err = this.VoucherBiz.RegisterTag(ctx, int32(int64Id)); err != nil {
		return err
	}

	return ctx.JSON(http2.StatusOK, map[string]interface{}{
		"data": id,
	})
}
