package admin_order

import (
	"context"

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

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

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

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

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

	// 获取产品信息
	product, err := l.svcCtx.ProductModel.FindOne(l.ctx, order.ProductId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询产品失败 err: %v", err)
	}

	// 判断是否为推广订单
	var isPromotion int64
	promotionOrder, err := l.svcCtx.AdminPromotionOrderModel.FindOneByOrderId(l.ctx, order.Id)
	if err == nil && promotionOrder != nil {
		isPromotion = 1
	}

	// 判断是否为代理订单并获取代理处理状态
	var isAgentOrder bool
	var agentProcessStatus string

	agentOrder, err := l.svcCtx.AgentOrderModel.FindOneByOrderId(l.ctx, order.Id)
	if err == nil && agentOrder != nil {
		isAgentOrder = true

		// 查询代理佣金记录
		commissions, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx,
			l.svcCtx.AgentCommissionModel.SelectBuilder().Where("order_id = ?", order.Id), "")
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询代理佣金失败 err: %v", err)
		}

		if len(commissions) > 0 {
			agentProcessStatus = "success"
		} else {
			// 检查订单状态，如果是已支付但无佣金记录，则为待处理或失败
			if order.Status == "paid" {
				agentProcessStatus = "pending"
			} else {
				agentProcessStatus = "failed"
			}
		}
	} else {
		isAgentOrder = false
		agentProcessStatus = "not_agent"
	}

	// 获取查询状态
	var queryState string
	builder := l.svcCtx.QueryModel.SelectBuilder().Where("order_id = ?", order.Id).Columns("query_state")
	queries, err := l.svcCtx.QueryModel.FindAll(l.ctx, builder, "")
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询查询状态失败 err: %v", err)
	}

	if len(queries) > 0 {
		queryState = queries[0].QueryState
	} else {
		// 查询清理日志
		cleanupBuilder := l.svcCtx.QueryCleanupDetailModel.SelectBuilder().
			Where("order_id = ?", order.Id).
			Where("del_state = ?", globalkey.DelStateNo).
			OrderBy("create_time DESC").
			Limit(1)
		cleanupDetails, err := l.svcCtx.QueryCleanupDetailModel.FindAll(l.ctx, cleanupBuilder, "")
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderDetail, 查询清理日志失败 err: %v", err)
		}

		if len(cleanupDetails) > 0 {
			queryState = model.QueryStateCleaned
		} else {
			queryState = ""
		}
	}

	// 构建响应
	resp = &types.AdminGetOrderDetailResp{
		Id:                 order.Id,
		OrderNo:            order.OrderNo,
		PlatformOrderId:    order.PlatformOrderId.String,
		ProductName:        product.ProductName,
		PaymentPlatform:    order.PaymentPlatform,
		PaymentScene:       order.PaymentScene,
		Amount:             order.Amount,
		SalesCost:          order.SalesCost,
		Status:             order.Status,
		CreateTime:         order.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:         order.UpdateTime.Format("2006-01-02 15:04:05"),
		IsPromotion:        isPromotion,
		QueryState:         queryState,
		IsAgentOrder:       isAgentOrder,
		AgentProcessStatus: agentProcessStatus,
	}

	// 处理可选字段
	if order.PayTime.Valid {
		resp.PayTime = order.PayTime.Time.Format("2006-01-02 15:04:05")
	}
	if order.RefundTime.Valid {
		resp.RefundTime = order.RefundTime.Time.Format("2006-01-02 15:04:05")
	}

	return resp, nil
}
