import dayjs from 'dayjs';
/** 从订单 payments 提取支付方式 code，与 UI 筛选选项及 filterBookings 一致 */
function getOrderPaymentCodes(order) {
  var payments = order.payments;
  if (!Array.isArray(payments) || payments.length === 0) {
    return [];
  }
  return payments.map(function (item) {
    return item === null || item === void 0 ? void 0 : item.code;
  }).filter(function (code) {
    return typeof code === 'string' && code.length > 0;
  });
}

/**
 * 订单过滤函数
 * @param orders 原始订单列表
 * @param filters 过滤条件
 * @returns 过滤 + 排序 + 分页后的结果
 *
 * @优化口子 性能优化预留：
 * - 可在此函数入口加缓存（按 filters 签名缓存结果）
 * - 可对枚举字段建倒排索引（status/payment_status/shipping_status/customer_id）
 * - 可对文本字段加前缀树或分词索引
 * - 可做增量过滤而非全量遍历
 */
export function filterOrders(orders, filters) {
  // Bug 1 修复：防护 filters 为 null/undefined
  var safeFilters = filters || {};
  if (!orders || !Array.isArray(orders)) {
    return {
      list: [],
      count: 0,
      size: 0,
      skip: 0,
      rejected: []
    };
  }

  // 默认分页参数
  var size = safeFilters.num || 20;
  var page = safeFilters.skip || 1;
  var rejected = [];

  // 1. 过滤
  var filteredList = orders.filter(function (order) {
    if (safeFilters.keyword) {
      if (!JSON.stringify(order).toLowerCase().includes(safeFilters.keyword.toLowerCase())) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'keyword',
            actual: '',
            expected: safeFilters.keyword
          }
        });
        return false;
      }
    }

    // status - 订单状态
    if (safeFilters.status && safeFilters.status.length > 0) {
      if (!order.status || !safeFilters.status.includes(order.status)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'status',
            actual: order.status,
            expected: safeFilters.status
          }
        });
        return false;
      }
    }

    // payment_status - 支付状态
    if (safeFilters.payment_status && safeFilters.payment_status.length > 0) {
      if (!order.payment_status || !safeFilters.payment_status.includes(order.payment_status)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'payment_status',
            actual: order.payment_status,
            expected: safeFilters.payment_status
          }
        });
        return false;
      }
    }

    // shipping_status - 处理状态
    if (safeFilters.shipping_status && safeFilters.shipping_status.length > 0) {
      if (!order.shipping_status || !safeFilters.shipping_status.includes(order.shipping_status)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'shipping_status',
            actual: order.shipping_status,
            expected: safeFilters.shipping_status
          }
        });
        return false;
      }
    }

    // customer_id - 客户ID（精确匹配）
    if (safeFilters.customer_id !== undefined && safeFilters.customer_id !== null) {
      if (String(order.customer_id) !== String(safeFilters.customer_id)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'customer_id',
            actual: order.customer_id,
            expected: safeFilters.customer_id
          }
        });
        return false;
      }
    }

    // order_sales_channel - 销售渠道
    if (safeFilters.order_sales_channel && safeFilters.order_sales_channel.length > 0) {
      if (!order.order_sales_channel || !safeFilters.order_sales_channel.includes(order.order_sales_channel)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'order_sales_channel',
            actual: order.order_sales_channel,
            expected: safeFilters.order_sales_channel
          }
        });
        return false;
      }
    }

    // payment_methods - 支付方式（按 payments[].code 匹配，不再使用 order.payment_methods）
    if (safeFilters.payment_methods && safeFilters.payment_methods.length > 0) {
      var orderPaymentCodes = getOrderPaymentCodes(order);
      if (orderPaymentCodes.length === 0) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'payment_methods',
            actual: order.payments,
            expected: safeFilters.payment_methods
          }
        });
        return false;
      }
      var hasMatch = orderPaymentCodes.some(function (code) {
        return safeFilters.payment_methods.includes(code);
      });
      if (!hasMatch) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'payment_methods',
            actual: orderPaymentCodes,
            expected: safeFilters.payment_methods
          }
        });
        return false;
      }
    }

    // min_total_amount / max_total_amount - 订单金额范围
    if (safeFilters.min_total_amount !== undefined || safeFilters.max_total_amount !== undefined) {
      var orderAmount = parseFloat(String(order.total_amount || 0));
      if (safeFilters.min_total_amount !== undefined && orderAmount < safeFilters.min_total_amount) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'min_total_amount',
            actual: order.total_amount,
            expected: safeFilters.min_total_amount
          }
        });
        return false;
      }
      if (safeFilters.max_total_amount !== undefined && orderAmount > safeFilters.max_total_amount) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'max_total_amount',
            actual: order.total_amount,
            expected: safeFilters.max_total_amount
          }
        });
        return false;
      }
    }

    // tag_ids - 标签（统一 String 比较，兼容 number/string）
    if (safeFilters.tag_ids && safeFilters.tag_ids.length > 0) {
      if (!order.tag_ids || !Array.isArray(order.tag_ids) || order.tag_ids.length === 0) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'tag_ids',
            actual: order.tag_ids,
            expected: safeFilters.tag_ids
          }
        });
        return false;
      }
      var filterTagSet = new Set(safeFilters.tag_ids.map(String));
      var _hasMatch = order.tag_ids.some(function (tag) {
        return filterTagSet.has(String(tag));
      });
      if (!_hasMatch) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'tag_ids',
            actual: order.tag_ids,
            expected: safeFilters.tag_ids
          }
        });
        return false;
      }
    }

    // shipping_type - 配送方式
    if (safeFilters.shipping_type && safeFilters.shipping_type.length > 0) {
      if (!order.shipping_type || !safeFilters.shipping_type.includes(order.shipping_type)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'shipping_type',
            actual: order.shipping_type,
            expected: safeFilters.shipping_type
          }
        });
        return false;
      }
    }

    // delivery_zone_name - 配送区域（模糊匹配）
    if (safeFilters.delivery_zone_name !== undefined && safeFilters.delivery_zone_name !== null && safeFilters.delivery_zone_name !== '') {
      if (!order.delivery_zone_name || !order.delivery_zone_name.toLowerCase().includes(safeFilters.delivery_zone_name.toLowerCase())) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'delivery_zone_name',
            actual: order.delivery_zone_name,
            expected: safeFilters.delivery_zone_name
          }
        });
        return false;
      }
    }

    // location_id - 取货地点（精确匹配）
    if (safeFilters.location_id !== undefined && safeFilters.location_id !== null) {
      if (String(order.location_id) !== String(safeFilters.location_id)) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'location_id',
            actual: order.location_id,
            expected: safeFilters.location_id
          }
        });
        return false;
      }
    }

    // shipping_order_number - 物流单号（模糊匹配）
    if (safeFilters.shipping_order_number !== undefined && safeFilters.shipping_order_number !== null && safeFilters.shipping_order_number !== '') {
      if (!order.shipping_order_number || !order.shipping_order_number.toLowerCase().includes(safeFilters.shipping_order_number.toLowerCase())) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'shipping_order_number',
            actual: order.shipping_order_number,
            expected: safeFilters.shipping_order_number
          }
        });
        return false;
      }
    }

    // logistics_company_id - 物流公司
    if (safeFilters.logistics_company_id && safeFilters.logistics_company_id.length > 0) {
      if (!order.logistics_company_id) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'logistics_company_id',
            actual: order.logistics_company_id,
            expected: safeFilters.logistics_company_id
          }
        });
        return false;
      }
      var orderLogisticsId = String(order.logistics_company_id);
      var _hasMatch2 = safeFilters.logistics_company_id.some(function (id) {
        return String(id) === orderLogisticsId;
      });
      if (!_hasMatch2) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'logistics_company_id',
            actual: order.logistics_company_id,
            expected: safeFilters.logistics_company_id
          }
        });
        return false;
      }
    }

    // zip - 邮编（模糊匹配）
    if (safeFilters.zip !== undefined && safeFilters.zip !== null && safeFilters.zip !== '') {
      if (!order.zip || !order.zip.toLowerCase().includes(safeFilters.zip.toLowerCase())) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'zip',
            actual: order.zip,
            expected: safeFilters.zip
          }
        });
        return false;
      }
    }

    // business_code - 业务类型（精确匹配）
    if (safeFilters.business_code) {
      if (!order.business_code || order.business_code !== safeFilters.business_code) {
        rejected.push({
          order_id: order.order_id,
          order_number: order.order_number,
          reason: {
            field: 'business_code',
            actual: order.business_code,
            expected: safeFilters.business_code
          }
        });
        return false;
      }
    }

    // start_time / end_time - 创建时间范围
    if (safeFilters.start_time || safeFilters.end_time) {
      var isCreatedIsUndefined = order.created_at === undefined;
      // 统一用 dayjs 按本地时区解析，避免 new Date("YYYY-MM-DD") 被当作 UTC 0 点
      // 与含时分的本地时间字符串比较时产生时区错位
      var orderTime = order.created_at ? typeof order.created_at === 'number' ? order.created_at : dayjs(String(order.created_at)).valueOf() : 0;
      if (safeFilters.start_time && !isCreatedIsUndefined) {
        var startTs = dayjs(safeFilters.start_time).startOf('day').valueOf();
        if (orderTime < startTs) {
          rejected.push({
            order_id: order.order_id,
            order_number: order.order_number,
            reason: {
              field: 'start_time',
              actual: order.created_at,
              expected: safeFilters.start_time
            }
          });
          return false;
        }
      }
      if (safeFilters.end_time && !isCreatedIsUndefined) {
        var endTs = dayjs(safeFilters.end_time).endOf('day').valueOf();
        if (orderTime > endTs) {
          rejected.push({
            order_id: order.order_id,
            order_number: order.order_number,
            reason: {
              field: 'end_time',
              actual: order.created_at,
              expected: safeFilters.end_time
            }
          });
          return false;
        }
      }
    }
    return true;
  });

  // 2. 排序
  if (safeFilters.order_by) {
    var sortField = safeFilters.order_by;
    var sortOrder = safeFilters.sort || 'desc';
    filteredList.sort(function (a, b) {
      var aVal;
      var bVal;
      switch (sortField) {
        case 'created_at':
          aVal = a.created_at ? typeof a.created_at === 'number' ? a.created_at : new Date(String(a.created_at)).getTime() : 0;
          bVal = b.created_at ? typeof b.created_at === 'number' ? b.created_at : new Date(String(b.created_at)).getTime() : 0;
          break;
        case 'updated_at':
          aVal = a.updated_at ? typeof a.updated_at === 'number' ? a.updated_at : new Date(String(a.updated_at)).getTime() : 0;
          bVal = b.updated_at ? typeof b.updated_at === 'number' ? b.updated_at : new Date(String(b.updated_at)).getTime() : 0;
          break;
        case 'total_amount':
          aVal = parseFloat(String(a.total_amount || 0));
          bVal = parseFloat(String(b.total_amount || 0));
          break;
        case 'customer_name':
          aVal = (a.customer_name || '').toLowerCase();
          bVal = (b.customer_name || '').toLowerCase();
          break;
        case 'amount_gap':
          return 0;
        default:
          return 0;
      }
      if (aVal < bVal) {
        return sortOrder === 'asc' ? -1 : 1;
      }
      if (aVal > bVal) {
        return sortOrder === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }

  // 3. 分页（skip 为页码，从 1 开始）
  var totalCount = filteredList.length;
  var startIndex = (page - 1) * size;
  var endIndex = startIndex + size;
  var paginatedList = filteredList.slice(startIndex, endIndex);
  return {
    list: paginatedList,
    count: totalCount,
    size: size,
    skip: page,
    rejected: rejected
  };
}