package admin_order

import (
	"context"
	"database/sql"
	"fmt"
	"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 AdminRefundOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

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

	// 检查订单状态
	if order.Status != "paid" {
		return nil, errors.Wrapf(xerr.NewErrMsg("订单状态不正确，无法退款"), "AdminRefundOrder, 订单状态不正确，无法退款 err: %v", err)
	}

	// 检查退款金额
	if req.RefundAmount > order.Amount {
		return nil, errors.Wrapf(xerr.NewErrMsg("退款金额不能大于订单金额"), "AdminRefundOrder, 退款金额不能大于订单金额 err: %v", err)
	}
	refundResp, err := l.svcCtx.AlipayService.AliRefund(l.ctx, order.OrderNo, req.RefundAmount)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "AdminRefundOrder, 退款失败 err: %v", err)
	}
	if refundResp.IsSuccess() {
		err = l.svcCtx.OrderModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
			// 创建退款记录
			refund := &model.OrderRefund{
				RefundNo:         fmt.Sprintf("refund-%s", order.OrderNo),
				PlatformRefundId: sql.NullString{String: refundResp.TradeNo, Valid: true},
				OrderId:          order.Id,
				UserId:           order.UserId,
				ProductId:        order.ProductId,
				RefundAmount:     req.RefundAmount,
				RefundReason:     sql.NullString{String: req.RefundReason, Valid: true},
				Status:           model.OrderRefundStatusPending,
				RefundTime:       sql.NullTime{Time: time.Now(), Valid: true},
			}

			if _, err := l.svcCtx.OrderRefundModel.Insert(ctx, session, refund); err != nil {
				return fmt.Errorf("创建退款记录失败: %v", err)
			}

			// 更新订单状态
			order.Status = model.OrderStatusRefunded
			order.RefundTime = sql.NullTime{Time: time.Now(), Valid: true}
			if _, err := l.svcCtx.OrderModel.Update(ctx, session, order); err != nil {
				return fmt.Errorf("更新订单状态失败: %v", err)
			}
			return nil
		})
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "AdminRefundOrder, 退款失败 err: %v", err)
		}
		return &types.AdminRefundOrderResp{
			Status:   model.OrderStatusRefunded,
			RefundNo: fmt.Sprintf("refund-%s", order.OrderNo),
			Amount:   req.RefundAmount,
		}, nil
	} else {
		return nil, errors.Wrapf(xerr.NewErrMsg(fmt.Sprintf("退款失败, : %v", refundResp.Msg)), "AdminRefundOrder, 退款失败 err: %v", err)
	}

}
