function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
import React, { useCallback, useMemo } from 'react';
import { PisellTags, PisellDateTimeDisplay } from '@pisell/materials';
import { locales } from '@pisell/utils';
import useEngineContext from "../../../hooks/useEngineContext";
import ClientName from "../../clientName";
import { FULFILLMENT_STATUS_COLOR_MAP, DELIVERY_TYPE_COLOR_MAP, getOrderHeaderLabels, getShippingStatusMap, ORDER_STATUS_COLOR_MAP, SHOP_SERVICE_TYPE_COLOR_MAP, getOrderStatusMap, PAYMENT_STATUS_COLOR_MAP, getPaymentStatusMap, getPlatformMap, getDeliveryTypeMap, getShopServiceTypeMap, getFilterButtonList, getSortList } from "../config/order";
import { getBusinessLabelMap, BUSINESS_COLOR_MAP } from "../config";
import { Tag, formatAmount, getDisplayLines, textStyles, formatPhone } from "./perspectiveUtils";
import BookingNotesPreview from "../components/BookingNotesPreview";
import { createNoteApis } from "../serve";
/**
 * 提取联系人原始对象，兼容 `{ value: {...} }`、对象本体、数组首项等结构。
 *
 * @example
 * const payload = pickContactPayload({ value: { first_name: 'Tom' } });
 * console.log(payload.first_name); // Tom
 */
function pickContactPayload(raw) {
  var first = Array.isArray(raw) ? raw[0] : raw;
  if (first !== null && first !== void 0 && first.value && _typeof(first.value) === 'object') {
    return first.value;
  }
  if (first && _typeof(first) === 'object') {
    return first;
  }
  return {};
}

/**
 * 订单行联系人字段归一化：优先 `value`，再回退 `contacts_info` / `contactsInfo`。
 *
 * @example
 * const info = resolveOrderContactInfo(record, record?.contacts_info);
 * console.log(info.displayName, info.phone, info.email);
 */
function resolveOrderContactInfo(record, contactValue) {
  var _contact$phone, _contact$phone2;
  var fromValue = pickContactPayload(contactValue);
  var fromSnake = pickContactPayload(record === null || record === void 0 ? void 0 : record.contacts_info);
  var fromCamel = pickContactPayload(record === null || record === void 0 ? void 0 : record.contactsInfo);
  var contact = Object.keys(fromValue).length ? fromValue : Object.keys(fromSnake).length ? fromSnake : fromCamel;
  var firstName = String((contact === null || contact === void 0 ? void 0 : contact.first_name) || '').trim();
  var lastName = String((contact === null || contact === void 0 ? void 0 : contact.last_name) || '').trim();
  var displayName = String((contact === null || contact === void 0 ? void 0 : contact.display_name) || "".concat(firstName, " ").concat(lastName)).trim();
  var phone = typeof (contact === null || contact === void 0 ? void 0 : contact.phone) === 'string' ? contact.phone : (contact === null || contact === void 0 || (_contact$phone = contact.phone) === null || _contact$phone === void 0 ? void 0 : _contact$phone.phone) || (contact === null || contact === void 0 || (_contact$phone2 = contact.phone) === null || _contact$phone2 === void 0 ? void 0 : _contact$phone2.value) || (contact === null || contact === void 0 ? void 0 : contact.mobile) || (contact === null || contact === void 0 ? void 0 : contact.phone_number) || '';
  var email = (contact === null || contact === void 0 ? void 0 : contact.email) || '';
  return {
    displayName: displayName,
    phone: phone,
    email: email
  };
}

/**
 * 订单行配送方式归一化：
 * - 店内服务优先读取 `metadata.shop_service_type.server_type`
 * - 其次读取 `delivery_type`
 * - 兼容 `shop_service_type` 扁平结构
 *
 * @example
 * const method = resolveShippingMethodDisplay(record, {
 *   shopServiceTypeLabelMap: SHOP_SERVICE_TYPE_LABEL_MAP,
 *   deliveryTypeLabelMap: DELIVERY_TYPE_LABEL_MAP,
 * });
 * console.log(method?.label);
 */
