package service

import (
	"context"
	"encoding/json"
	"github.com/go-kratos/kratos/v2/errors"
	err2 "voucher/api/err"
	v1 "voucher/api/v1"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/vo"
)

func (c *CmbService) Order(ctx context.Context, request *v1.CmbRequest) (*v1.CmbReply, error) {

	orderNo, err := c.order(ctx, request)

	if err != nil {
		return c.OrderFail(ctx, err)
	}

	return c.OrderSuccess(ctx, orderNo)
}

func (c *CmbService) order(ctx context.Context, request *v1.CmbRequest) (string, error) {

	bizContent, err := c.CmbMixRepo.OrderVerify(ctx, request)
	if err != nil {
		return "", err
	}

	boReq := &bo.OrderCreateReqBo{
		OutBizNo:    bizContent.TransactionId,
		ProductNo:   bizContent.ActivityId,
		Account:     bizContent.CmbUid,
		AppID:       bizContent.AppId,
		Attach:      bizContent.Attach,
		AccountType: vo.OrderAccountTypeOpenId,
		Type:        vo.OrderTypeCmb,
		NotifyUrl:   c.bc.Cmb.NotifyUrl,
	}

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

	return orderNo, nil
}

func (c *CmbService) OrderSuccess(ctx context.Context, orderNo string) (*v1.CmbReply, error) {

	bizReply := &v1.CmbOrderReply{
		RespCode: vo.CmbResponseStatusSuccess.GetValue(),
		RespMsg:  "成功",
		CodeNo:   orderNo,
	}

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}

func (c *CmbService) OrderFail(ctx context.Context, err error) (*v1.CmbReply, error) {

	se := errors.FromError(err)

	if len(se.Reason) == 0 {
		se.Reason = err2.CmbErr_CMB_UNKNOWN.String()
	}

	bizReply := &v1.CmbOrderReply{
		RespCode:     vo.CmbResponseStatusFail.GetValue(),
		RespMsg:      se.Message,
		CodeNo:       "",
		ThirdErrCode: se.Reason,
	}

	replyBizContent, _ := json.Marshal(bizReply)

	return c.GetResponse(ctx, replyBizContent)
}
