package service

import (
	"encoding/json"
	"github.com/go-kratos/kratos/v2/transport/http"
	v1 "voucher/api/v1"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/vo"
)

func (s *VoucherService) CmbOrder(ctx http.Context) error {

	var (
		reply *v1.CmbReply
		err   error
	)

	bizReply, err := s.cmbOrder(ctx)
	if err != nil {
		reply, err = s.CmbMixRepo.GetResponse(ctx, &bo.CmbResponseBo{
			RespCode:   vo.CmbResponseStatusFail.GetValue(),
			RespMsg:    err.Error(),
			FuncName:   vo.CmbOrderFuncName,
			BizContent: "",
		})
	} else {
		replyBizContent, _ := json.Marshal(bizReply)
		reply, err = s.CmbMixRepo.GetResponse(ctx, &bo.CmbResponseBo{
			RespCode:   vo.CmbResponseStatusSuccess.GetValue(),
			RespMsg:    "成功",
			FuncName:   vo.CmbOrderFuncName,
			BizContent: string(replyBizContent),
		})
	}

	return ctx.JSON(200, reply)
}

func (s *VoucherService) cmbOrder(ctx http.Context) (*v1.CmbOrderReply, error) {

	var req *v1.CmbRequest
	if err := ctx.BindForm(&req); err != nil {
		return nil, err
	}

	if err := req.Validate(); err != nil {
		return nil, err
	}

	bizContent, err := s.CmbMixRepo.OrderVerify(ctx, req, vo.CmbOrderFuncName)
	if err != nil {
		return nil, err
	}

	boReq := &bo.OrderCreateReqBo{
		OutBizNo:    bizContent.TransactionId,
		ProductNo:   bizContent.ActivityId,
		Account:     bizContent.CmbUid,
		AppID:       bizContent.AppId,
		AccountType: vo.OrderAccountTypeOpenId,
	}

	orderNo, err := s.VoucherBiz.CmbOrder(ctx, boReq)
	if err != nil {
		return nil, err
	}

	return &v1.CmbOrderReply{
		CodeNo: orderNo,
	}, nil
}

func (s *VoucherService) CmbProductQuery(ctx http.Context) error {

	var (
		reply *v1.CmbReply
		err   error
	)

	bizReply, err := s.cmbProductQuery(ctx)
	if err != nil {
		reply, err = s.CmbMixRepo.GetResponse(ctx, &bo.CmbResponseBo{
			RespCode:   vo.CmbResponseStatusFail.GetValue(),
			RespMsg:    err.Error(),
			FuncName:   vo.CmbOrderFuncName,
			BizContent: "",
		})
	} else {
		replyBizContent, _ := json.Marshal(bizReply)
		reply, err = s.CmbMixRepo.GetResponse(ctx, &bo.CmbResponseBo{
			RespCode:   vo.CmbResponseStatusSuccess.GetValue(),
			RespMsg:    "成功",
			FuncName:   vo.CmbOrderFuncName,
			BizContent: string(replyBizContent),
		})
	}

	return ctx.JSON(200, reply)
}

func (s *VoucherService) cmbProductQuery(ctx http.Context) (*v1.CmbQueryProductReply, error) {

	var req *v1.CmbRequest
	if err := ctx.BindForm(&req); err != nil {
		return nil, err
	}

	if err := req.Validate(); err != nil {
		return nil, err
	}

	bizContent, err := s.CmbMixRepo.ProductQueryVerify(ctx, req, vo.CmbProductQueryFuncName)
	if err != nil {
		return nil, err
	}

	reply, err := s.VoucherBiz.CmbProductQuery(ctx, bizContent.ActivityId)
	if err != nil {
		return nil, err
	}

	return reply, nil
}
