package admin_order

import (
	"context"
	"sync"

	"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/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/mr"
)

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

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

func (l *AdminGetOrderListLogic) AdminGetOrderList(req *types.AdminGetOrderListReq) (resp *types.AdminGetOrderListResp, err error) {
	// 构建查询条件
	builder := l.svcCtx.OrderModel.SelectBuilder()
	if req.OrderNo != "" {
		builder = builder.Where("order_no = ?", req.OrderNo)
	}
	if req.PlatformOrderId != "" {
		builder = builder.Where("platform_order_id = ?", req.PlatformOrderId)
	}
	if req.ProductName != "" {
		builder = builder.Where("product_id IN (SELECT id FROM product WHERE product_name LIKE ?)", "%"+req.ProductName+"%")
	}
	if req.PaymentPlatform != "" {
		builder = builder.Where("payment_platform = ?", req.PaymentPlatform)
	}
	if req.PaymentScene != "" {
		builder = builder.Where("payment_scene = ?", req.PaymentScene)
	}
	if req.Amount > 0 {
		builder = builder.Where("amount = ?", req.Amount)
	}
	if req.Status != "" {
		builder = builder.Where("status = ?", req.Status)
	}
	if req.IsPromotion != -1 {
		builder = builder.Where("id IN (SELECT order_id FROM admin_promotion_order WHERE del_state = 0)")
	}
	// 时间范围查询
	if req.CreateTimeStart != "" {
		builder = builder.Where("create_time >= ?", req.CreateTimeStart)
	}
	if req.CreateTimeEnd != "" {
		builder = builder.Where("create_time <= ?", req.CreateTimeEnd)
	}
	if req.PayTimeStart != "" {
		builder = builder.Where("pay_time >= ?", req.PayTimeStart)
	}
	if req.PayTimeEnd != "" {
		builder = builder.Where("pay_time <= ?", req.PayTimeEnd)
	}
	if req.RefundTimeStart != "" {
		builder = builder.Where("refund_time >= ?", req.RefundTimeStart)
	}
	if req.RefundTimeEnd != "" {
		builder = builder.Where("refund_time <= ?", req.RefundTimeEnd)
	}

	// 并发获取总数和列表
	var total int64
	var orders []*model.Order
	err = mr.Finish(func() error {
		var err error
		total, err = l.svcCtx.OrderModel.FindCount(l.ctx, builder, "id")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询订单总数失败 err: %v", err)
		}
		return nil
	}, func() error {
		var err error
		orders, err = l.svcCtx.OrderModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询订单列表失败 err: %v", err)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	// 并发获取产品信息和查询状态
	productMap := make(map[int64]string)
	queryStateMap := make(map[int64]string)
	agentOrderMap := make(map[int64]bool)           // 代理订单映射
	agentProcessStatusMap := make(map[int64]string) // 代理处理状态映射

	var mu sync.Mutex

	// 批量获取查询状态
	if len(orders) > 0 {
		orderIds := make([]int64, 0, len(orders))
		for _, order := range orders {
			orderIds = append(orderIds, order.Id)
		}

		// 1. 先查询当前查询状态
		builder := l.svcCtx.QueryModel.SelectBuilder().
			Where(squirrel.Eq{"order_id": orderIds}).
			Columns("order_id", "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), "AdminGetOrderList, 批量查询查询状态失败 err: %v", err)
		}

		// 2. 记录已找到查询状态的订单ID
		foundOrderIds := make(map[int64]bool)
		for _, query := range queries {
			queryStateMap[query.OrderId] = query.QueryState
			foundOrderIds[query.OrderId] = true
		}

		// 3. 查找未找到查询状态的订单是否在清理日志中
		notFoundOrderIds := make([]int64, 0)
		for _, orderId := range orderIds {
			if !foundOrderIds[orderId] {
				notFoundOrderIds = append(notFoundOrderIds, orderId)
			}
		}

		if len(notFoundOrderIds) > 0 {
			// 查询清理日志
			cleanupBuilder := l.svcCtx.QueryCleanupDetailModel.SelectBuilder().
				Where(squirrel.Eq{"order_id": notFoundOrderIds}).
				Where("del_state = ?", globalkey.DelStateNo).
				OrderBy("create_time DESC")
			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), "AdminGetOrderList, 查询清理日志失败 err: %v", err)
			}

			// 记录已清理的订单状态
			for _, detail := range cleanupDetails {
				if _, exists := queryStateMap[detail.OrderId]; !exists {
					queryStateMap[detail.OrderId] = model.QueryStateCleaned // 使用常量标记为已清除状态
				}
			}

			// 对于既没有查询状态也没有清理记录的订单，不设置状态（保持为空字符串）
			for _, orderId := range notFoundOrderIds {
				if _, exists := queryStateMap[orderId]; !exists {
					queryStateMap[orderId] = "" // 未知状态保持为空字符串
				}
			}
		}

		// 批量获取代理订单状态
		agentOrders, err := l.svcCtx.AgentOrderModel.FindAll(l.ctx,
			l.svcCtx.AgentOrderModel.SelectBuilder().Where(squirrel.Eq{"order_id": orderIds}), "")
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 批量查询代理订单失败 err: %v", err)
		}

		// 记录代理订单
		for _, agentOrder := range agentOrders {
			agentOrderMap[agentOrder.OrderId] = true
		}

		// 对于代理订单，查询代理处理状态
		if len(agentOrders) > 0 {
			agentOrderIds := make([]int64, 0, len(agentOrders))
			for _, agentOrder := range agentOrders {
				agentOrderIds = append(agentOrderIds, agentOrder.OrderId)
			}

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

			// 记录有佣金记录的订单为处理成功
			processedOrderIds := make(map[int64]bool)
			for _, commission := range commissions {
				processedOrderIds[commission.OrderId] = true
			}

			// 创建订单状态映射，避免重复查找
			orderStatusMap := make(map[int64]string)
			for _, order := range orders {
				orderStatusMap[order.Id] = order.Status
			}

			// 设置代理处理状态
			for _, agentOrder := range agentOrders {
				orderId := agentOrder.OrderId
				if processedOrderIds[orderId] {
					agentProcessStatusMap[orderId] = "success"
				} else {
					// 检查订单状态，如果是已支付但无佣金记录，则为待处理或失败
					if orderStatusMap[orderId] == "paid" {
						agentProcessStatusMap[orderId] = "pending"
					} else {
						agentProcessStatusMap[orderId] = "failed"
					}
				}
			}
		}
	}

	// 并发获取产品信息
	err = mr.MapReduceVoid(func(source chan<- interface{}) {
		for _, order := range orders {
			source <- order
		}
	}, func(item interface{}, writer mr.Writer[struct{}], cancel func(error)) {
		order := item.(*model.Order)

		// 获取产品信息
		product, err := l.svcCtx.ProductModel.FindOne(l.ctx, order.ProductId)
		if err != nil && !errors.Is(err, model.ErrNotFound) {
			cancel(errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "AdminGetOrderList, 查询产品信息失败 err: %v", err))
			return
		}
		mu.Lock()
		if product != nil {
			productMap[product.Id] = product.ProductName
		} else {
			productMap[order.ProductId] = "" // 产品不存在时设置为空字符串
		}
		mu.Unlock()
		writer.Write(struct{}{})
	}, func(pipe <-chan struct{}, cancel func(error)) {
		for range pipe {
		}
	})
	if err != nil {
		return nil, err
	}

	// 构建响应
	resp = &types.AdminGetOrderListResp{
		Total: total,
		Items: make([]types.OrderListItem, 0, len(orders)),
	}

	for _, order := range orders {
		item := types.OrderListItem{
			Id:              order.Id,
			OrderNo:         order.OrderNo,
			PlatformOrderId: order.PlatformOrderId.String,
			ProductName:     productMap[order.ProductId],
			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"),
			QueryState:      queryStateMap[order.Id],
		}
		if order.PayTime.Valid {
			item.PayTime = order.PayTime.Time.Format("2006-01-02 15:04:05")
		}
		if order.RefundTime.Valid {
			item.RefundTime = order.RefundTime.Time.Format("2006-01-02 15:04:05")
		}
		// 判断是否为推广订单
		promotionOrder, err := l.svcCtx.AdminPromotionOrderModel.FindOneByOrderId(l.ctx, order.Id)
		if err == nil && promotionOrder != nil {
			item.IsPromotion = 1
		}

		// 设置代理订单相关字段
		if agentOrderMap[order.Id] {
			item.IsAgentOrder = true
			item.AgentProcessStatus = agentProcessStatusMap[order.Id]
		} else {
			item.IsAgentOrder = false
			item.AgentProcessStatus = "not_agent"
		}
		resp.Items = append(resp.Items, item)
	}

	return resp, nil
}
