package admin_order

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

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

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

func (l *AdminCreateOrderLogic) AdminCreateOrder(req *types.AdminCreateOrderReq) (resp *types.AdminCreateOrderResp, err error) {
	// 生成订单号
	orderNo := fmt.Sprintf("%dADMIN", time.Now().UnixNano())

	// 根据产品名称查询产品ID
	builder := l.svcCtx.ProductModel.SelectBuilder()
	builder = builder.Where("product_name = ? AND del_state = ?", req.ProductName, 0)
	products, err := l.svcCtx.ProductModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 查询产品失败 err: %v", err)
	}
	if len(products) == 0 {
		return nil, errors.Wrapf(xerr.NewErrMsg(fmt.Sprintf("产品不存在: %s", req.ProductName)), "AdminCreateOrder, 查询产品失败 err: %v", err)
	}
	product := products[0]

	// 创建订单对象
	order := &model.Order{
		OrderNo:         orderNo,
		PlatformOrderId: sql.NullString{String: req.PlatformOrderId, Valid: req.PlatformOrderId != ""},
		ProductId:       product.Id,
		PaymentPlatform: req.PaymentPlatform,
		PaymentScene:    req.PaymentScene,
		Amount:          req.Amount,
		Status:          req.Status,
	}

	// 使用事务处理订单创建
	var orderId int64
	err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 插入订单
		result, err := l.svcCtx.OrderModel.Insert(ctx, session, order)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 创建订单失败 err: %v", err)
		}

		// 获取订单ID
		orderId, err = result.LastInsertId()
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 获取订单ID失败 err: %v", err)
		}

		// 如果是推广订单，创建推广订单记录
		if req.IsPromotion == 1 {
			promotionOrder := &model.AdminPromotionOrder{
				OrderId:    orderId,
				Version:    1,
				CreateTime: time.Now(),
				UpdateTime: time.Now(),
			}
			_, err = l.svcCtx.AdminPromotionOrderModel.Insert(ctx, session, promotionOrder)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminCreateOrder, 创建推广订单失败 err: %v", err)
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.AdminCreateOrderResp{
		Id: orderId,
	}, nil
}
