package query

import (
	"context"
	"encoding/json"
	"fmt"
	"ycc-server/app/main/api/internal/svc"
	"ycc-server/app/main/api/internal/types"
	"ycc-server/common/ctxdata"
	"ycc-server/common/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryProvisionalOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryProvisionalOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryProvisionalOrderLogic {
	return &QueryProvisionalOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryProvisionalOrderLogic) QueryProvisionalOrder(req *types.QueryProvisionalOrderReq) (resp *types.QueryProvisionalOrderResp, err error) {
	userID, getUidErr := ctxdata.GetUidFromCtx(l.ctx)
	if getUidErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 获取用户信息失败, %+v", getUidErr)
	}
	redisKey := fmt.Sprintf("%d:%s", userID, req.Id)
	cache, cacheErr := l.svcCtx.Redis.GetCtx(l.ctx, redisKey)
	if cacheErr != nil {
		return nil, cacheErr
	}
	var data types.QueryCache
	err = json.Unmarshal([]byte(cache), &data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 解析缓存内容失败, %v", err)
	}

	productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, data.Product)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 查找产品错误: %v", err)
	}
	var product types.Product
	err = copier.Copy(&product, productModel)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取临时订单, 用户信息结构体复制失败: %v", err)
	}
	return &types.QueryProvisionalOrderResp{
		Name:    data.Name,
		IdCard:  data.Name,
		Mobile:  data.Mobile,
		Product: product,
	}, nil
}