function resolveShippingMethodDisplay(record, maps) {
  var _record$metadata, _record$shop_service_, _maps$deliveryTypeLab;
  var deliveryType = (record === null || record === void 0 ? void 0 : record.delivery_type) || (record === null || record === void 0 ? void 0 : record.shipping_type) || (
  /**
   * 新结构兼容：部分 delivery 订单未下发 delivery_type，
   * 但会给 `type=delivery` / `business_code=delivery`。
   * 该场景按本地配送展示。
   *
   * @example
   * resolveShippingMethodDisplay({ type: 'delivery' }, maps)?.label
   */
  (record === null || record === void 0 ? void 0 : record.type) === 'delivery' || (record === null || record === void 0 ? void 0 : record.business_code) === 'delivery' ? 'local_delivery' : undefined);
  var serverType = (record === null || record === void 0 || (_record$metadata = record.metadata) === null || _record$metadata === void 0 || (_record$metadata = _record$metadata.shop_service_type) === null || _record$metadata === void 0 ? void 0 : _record$metadata.server_type) || (record === null || record === void 0 || (_record$shop_service_ = record.shop_service_type) === null || _record$shop_service_ === void 0 ? void 0 : _record$shop_service_.server_type) || (record === null || record === void 0 ? void 0 : record.shop_service_type);
  if (deliveryType === 'shop_service' || deliveryType == null && serverType) {
    var _maps$shopServiceType;
    var _label = (_maps$shopServiceType = maps.shopServiceTypeLabelMap) === null || _maps$shopServiceType === void 0 ? void 0 : _maps$shopServiceType[serverType];
    if (!_label) return null;
    return {
      label: _label,
      color: SHOP_SERVICE_TYPE_COLOR_MAP === null || SHOP_SERVICE_TYPE_COLOR_MAP === void 0 ? void 0 : SHOP_SERVICE_TYPE_COLOR_MAP[serverType]
    };
  }
  var label = (_maps$deliveryTypeLab = maps.deliveryTypeLabelMap) === null || _maps$deliveryTypeLab === void 0 ? void 0 : _maps$deliveryTypeLab[deliveryType];
  if (!label || deliveryType === 'nil') return null;
  return {
    label: label,
    color: DELIVERY_TYPE_COLOR_MAP === null || DELIVERY_TYPE_COLOR_MAP === void 0 ? void 0 : DELIVERY_TYPE_COLOR_MAP[deliveryType]
  };
}

/**
 * 解析订单商品数量，兼容顶层 / summary / products 明细三种来源。
 *
 * @example
 * const count = resolveOrderItemsCount({
 *   summary: { product_quantity: 1 },
 *   products: [{ product_quantity: 2 }],
 * });
 * console.log(count); // 1（优先 summary）
 */
function resolveOrderItemsCount(record) {
  var _record$summary;
  var topLevelCount = Number(record === null || record === void 0 ? void 0 : record.product_quantity);
  if (Number.isFinite(topLevelCount) && topLevelCount >= 0) {
    return topLevelCount;
  }
  var summaryCount = Number(record === null || record === void 0 || (_record$summary = record.summary) === null || _record$summary === void 0 ? void 0 : _record$summary.product_quantity);
  if (Number.isFinite(summaryCount) && summaryCount >= 0) {
    return summaryCount;
  }
  var products = Array.isArray(record === null || record === void 0 ? void 0 : record.products) ? record.products : [];
  if (products.length === 0) return 0;
  return products.reduce(function (sum, item) {
    var _ref, _item$product_quantit;
    var qty = Number((_ref = (_item$product_quantit = item === null || item === void 0 ? void 0 : item.product_quantity) !== null && _item$product_quantit !== void 0 ? _item$product_quantit : item === null || item === void 0 ? void 0 : item.quantity) !== null && _ref !== void 0 ? _ref : 0);
    if (!Number.isFinite(qty) || qty <= 0) return sum;
    return sum + qty;
  }, 0);
}

/**
 * 解析「Created by / Updated by」显示对象，兼容新旧订单结构。
 * - 旧结构优先：`create_account` / `last_edit_account`
 * - 新结构回退：`customer`
 * - 最后回退：`customer_name` + 电话/邮箱
 *
 * @example
 * const actor = resolveOrderActorDisplay({
 *   customer_name: '佳 贾',
 *   phone: '0425541521',
 *   country_calling_code: '61',
 * });
 * console.log(actor?.display_name); // 佳 贾
 */
function resolveOrderActorDisplay(record, preferredActor) {
  var candidate = preferredActor || (record === null || record === void 0 ? void 0 : record.last_edit_account) || (record === null || record === void 0 ? void 0 : record.create_account) || (record === null || record === void 0 ? void 0 : record.customer);
  if (candidate && _typeof(candidate) === 'object') {
    var displayName = String((candidate === null || candidate === void 0 ? void 0 : candidate.display_name) || (candidate === null || candidate === void 0 ? void 0 : candidate.customer_name) || [candidate === null || candidate === void 0 ? void 0 : candidate.first_name, candidate === null || candidate === void 0 ? void 0 : candidate.last_name].filter(Boolean).join(' ')).trim();
    if (displayName) {
      return _objectSpread(_objectSpread({}, candidate), {}, {
        display_name: displayName
      });
    }
  }
  if (record !== null && record !== void 0 && record.customer_name || record !== null && record !== void 0 && record.phone || record !== null && record !== void 0 && record.email) {
    return {
      display_name: (record === null || record === void 0 ? void 0 : record.customer_name) || '',
      phone: (record === null || record === void 0 ? void 0 : record.phone) || '',
      country_calling_code: (record === null || record === void 0 ? void 0 : record.country_calling_code) || '',
      email: (record === null || record === void 0 ? void 0 : record.email) || ''
    };
  }
  return null;
}
/**
 * 统一解析订单金额（兼容新结构 summary/payments 与旧结构顶层金额字段）。
 *
 * @example
 * const amounts = resolveOrderPaymentAmounts({
 *   summary: { total_amount: '23.28' },
 *   payments: [{ status: 'paid', amount: '6.07' }],
 * });
 * console.log(amounts.totalAmount, amounts.paidAmount, amounts.dueAmount);
 */
