package admin_order

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

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

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

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

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

func (l *AdminUpdateOrderLogic) AdminUpdateOrder(req *types.AdminUpdateOrderReq) (resp *types.AdminUpdateOrderResp, err error) {
	// 获取原订单信息
	order, err := l.svcCtx.OrderModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 查询订单失败 err: %v", err)
	}

	// 更新订单字段
	if req.OrderNo != nil {
		order.OrderNo = *req.OrderNo
	}
	if req.PlatformOrderId != nil {
		order.PlatformOrderId = sql.NullString{String: *req.PlatformOrderId, Valid: true}
	}
	if req.PaymentPlatform != nil {
		order.PaymentPlatform = *req.PaymentPlatform
	}
	if req.PaymentScene != nil {
		order.PaymentScene = *req.PaymentScene
	}
	if req.Amount != nil {
		order.Amount = *req.Amount
	}
	if req.Status != nil {
		order.Status = *req.Status
	}
	if req.PayTime != nil {
		payTime, err := time.Parse("2006-01-02 15:04:05", *req.PayTime)
		if err == nil {
			order.PayTime = sql.NullTime{Time: payTime, Valid: true}
		}
	}
	if req.RefundTime != nil {
		refundTime, err := time.Parse("2006-01-02 15:04:05", *req.RefundTime)
		if err == nil {
			order.RefundTime = sql.NullTime{Time: refundTime, Valid: true}
		}
	}

	// 使用事务更新订单
	err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 更新订单
		_, err := l.svcCtx.OrderModel.Update(ctx, session, order)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 更新订单失败 err: %v", err)
		}

		// 处理推广订单状态
		if req.IsPromotion != nil {
			promotionOrder, err := l.svcCtx.AdminPromotionOrderModel.FindOneByOrderId(ctx, order.Id)
			if err == nil && promotionOrder != nil {
				// 如果存在推广订单记录但不需要推广，则删除
				if *req.IsPromotion == 0 {
					err = l.svcCtx.AdminPromotionOrderModel.DeleteSoft(ctx, session, promotionOrder)
					if err != nil {
						return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 删除推广订单失败 err: %v", err)
					}
				}
			} else if *req.IsPromotion == 1 {
				// 如果需要推广但不存在记录，则创建
				newPromotionOrder := &model.AdminPromotionOrder{
					OrderId: order.Id,
					Version: 1,
				}
				_, err = l.svcCtx.AdminPromotionOrderModel.Insert(ctx, session, newPromotionOrder)
				if err != nil {
					return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminUpdateOrder, 创建推广订单失败 err: %v", err)
				}
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.AdminUpdateOrderResp{
		Success: true,
	}, nil
}
