import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
//#region src/plus/salesSdk/demo/components/buildSteps.ts
/** 选客户：fixture.customerId 优先；缺省 = customer.list[0] */
function pickCustomer(_x, _x2) {
	return _pickCustomer.apply(this, arguments);
}
function _pickCustomer() {
	_pickCustomer = _asyncToGenerator(function* (deps, customerId) {
		var _resp$list$, _resp$list3;
		if (customerId != null) {
			var _ref, _resp$list$find, _resp$list, _resp$list2;
			const found = deps.customer.loadById(customerId);
			if (found) return found;
			const resp = yield deps.customer.loadList({ search: String(customerId) });
			return (_ref = (_resp$list$find = (_resp$list = resp.list) === null || _resp$list === void 0 ? void 0 : _resp$list.find((c) => String(c.id) === String(customerId))) !== null && _resp$list$find !== void 0 ? _resp$list$find : (_resp$list2 = resp.list) === null || _resp$list2 === void 0 ? void 0 : _resp$list2[0]) !== null && _ref !== void 0 ? _ref : null;
		}
		return (_resp$list$ = (_resp$list3 = (yield deps.customer.loadList()).list) === null || _resp$list3 === void 0 ? void 0 : _resp$list3[0]) !== null && _resp$list$ !== void 0 ? _resp$list$ : null;
	});
	return _pickCustomer.apply(this, arguments);
}
/**
* 从 catalog 挑一行 `ProductData`（`cart.addProduct` 入参）。
* fixture：productPicker.productId → 缺省取第一条
*/
function pickCatalogProduct(products, picker) {
	var _products$;
	if (!Array.isArray(products) || products.length === 0) return null;
	if (picker.productId) {
		var _products$find;
		return (_products$find = products.find((p) => p.id === picker.productId)) !== null && _products$find !== void 0 ? _products$find : null;
	}
	return (_products$ = products[0]) !== null && _products$ !== void 0 ? _products$ : null;
}
/** 真接口 submit 二次确认 */
function confirmSubmit() {
	if (typeof window === "undefined") return false;
	return window.confirm("一键测试将调用真实 submit API，确认继续？");
}
/**
* 共用业务步骤：
*  - loadCustomers
*  - selectCustomer
*  - loadProducts
*  - addProduct
*  - recalcSummary
*  - submit（含二次确认）
*
* 调用方在前面追加 `createNew`（新建）或 `loadDetail`（编辑）作为第一步即可。
*/
function buildMutableSteps(deps, fixture) {
	/**
	* 通过闭包内 ref 把「上一步挑出的客户 / 商品 / 拉到的商品列表」带给后面的步骤。
	*
	* 为什么 products 也要 carry：useMemo 闭包捕获的是 `deps.products.products` 在 build
	* 时刻的快照，串行执行中即便 `products.load` 触发 setProducts，runAll 已捕获旧 steps
	* 数组，下一步的 `cart.addProduct` 仍读旧快照（空数组）。所以 load 步骤把返回的 list
	* 写到 carry，addProduct 优先读 carry，回退才到 React state。
	*/
	const carry = {
		customer: null,
		product: null,
		products: []
	};
	return [
		{
			id: "customer.loadList",
			label: "customer.loadList",
			description: "从服务端拉默认一页客户列表",
			run: function() {
				var _ref2 = _asyncToGenerator(function* () {
					return deps.customer.loadList();
				});
				return function run() {
					return _ref2.apply(this, arguments);
				};
			}()
		},
		{
			id: "customer.select",
			label: "customer.select",
			description: fixture.customerId ? `按 customerId=${fixture.customerId} 选客户` : "默认选 customer.list[0]",
			run: function() {
				var _ref3 = _asyncToGenerator(function* () {
					const picked = yield pickCustomer(deps, fixture.customerId);
					if (!picked) throw new Error("未找到可选客户，请检查 customerId 或客户列表");
					deps.customer.select(picked);
					carry.customer = picked;
					return picked;
				});
				return function run() {
					return _ref3.apply(this, arguments);
				};
			}()
		},
		{
			id: "products.load",
			label: "products.load",
			description: "loadProducts(fixture.loadProductsParams)",
			run: function() {
				var _ref4 = _asyncToGenerator(function* () {
					console.log(_objectSpread2(_objectSpread2({}, fixture.loadProductsParams), {}, { menu_list_ids: [43775] }), "fixture.loadProductsParams123");
					const list = yield deps.products.load(_objectSpread2(_objectSpread2({}, fixture.loadProductsParams), {}, { menu_list_ids: [43775] }));
					carry.products = Array.isArray(list) ? list : [];
					return list;
				});
				return function run() {
					return _ref4.apply(this, arguments);
				};
			}()
		},
		{
			id: "cart.addProductWithFlow",
			label: "cart.addProductWithFlow",
			description: "加车编排：OS 决策 → legacy Info2 弹窗 (pisell1.handleOpenProductModal) → confirmDetail → 写入 tempOrder",
			run: function() {
				var _ref5 = _asyncToGenerator(function* () {
					var _fixture$productPicke;
					const product = pickCatalogProduct(carry.products.length > 0 ? carry.products : deps.products.products, _objectSpread2(_objectSpread2({}, fixture.productPicker), {}, { productId: 6e4 }));
					if (!product) throw new Error("未找到可加车商品：请确认 products.load 已成功且 catalog 不为空");
					carry.product = product;
					const quantity = (_fixture$productPicke = fixture.productPicker.num) !== null && _fixture$productPicke !== void 0 ? _fixture$productPicke : 1;
					const result = yield deps.cart.addProductWithFlow(product, { quantity });
					if (result.status === "cancelled") throw new Error("加车流程已取消（可能为规格弹窗、跨日日期、Holder 或资源抽屉中取消）");
					if (result.status === "requiresDetail") throw new Error("命中 requiresDetail 但未配置 uiHosts.openProductDetail（请使用 SalesSdkDemoTabShell）");
					if (result.status === "requiresBookingEdit") throw new Error("命中 requiresBookingEdit 但未配置 uiHosts.openBookingEdit（请使用 SalesSdkDemoTabShell）");
					return result;
				});
				return function run() {
					return _ref5.apply(this, arguments);
				};
			}()
		},
		{
			id: "cart.recalcSummary",
			label: "cart.recalcSummary",
			description: "触发 summary 重算",
			run: function() {
				var _ref6 = _asyncToGenerator(function* () {
					return deps.cart.recalcSummary();
				});
				return function run() {
					return _ref6.apply(this, arguments);
				};
			}()
		},
		{
			id: "cart.submit",
			label: "cart.submit",
			description: "调真实 OS submit API（执行前会弹确认框）",
			run: function() {
				var _ref7 = _asyncToGenerator(function* () {
					if (!confirmSubmit()) throw new Error("用户取消 submit");
					return deps.cart.submit();
				});
				return function run() {
					return _ref7.apply(this, arguments);
				};
			}()
		}
	];
}
/** 新建 Tab：第一步走 sales.createNew，其余复用 mutable 步骤 */
function buildCreateSteps(deps, fixture) {
	return [{
		id: "sales.createNew",
		label: "sales.createNew",
		description: "创建一个新的 tempOrder",
		run: function() {
			var _ref8 = _asyncToGenerator(function* () {
				return deps.sales.createNew();
			});
			return function run() {
				return _ref8.apply(this, arguments);
			};
		}()
	}, ...buildMutableSteps(deps, fixture)];
}
/**
* 编辑 Tab 专用：loadDetail 之后写入 tempOrder 元数据（备注 / 整单优惠 / 联系人）。
* fixture 对应字段缺省时步骤标记 skip，一键串行会自动跳过。
*/
function buildEditOrderMetaSteps(deps, fixture) {
	return [
		{
			id: "sales.setOrderNote",
			label: "sales.setOrderNote",
			description: fixture.orderNote != null ? `note="${fixture.orderNote}"` : "未配置 orderNote，跳过",
			skip: fixture.orderNote == null,
			run: function() {
				var _ref9 = _asyncToGenerator(function* () {
					var _fixture$orderNote;
					return deps.sales.setOrderNote((_fixture$orderNote = fixture.orderNote) !== null && _fixture$orderNote !== void 0 ? _fixture$orderNote : "");
				});
				return function run() {
					return _ref9.apply(this, arguments);
				};
			}()
		},
		{
			id: "sales.setShopDiscount",
			label: "sales.setShopDiscount",
			description: fixture.shopDiscount != null ? `shop_discount=${fixture.shopDiscount}` : "未配置 shopDiscount，跳过",
			skip: fixture.shopDiscount == null,
			run: function() {
				var _ref10 = _asyncToGenerator(function* () {
					return deps.sales.setShopDiscount(fixture.shopDiscount);
				});
				return function run() {
					return _ref10.apply(this, arguments);
				};
			}()
		},
		{
			id: "sales.setContactsInfo",
			label: "sales.setContactsInfo",
			description: fixture.contactsInfo !== void 0 ? `contacts_info=${JSON.stringify(fixture.contactsInfo)}` : "未配置 contactsInfo，跳过",
			skip: fixture.contactsInfo === void 0,
			run: function() {
				var _ref11 = _asyncToGenerator(function* () {
					var _fixture$contactsInfo;
					return deps.sales.setContactsInfo((_fixture$contactsInfo = fixture.contactsInfo) !== null && _fixture$contactsInfo !== void 0 ? _fixture$contactsInfo : null);
				});
				return function run() {
					return _ref11.apply(this, arguments);
				};
			}()
		}
	];
}
/** 编辑 Tab：第一步走 sales.loadDetail(orderId)，再写元数据，其余复用 mutable 步骤 */
function buildEditSteps(deps, fixture) {
	return [
		{
			id: "sales.loadDetail",
			label: "sales.loadDetail",
			description: `加载订单详情 orderId=${fixture.orderId}`,
			run: function() {
				var _ref12 = _asyncToGenerator(function* () {
					if (!Number.isFinite(fixture.orderId) || fixture.orderId <= 0) throw new Error("orderId 必须为正整数");
					return deps.sales.loadDetail(fixture.orderId);
				});
				return function run() {
					return _ref12.apply(this, arguments);
				};
			}()
		},
		...buildEditOrderMetaSteps(deps, fixture),
		...buildMutableSteps(deps, fixture)
	];
}
//#endregion
export { buildCreateSteps, buildEditSteps };