function resolveOrderPaymentAmounts(record) {
  var _record$summary2, _record$summary3;
  var summaryTotal = Number(record === null || record === void 0 || (_record$summary2 = record.summary) === null || _record$summary2 === void 0 ? void 0 : _record$summary2.total_amount);
  var topLevelTotal = Number(record === null || record === void 0 ? void 0 : record.total_amount);
  var totalAmount = Number.isFinite(summaryTotal) ? summaryTotal : Number.isFinite(topLevelTotal) ? topLevelTotal : 0;
  var topLevelPaid = Number(record === null || record === void 0 ? void 0 : record.paid_amount);
  var topLevelRefunded = Number((record === null || record === void 0 ? void 0 : record.total_refund_amount) || (record === null || record === void 0 || (_record$summary3 = record.summary) === null || _record$summary3 === void 0 ? void 0 : _record$summary3.total_refund_amount) || 0);
  var payments = Array.isArray(record === null || record === void 0 ? void 0 : record.payments) ? record.payments : [];
  var paidFromPayments = payments.reduce(function (sum, item) {
    var _ref2, _item$amount;
    var status = String((item === null || item === void 0 ? void 0 : item.status) || '').toLowerCase();
    if (!['paid', 'captured', 'success', 'completed'].includes(status)) {
      return sum;
    }
    var amount = Number((_ref2 = (_item$amount = item === null || item === void 0 ? void 0 : item.amount) !== null && _item$amount !== void 0 ? _item$amount : item === null || item === void 0 ? void 0 : item.origin_amount) !== null && _ref2 !== void 0 ? _ref2 : 0);
    if (!Number.isFinite(amount) || amount <= 0) return sum;
    return sum + amount;
  }, 0);
  var refundedFromPayments = payments.reduce(function (sum, item) {
    var _ref3, _item$amount2;
    var status = String((item === null || item === void 0 ? void 0 : item.status) || '').toLowerCase();
    if (!['refunded', 'partially_refunded', 'refund'].includes(status)) {
      return sum;
    }
    var amount = Number((_ref3 = (_item$amount2 = item === null || item === void 0 ? void 0 : item.amount) !== null && _item$amount2 !== void 0 ? _item$amount2 : item === null || item === void 0 ? void 0 : item.origin_amount) !== null && _ref3 !== void 0 ? _ref3 : 0);
    if (!Number.isFinite(amount) || amount <= 0) return sum;
    return sum + amount;
  }, 0);
  var paidAmount = Number.isFinite(topLevelPaid) ? topLevelPaid : paidFromPayments;
  var refundedAmount = Number.isFinite(topLevelRefunded) ? topLevelRefunded : refundedFromPayments;
  var dueAmount = Math.max(totalAmount - paidAmount, 0);
  return {
    totalAmount: totalAmount,
    paidAmount: paidAmount,
    refundedAmount: refundedAmount,
    dueAmount: dueAmount
  };
}
export var useOrderPerspective = function useOrderPerspective() {
  var _context$appHelper, _context$appHelper2, _context$appHelper2$g, _context$appHelper3, _context$engine;
  var context = useEngineContext();
  var utils = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
  var app = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getApp) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2);
  var NativePage = context === null || context === void 0 || (_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 || (_context$appHelper3 = _context$appHelper3.utils) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.NativePage;
  /** 监听 locale，切换语言时重新计算 label/filter/sort 等文案 */
  var locale = context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale;

  /**
   * 静态部分：label maps 等只需计算一次的数据。
   */
  var staticData = useMemo(function () {
    var PAYMENT_STATUS_LABEL_MAP = getPaymentStatusMap();
    var PLATFORM_LABEL_MAP = getPlatformMap();
    var ORDER_STATUS_LABEL_MAP = getOrderStatusMap();
    var SHIPPING_STATUS_LABEL_MAP = getShippingStatusMap();
    var DELIVERY_TYPE_LABEL_MAP = getDeliveryTypeMap();
    var SHOP_SERVICE_TYPE_LABEL_MAP = getShopServiceTypeMap();
    var BUSINESS_LABEL_MAP = getBusinessLabelMap();
    var orderLabels = getOrderHeaderLabels();
    var amountLabels = {
      total: locales.getText('pisell2.orderList.common.totalAmount'),
      paid: locales.getText('pisell2.orderList.common.paidAmount'),
      due: locales.getText('pisell2.orderList.common.dueAmount'),
      refunded: locales.getText('pisell2.orderList.common.refundedAmount'),
      items: locales.getText('pisell2.orderList.common.itemsCount')
    };
    return {
      PAYMENT_STATUS_LABEL_MAP: PAYMENT_STATUS_LABEL_MAP,
      PLATFORM_LABEL_MAP: PLATFORM_LABEL_MAP,
      ORDER_STATUS_LABEL_MAP: ORDER_STATUS_LABEL_MAP,
      SHIPPING_STATUS_LABEL_MAP: SHIPPING_STATUS_LABEL_MAP,
      DELIVERY_TYPE_LABEL_MAP: DELIVERY_TYPE_LABEL_MAP,
      SHOP_SERVICE_TYPE_LABEL_MAP: SHOP_SERVICE_TYPE_LABEL_MAP,
      BUSINESS_LABEL_MAP: BUSINESS_LABEL_MAP,
      orderLabels: orderLabels,
      amountLabels: amountLabels
    };
  }, [locale]);

  /**
   * 构建 columns 的工厂：接收 runtimeContext，使列渲染可访问 refresh 等运行时能力。
   */
  var buildColumns = useCallback(function (ctx) {
    var PAYMENT_STATUS_LABEL_MAP = staticData.PAYMENT_STATUS_LABEL_MAP,
      PLATFORM_LABEL_MAP = staticData.PLATFORM_LABEL_MAP,
      ORDER_STATUS_LABEL_MAP = staticData.ORDER_STATUS_LABEL_MAP,
      SHIPPING_STATUS_LABEL_MAP = staticData.SHIPPING_STATUS_LABEL_MAP,
      DELIVERY_TYPE_LABEL_MAP = staticData.DELIVERY_TYPE_LABEL_MAP,
      SHOP_SERVICE_TYPE_LABEL_MAP = staticData.SHOP_SERVICE_TYPE_LABEL_MAP,
      BUSINESS_LABEL_MAP = staticData.BUSINESS_LABEL_MAP,
      orderLabels = staticData.orderLabels,
      amountLabels = staticData.amountLabels;
    return [{
      title: orderLabels.saleBrief,
      key: 'sale_brief',
      width: 225,
      // fixed: 'left',
      render: function render(_, record) {
        var orderCode = record === null || record === void 0 ? void 0 : record.shop_full_order_number;
        var currencySymbol = record === null || record === void 0 ? void 0 : record.currency_symbol;
        var _resolveOrderPaymentA = resolveOrderPaymentAmounts(record),
          totalAmount = _resolveOrderPaymentA.totalAmount;
        var paymentStatus = record === null || record === void 0 ? void 0 : record.payment_status;
        var orderNote = record === null || record === void 0 ? void 0 : record.note;
        var internalNotes = record === null || record === void 0 ? void 0 : record.internal_note;
        var noteApis = createNoteApis((record === null || record === void 0 ? void 0 : record.id) || (record === null || record === void 0 ? void 0 : record.order_id) || (record === null || record === void 0 ? void 0 : record.orderId));
        var tags = (record === null || record === void 0 ? void 0 : record.tag) || (record === null || record === void 0 ? void 0 : record.tags) || [];
        var paymentLabel = PAYMENT_STATUS_LABEL_MAP[paymentStatus] || paymentStatus || '-';
        var paymentColor = PAYMENT_STATUS_COLOR_MAP[paymentStatus] || '';
        return /*#__PURE__*/React.createElement("div", {
          className: "pisell-sales-grid-sale-brief",
          style: {
            display: 'flex',
            flexDirection: 'column'
          }
        }, /*#__PURE__*/React.createElement("div", {
          style: {
            fontWeight: 'bold',
            textDecoration: 'underline',
            color: 'var(--theme-color, #7f56d9)'
          }
        }, orderCode), Array.isArray(tags) && tags.length > 0 ? /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'flex',
            gap: 4,
            flexWrap: 'wrap'
          }
        }, tags.map(function (item) {
          return /*#__PURE__*/React.createElement(Tag, {
            key: "".concat(item === null || item === void 0 ? void 0 : item.id),
            style: {
              margin: 0,
              maxWidth: 160,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              fontWeight: 500
            }
          }, item === null || item === void 0 ? void 0 : item.name);
        })) : null, /*#__PURE__*/React.createElement("div", {
          style: {
            fontWeight: 'bold'
          }
        }, /*#__PURE__*/React.createElement("span", {
          style: {
            marginRight: 6
          }
        }, amountLabels.total, ":"), /*#__PURE__*/React.createElement("span", null, formatAmount(totalAmount, currencySymbol))), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Tag, {
          style: {
            backgroundColor: paymentColor,
            whiteSpace: 'nowrap',
            border: 'none',
            fontWeight: 500
          }
        }, paymentLabel)), /*#__PURE__*/React.createElement(BookingNotesPreview, {
          dataSource: {
            note: orderNote,
            internalNotes: internalNotes,
            apis: noteApis,
            onChange: function onChange(value, type, noteType) {
              ctx.refresh();
            }
          },
          labels: {
            orderNote: orderLabels.orderNote,
            internalNote: orderLabels.internalNote
          },
          style: {
            maxWidth: '100%'
          }
        }));
      }
    }, {
      title: orderLabels.customer,
      key: 'customer',
      align: 'center',
      width: 150,
      uniformCompare: function uniformCompare(value, record) {
        var customer = record === null || record === void 0 ? void 0 : record.customer;
        if (!customer) return '-';
        var guestCode = customer === null || customer === void 0 ? void 0 : customer.guest_code;
        if (guestCode) return "".concat(guestCode);
        if (customer.user_id === 1) return 'walk-in'; // 返回任意固定值即可
        return customer;
      },
      render: function render(_, record) {
        var customer = record === null || record === void 0 ? void 0 : record.customer;
        if (!customer) return '-';
        var guestCode = customer === null || customer === void 0 ? void 0 : customer.guest_code;
        if (guestCode) {
          return /*#__PURE__*/React.createElement("div", {
            className: "pisell-sales-grid-person-cell"
          }, /*#__PURE__*/React.createElement("div", {
            style: {
              fontWeight: 'bold'
            }
          }, orderLabels.guest));
        }
        var phone = formatPhone((customer === null || customer === void 0 ? void 0 : customer.phone) || (record === null || record === void 0 ? void 0 : record.phone), (customer === null || customer === void 0 ? void 0 : customer.country_calling_code) || (record === null || record === void 0 ? void 0 : record.country_calling_code));
        var lines = getDisplayLines([phone, customer === null || customer === void 0 ? void 0 : customer.email]);
        return /*#__PURE__*/React.createElement("div", {
          className: "pisell-sales-grid-person-cell"
        }, /*#__PURE__*/React.createElement(ClientName, {
          dataSource: customer,
          style: {
            fontSize: 14
          }
        }), lines.map(function (line, index) {
          return /*#__PURE__*/React.createElement("div", {
            key: "".concat(line, "-").concat(index),
            style: textStyles.text
          }, line);
        }));
      }
    }, {
      title: orderLabels.contact,
      dataIndex: 'contacts_info',
      key: 'contacts_info',
      align: 'center',
      width: 150,
      uniformCompare: function uniformCompare(value, record) {
        if (!value) return '-';
        return value;
      },
      render: function render(value, record) {
        var info = resolveOrderContactInfo(record, value);
        if (!(info !== null && info !== void 0 && info.displayName) && !(info !== null && info !== void 0 && info.phone) && !(info !== null && info !== void 0 && info.email)) return '-';
        var phone = formatPhone(info === null || info === void 0 ? void 0 : info.phone);
        var lines = getDisplayLines([phone, info === null || info === void 0 ? void 0 : info.email]);
        return /*#__PURE__*/React.createElement("div", {
          className: "pisell-sales-grid-person-cell"
        }, /*#__PURE__*/React.createElement(ClientName, {
          dataSource: {
            display_name: info === null || info === void 0 ? void 0 : info.displayName
          },
          style: {
            fontSize: 14
          }
        }), lines.map(function (line, index) {
          return /*#__PURE__*/React.createElement("div", {
            key: "".concat(line, "-").concat(index),
            style: textStyles.text
          }, line);
        }));
      }
    }, {
      title: orderLabels.paymentInfo,
      key: 'payment_info',
      width: 124,
      align: 'center',
      render: function render(_, record) {
        var value = record === null || record === void 0 ? void 0 : record.payment_status;
        var currencySymbol = record === null || record === void 0 ? void 0 : record.currency_symbol;
        var _resolveOrderPaymentA2 = resolveOrderPaymentAmounts(record),
          totalAmount = _resolveOrderPaymentA2.totalAmount,
          paidAmount = _resolveOrderPaymentA2.paidAmount,
          refundedAmount = _resolveOrderPaymentA2.refundedAmount,
          dueAmount = _resolveOrderPaymentA2.dueAmount;
        var amountStyles = {
          due: {
            fontWeight: 'bold',
            color: '#D92D20'
          },
          refunded: {
            color: '#CA8504',
            fontWeight: 'bold'
          }
        };
        var lines = [];
        if (['payment_processing', 'unpaid', 'partially_paid'].includes(value)) {
          lines.push({
            label: amountLabels.due,
            value: formatAmount(dueAmount, currencySymbol),
            bold: true,
            kind: 'due'
          });
          lines.push({
            label: amountLabels.total,
            value: formatAmount(totalAmount, currencySymbol),
            kind: 'total'
          });
        } else if (value === 'paid') {
          lines.push({
            label: amountLabels.paid,
            value: formatAmount(paidAmount, currencySymbol),
            bold: true,
            kind: 'paid'
          });
          lines.push({
            label: amountLabels.total,
            value: formatAmount(totalAmount, currencySymbol),
            kind: 'total'
          });
        } else if (['partially_refunded', 'refunded'].includes(value)) {
          lines.push({
            label: amountLabels.refunded,
            value: formatAmount(refundedAmount, currencySymbol),
            bold: true,
            kind: 'refunded'
          });
          lines.push({
            label: amountLabels.paid,
            value: formatAmount(paidAmount, currencySymbol),
            kind: 'paid'
          });
          lines.push({
            label: amountLabels.total,
            value: formatAmount(totalAmount, currencySymbol),
            kind: 'total'
          });
        } else if (['voided', 'authorized'].includes(value)) {
          lines.push({
            label: amountLabels.total,
            value: formatAmount(totalAmount, currencySymbol),
            bold: true,
            kind: 'total'
          });
        } else {
          lines.push({
            label: amountLabels.total,
            value: formatAmount(totalAmount, currencySymbol),
            bold: true,
            kind: 'total'
          });
        }
        return /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'flex',
            flexDirection: 'column',
            gap: 4,
            alignItems: 'flex-start'
          }
        }, lines.map(function (line) {
          return /*#__PURE__*/React.createElement("div", {
            key: line.label,
            style: textStyles.text
          }, /*#__PURE__*/React.createElement("span", {
            style: _objectSpread({
              whiteSpace: 'nowrap'
            }, line.kind && amountStyles[line.kind] ? amountStyles[line.kind] : {})
          }, line.label, ": ", line.value));
        }));
      }
    }, {
      title: orderLabels.items,
      key: 'product_quantity',
      align: 'center',
      width: 120,
      render: function render(_, record) {
        var count = resolveOrderItemsCount(record);
        return /*#__PURE__*/React.createElement("span", {
          style: _objectSpread(_objectSpread({}, textStyles.text), {}, {
            textAlign: 'center'
          })
        }, count, amountLabels.items);
      }
    }, {
      title: orderLabels.orderOrigin,
      key: 'order_origin',
      width: 138,
      align: 'center',
      render: function render(_, record) {
        var channel = PLATFORM_LABEL_MAP[record === null || record === void 0 ? void 0 : record.order_sales_channel] || PLATFORM_LABEL_MAP[record === null || record === void 0 ? void 0 : record.order_platform] || (record === null || record === void 0 ? void 0 : record.order_sales_channel) || (record === null || record === void 0 ? void 0 : record.order_platform);
        var device = (record === null || record === void 0 ? void 0 : record.device_name) || (record === null || record === void 0 ? void 0 : record.device) || (record === null || record === void 0 ? void 0 : record.terminal);
        var time = (record === null || record === void 0 ? void 0 : record.created_at) || (record === null || record === void 0 ? void 0 : record.order_time);
        var actor = resolveOrderActorDisplay(record, record === null || record === void 0 ? void 0 : record.create_account);
        var lines = getDisplayLines([channel, device]);
        if (lines.length === 0) {
          return null;
        }
        var businessLabel = BUSINESS_LABEL_MAP[record.business_code];
        return /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-start'
          }
        }, businessLabel ? /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Tag, {
          color: BUSINESS_COLOR_MAP[record.business_code],
          style: {
            color: 'black',
            fontWeight: 500
          }
        }, businessLabel)) : null, lines.map(function (line, index) {
          return /*#__PURE__*/React.createElement("div", {
            key: "".concat(line, "-").concat(index),
            style: textStyles.text
          }, line);
        }), /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'flex',
            alignItems: 'center',
            whiteSpace: 'nowrap'
          }
        }, /*#__PURE__*/React.createElement("span", null, orderLabels.createdBy, ":"), actor ? /*#__PURE__*/React.createElement(ClientName, {
          dataSource: actor,
          style: {
            fontSize: 14
          }
        }) : /*#__PURE__*/React.createElement("span", {
          style: _objectSpread(_objectSpread({}, textStyles.text), {}, {
            marginLeft: 4
          })
        }, "-")), /*#__PURE__*/React.createElement(PisellDateTimeDisplay, {
          value: time,
          layout: "inline",
          textAlign: "left",
          timeFormat: {
            padHour: true
          },
          dateFormat: {
            showYear: false,
            shortMonth: true,
            showRelativeDay: true,
            useCommaBeforeYear: false
          },
          fields: {
            fieldOrder: ['time', 'weekday', 'date']
            // inlineSeparators: [' ', ', '],
          },
          style: {
            whiteSpace: 'nowrap'
          }
        }));
      }
    }, {
      title: orderLabels.paymentStatus,
      dataIndex: 'payment_status',
      key: 'payment_status',
      align: 'center',
      width: 160,
      render: function render(value) {
        var key = value === 'partially_paid' ? 'unpaid' : value;
        var label = PAYMENT_STATUS_LABEL_MAP[key] || value || '-';
        var color = PAYMENT_STATUS_COLOR_MAP[key] || '';
        return /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'center'
          }
        }, /*#__PURE__*/React.createElement(PisellTags, {
          style: {
            backgroundColor: color,
            whiteSpace: 'nowrap'
          }
        }, label));
      }
    }, {
      title: orderLabels.shippingMethod,
      key: 'delivery_type',
      align: 'center',
      width: 160,
      render: function render(_, record) {
        var method = resolveShippingMethodDisplay(record, {
          shopServiceTypeLabelMap: SHOP_SERVICE_TYPE_LABEL_MAP,
          deliveryTypeLabelMap: DELIVERY_TYPE_LABEL_MAP
        });
        if (!method) return '-';
        return /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'center'
          }
        }, /*#__PURE__*/React.createElement(Tag, {
          style: {
            whiteSpace: 'nowrap',
            fontWeight: 500
          },
          color: method.color
        }, method.label));
      },
      uniformCompare: function uniformCompare(_, record) {
        var _record$metadata2;
        var deliveryType = (record === null || record === void 0 ? void 0 : record.delivery_type) || '';
        var serverType = (record === null || record === void 0 || (_record$metadata2 = record.metadata) === null || _record$metadata2 === void 0 || (_record$metadata2 = _record$metadata2.shop_service_type) === null || _record$metadata2 === void 0 ? void 0 : _record$metadata2.server_type) || '';
        return "".concat(deliveryType, "|").concat(serverType);
      }
    }, {
      title: orderLabels.orderStatus,
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 150,
      render: function render(value) {
        var color = ORDER_STATUS_COLOR_MAP[value];
        var label = ORDER_STATUS_LABEL_MAP[value] || value || '-';
        return /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'center'
          }
        }, /*#__PURE__*/React.createElement(PisellTags, {
          style: {
            whiteSpace: 'nowrap',
            borderColor: color === null || color === void 0 ? void 0 : color.borderColor,
            color: color === null || color === void 0 ? void 0 : color.textColor
          }
        }, label));
      }
    }, {
      title: orderLabels.fulfillmentStatus,
      dataIndex: 'shipping_status',
      key: 'shipping_status',
      align: 'center',
      width: 160,
      render: function render(value) {
        var color = FULFILLMENT_STATUS_COLOR_MAP[value];
        var label = SHIPPING_STATUS_LABEL_MAP[value] || value || '-';
        return /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'center'
          }
        }, /*#__PURE__*/React.createElement(PisellTags, {
          style: {
            whiteSpace: 'nowrap',
            borderColor: color === null || color === void 0 ? void 0 : color.borderColor,
            color: color === null || color === void 0 ? void 0 : color.textColor
          }
        }, label));
      }
    }, {
      title: orderLabels.updated,
      key: 'last_edit_account',
      width: 132,
      align: 'center',
      render: function render(_, record) {
        var _record$last_edit_acc;
        var editor = resolveOrderActorDisplay(record, record === null || record === void 0 ? void 0 : record.last_edit_account);
        var time = (record === null || record === void 0 || (_record$last_edit_acc = record.last_edit_account) === null || _record$last_edit_acc === void 0 ? void 0 : _record$last_edit_acc.created_at) || (editor === null || editor === void 0 ? void 0 : editor.updated_at) || (record === null || record === void 0 ? void 0 : record.updated_at);
        var channel = PLATFORM_LABEL_MAP[record === null || record === void 0 ? void 0 : record.order_platform] || (record === null || record === void 0 ? void 0 : record.order_platform);
        var lines = getDisplayLines([channel]);
        return /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-start'
          }
        }, editor ? /*#__PURE__*/React.createElement(ClientName, {
          dataSource: editor,
          style: {
            fontSize: 14
          }
        }) : /*#__PURE__*/React.createElement("div", {
          style: _objectSpread({}, textStyles.text)
        }, "-"), /*#__PURE__*/React.createElement(PisellDateTimeDisplay, {
          value: time,
          layout: "inline",
          textAlign: "left",
          timeFormat: {
            padHour: true
          },
          dateFormat: {
            showYear: false,
            shortMonth: true,
            showRelativeDay: true,
            useCommaBeforeYear: false
          },
          fields: {
            fieldOrder: ['time', 'weekday', 'date']
            // inlineSeparators: [' ', ', '],
          },
          style: {
            whiteSpace: 'nowrap'
          }
        }), lines.map(function (line, index) {
          return /*#__PURE__*/React.createElement("div", {
            key: "".concat(line, "-").concat(index),
            style: textStyles.text
          }, line);
        }));
      }
    }, {
      title: orderLabels.orderId,
      dataIndex: 'order_id',
      key: 'order_id',
      align: 'center',
      width: 100,
      /**
       * Order ID 显示兼容：
       * - osServer 本地订单主键优先 `order_id`
       * - 兼容历史字段 `orderId`
       * - 最后回退 `id`
       *
       * @example
       * // record = { order_id: 1001 } => 1001
       * // record = { orderId: 1002 } => 1002
       * // record = { id: 1003 } => 1003
       */
      render: function render(_value, record) {
        // const orderId = record?.order_id ?? record?.orderId ?? record?.id;
        var orderId = record === null || record === void 0 ? void 0 : record.shop_order_number;
        return /*#__PURE__*/React.createElement("span", {
          style: _objectSpread(_objectSpread({}, textStyles.text), {}, {
            textAlign: 'center'
          })
        }, orderId);
      }
    }];
  }, [staticData]);

  /**
   * 最终 perspective 配置：
   * 使用 getChildComponentProps 工厂函数，使 onRow、columns 等可访问运行时上下文。
   */
  var _perspective = useMemo(function () {
    return {
      key: 'handle',
      label: 'Handle',
      getChildComponentProps: function getChildComponentProps(ctx) {
        return {
          grid: {
            bordered: true,
            collapseUniformColumns: true,
            columns: buildColumns(ctx),
            defaultHiddenColumnKeys: ['order_origin', 'payment_status', 'delivery_type', 'status', 'shipping_status', 'last_edit_account', 'id'],
            scroll: {
              x: 'max-content',
              autoCalc: true,
              scrollToFirstRowOnChange: true
            },
            rowSelection: {
              fixed: true,
              columnWidth: 48
            },
            onRow: function onRow(record) {
              return {
                onClick: function onClick() {
                  var _ref4, _record$order_id, _app$history, _app$history2;
                  var orderId = (_ref4 = (_record$order_id = record === null || record === void 0 ? void 0 : record.order_id) !== null && _record$order_id !== void 0 ? _record$order_id : record === null || record === void 0 ? void 0 : record.orderId) !== null && _ref4 !== void 0 ? _ref4 : record === null || record === void 0 ? void 0 : record.id;

                  // handleOpenSaleDetail
                  utils === null || utils === void 0 || utils.action({
                    type: 'pisell1.handleOpenSaleDetail',
                    data: {
                      osProps: {
                        orderId: orderId,
                        osKey: 'sales-management-item-detail'
                      }
                    }
                  });
                  return;
                  var nativePage = NativePage === null || NativePage === void 0 ? void 0 : NativePage();
                  if (nativePage !== null && nativePage !== void 0 && nativePage.open && orderId != null) {
                    nativePage.open({
                      page: '/native/order/detail',
                      params: {
                        order_id: orderId
                      }
                    });
                    return;
                  }
                  var pathname = encodeURIComponent((app === null || app === void 0 || (_app$history = app.history) === null || _app$history === void 0 || (_app$history = _app$history.instance) === null || _app$history === void 0 || (_app$history = _app$history.location) === null || _app$history === void 0 ? void 0 : _app$history.pathname) || '');
                  app === null || app === void 0 || (_app$history2 = app.history) === null || _app$history2 === void 0 || _app$history2.push("/order-detail?id=".concat(record.id, "&goback=").concat(pathname));
                }
              };
            }
          },
          toolBar: {
            search: {
              showConfirmButton: false
            },
            sort: {
              list: getSortList()
            },
            quickFilter: {
              filterList: [{
                type: 'rangePicker',
                name: 'orderDate',
                key: 'orderDate',
                props: {
                  placeholder: locales.getText('pisell2.orderList.quickFilter.orderDate.placeholder')
                }
              }]
            },
            filter: {
              hiddenQuickFilter: true,
              defaultFilterValue: {
                quickFilter: [],
                otherFilter: getFilterButtonList(),
                values: {}
              }
            }
          },
          batchActionBar: {
            overflowThreshold: 2,
            defaultActions: {
              showSelectAll: false,
              showClear: false,
              showInvert: false,
              showDelete: false
            }
          }
        };
      }
    };
  }, [buildColumns, app, locale, NativePage]);
  return _perspective;
};