const { searchPurchaserOrderCustomers, fetchPurchaserOrderList, fetchPurchaserOrderDetail, searchPurchaserOrderSkus, savePurchaserOrderItems, fetchPurchaseCategories, createPurchaseCategory, } = require('../../utils/request'); const { buildCategoryPickerOptions, applyManualCategory, applyCategoryInput, categoryInputValue, filterCategoryOptions, findCategoryOptionByName, } = require('../../utils/orderCategory'); const { PROCESSING_METHOD_OPTIONS } = require('../../utils/constants'); const { PROCESSING_OWNER_SUPPLIER, PROCESSING_OWNER_WAREHOUSE, needsProcessingOwnerChoice, } = require('../../utils/processingOwner'); function extraDishFromOrderStatus(status) { return Number(status) >= 60; } const INDEPENDENT_INBOUND_LABEL = '独立入库'; /** 加单专用:非原材料默认仓内,避免改录单默认加工方 */ /** 加单专用:非原材料默认仓内,避免改录单默认加工方 */ function purchaserAddProcessingOwner(method, preferred) { if (!needsProcessingOwnerChoice(method)) return null; const raw = String(preferred || '').trim().toLowerCase(); if (raw === PROCESSING_OWNER_SUPPLIER) return PROCESSING_OWNER_SUPPLIER; return PROCESSING_OWNER_WAREHOUSE; } function emptyDraft(orderStatus) { return { id: `new-${Date.now()}`, item_name: '', sku_code: '', create_product: false, quantity: '', unit: '斤', price: '', cost_price: '', processing_method: '原材料', processing_owner: null, category_code: '', category_name: '', category_label: '', category_input: '', supplier_code: '', is_extra_dish: extraDishFromOrderStatus(orderStatus), remark: '', }; } Component({ options: { addGlobalClass: true }, data: { visible: false, mode: 'add', title: '加单', loading: false, saving: false, error: '', customers: [], customerLabels: ['请选择客户'], customerIndex: 0, customerCode: '', orders: [], orderLabels: ['请选择订单'], orderIndex: 0, orderCode: '', detail: null, draft: emptyDraft(), editItems: [], supplierOptions: [{ supplier_code: '', company_name: '未分配(自采)' }], supplierLabels: ['未分配(自采)'], supplierIndex: 0, processingMethods: PROCESSING_METHOD_OPTIONS, processingIndex: 0, categoryOptions: [], categorySuggestions: [], categoryQuery: '', categoryFocused: false, categoryCanCreate: false, creatingCategory: false, skuSuggestions: [], skuQuery: '', skuFocused: false, skuSearching: false, skuCanCreate: false, }, methods: { async open(mode) { const normalizedMode = mode === 'edit' || mode === 'remove' ? 'edit' : 'add'; this.setData({ visible: true, mode: normalizedMode, title: normalizedMode === 'edit' ? '改单' : '加单', error: '', customerIndex: 0, customerCode: '', orderIndex: 0, orderCode: '', orders: [], orderLabels: ['请选择订单'], detail: null, draft: emptyDraft(), editItems: [], skuSuggestions: [], skuQuery: '', skuFocused: false, skuSearching: false, skuCanCreate: false, }); await Promise.all([this.loadCustomers(), this.loadCategories()]); }, close() { if (this.data.saving) return; if (this._skuSearchTimer) clearTimeout(this._skuSearchTimer); this.setData({ visible: false, categoryFocused: false, skuFocused: false }); }, stopTap() {}, async loadCustomers() { this.setData({ loading: true, error: '' }); try { const result = await searchPurchaserOrderCustomers({}); const customers = result.data || []; const names = customers.map((row) => row.company_name || row.customer_code); const customerLabels = this.data.mode === 'add' ? ['请选择客户', INDEPENDENT_INBOUND_LABEL, ...names] : ['请选择客户', ...names]; this.setData({ customers, customerLabels, }); } catch (err) { this.setData({ error: err.message || '加载客户失败' }); } finally { this.setData({ loading: false }); } }, async loadCategories() { try { const result = await fetchPurchaseCategories(); this.setData({ categoryOptions: buildCategoryPickerOptions(result.data || []) }); } catch (_) { this.setData({ categoryOptions: buildCategoryPickerOptions([]) }); } }, async onCustomerPick(e) { const pickerIndex = Number(e.detail.value) || 0; const addMode = this.data.mode === 'add'; if (addMode && pickerIndex === 1) { this.close(); setTimeout(() => this.triggerEvent('independentinbound'), 80); return; } const offset = addMode ? 2 : 1; const row = pickerIndex >= offset ? this.data.customers[pickerIndex - offset] : null; const customerCode = row ? String(row.customer_code || '') : ''; this.setData({ customerIndex: pickerIndex, customerCode, orderIndex: 0, orderCode: '', orders: [], orderLabels: ['请选择订单'], detail: null, editItems: [], draft: emptyDraft(), skuSuggestions: [], skuQuery: '', skuFocused: false, skuCanCreate: false, }); if (!customerCode) return; this.setData({ loading: true, error: '' }); try { const result = await fetchPurchaserOrderList({ customer_code: customerCode }); const orders = result.data || []; this.setData({ orders, orderLabels: [ '请选择订单', ...orders.map((item) => `${item.order_code} · 配送时间 ${item.delivery_date || '未填'}`), ], }); } catch (err) { this.setData({ error: err.message || '加载订单失败' }); } finally { this.setData({ loading: false }); } }, async onOrderPick(e) { const pickerIndex = Number(e.detail.value) || 0; const row = pickerIndex > 0 ? this.data.orders[pickerIndex - 1] : null; const orderCode = row ? String(row.order_code || '') : ''; this.setData({ orderIndex: pickerIndex, orderCode, detail: null, editItems: [], draft: emptyDraft(), }); if (!orderCode) return; this.setData({ loading: true, error: '' }); try { const result = await fetchPurchaserOrderDetail(orderCode); const detail = result.data || {}; const supplierOptions = [ { supplier_code: '', company_name: '未分配(自采)' }, ...(detail.suppliers || []), ]; this.setData({ detail, editItems: (detail.items || []).map((item) => ({ ...item, pending_remove: false, item_name: item.item_name || '', quantity: item.quantity == null ? '' : String(item.quantity), unit: item.unit || '斤', price: item.price == null ? '' : String(item.price), cost_price: item.cost_price == null ? '' : String(item.cost_price), })), supplierOptions, supplierLabels: supplierOptions.map((item) => item.company_name || item.supplier_code), supplierIndex: 0, draft: emptyDraft(detail.order_status), }); await this.searchSkus(''); } catch (err) { this.setData({ error: err.message || '加载订单详情失败' }); } finally { this.setData({ loading: false }); } }, onDraftInput(e) { const field = e.currentTarget.dataset.field; if (!field) return; this.setData({ [`draft.${field}`]: e.detail.value }); }, onSkuFocus() { this.setData({ skuFocused: true }); this.searchSkus(this.data.draft.item_name || ''); }, onSkuInput(e) { const value = String(e.detail.value || ''); this.setData({ 'draft.item_name': value, 'draft.sku_code': '', 'draft.create_product': false, skuQuery: value, skuFocused: true, }); if (this._skuSearchTimer) clearTimeout(this._skuSearchTimer); this._skuSearchTimer = setTimeout(() => this.searchSkus(value), 250); }, onSkuBlur() { setTimeout(() => this.setData({ skuFocused: false }), 220); }, async searchSkus(query) { if (!this.data.customerCode || this.data.mode !== 'add') return; const q = String(query || '').trim(); const searchSeq = (this._skuSearchSeq || 0) + 1; this._skuSearchSeq = searchSeq; this.setData({ skuSearching: true, skuQuery: q }); try { const result = await searchPurchaserOrderSkus({ customer_code: this.data.customerCode, q, }); if (searchSeq !== this._skuSearchSeq) return; const rows = result.data || []; const normalized = q.toLowerCase(); const exact = rows.some( (row) => String(row.sku_name || '').trim().toLowerCase() === normalized ); this.setData({ skuSuggestions: rows, skuCanCreate: Boolean(q) && !exact, }); } catch (err) { if (searchSeq !== this._skuSearchSeq) return; this.setData({ skuSuggestions: [], skuCanCreate: Boolean(q), error: err.message || '搜索商品失败', }); } finally { if (searchSeq === this._skuSearchSeq) this.setData({ skuSearching: false }); } }, pickSku(e) { const index = Number(e.currentTarget.dataset.index); const row = this.data.skuSuggestions[index]; if (!row) return; const categoryCode = String(row.category_code || ''); const categoryName = String(row.category_name || ''); this.setData({ draft: { ...this.data.draft, sku_code: String(row.sku_code || ''), item_name: String(row.sku_name || row.sku_code || ''), unit: String(row.unit || '斤'), price: Number(row.sale_price) > 0 ? String(row.sale_price) : '', cost_price: Number(row.cost_price) > 0 ? String(row.cost_price) : '', category_code: categoryCode, category_name: categoryName, category_label: categoryName, category_input: categoryName, create_product: false, }, skuFocused: false, skuCanCreate: false, categoryFocused: false, }); }, chooseCreateSku() { const name = String(this.data.skuQuery || this.data.draft.item_name || '').trim(); if (!name) return; this.setData({ 'draft.item_name': name, 'draft.sku_code': '', 'draft.create_product': true, skuFocused: false, skuCanCreate: false, }); wx.showToast({ title: '确认加单时新建商品', icon: 'none' }); }, onSupplierPick(e) { const index = Number(e.detail.value) || 0; const option = this.data.supplierOptions[index] || this.data.supplierOptions[0]; this.setData({ supplierIndex: index, 'draft.supplier_code': option ? option.supplier_code || '' : '', }); }, onProcessingPick(e) { const index = Number(e.detail.value) || 0; const method = this.data.processingMethods[index] || '原材料'; this.setData({ processingIndex: index, 'draft.processing_method': method, 'draft.processing_owner': purchaserAddProcessingOwner( method, this.data.draft.processing_owner ), }); }, onProcessingOwnerTap(e) { const method = this.data.draft.processing_method; if (!needsProcessingOwnerChoice(method)) return; const owner = String(e.currentTarget.dataset.owner || '') === PROCESSING_OWNER_WAREHOUSE ? PROCESSING_OWNER_WAREHOUSE : PROCESSING_OWNER_SUPPLIER; this.setData({ 'draft.processing_owner': owner }); }, setCategorySearch(value) { const query = String(value || '').trim(); this.setData({ categoryQuery: query, categorySuggestions: filterCategoryOptions(query, this.data.categoryOptions, 20), categoryCanCreate: Boolean(query) && !findCategoryOptionByName(query, this.data.categoryOptions), }); }, onCategoryFocus() { this.setData({ categoryFocused: true }); this.setCategorySearch(this.data.draft.category_input || ''); }, onCategoryInput(e) { const value = e.detail.value; const draft = applyCategoryInput(this.data.draft, value, this.data.categoryOptions); this.setData({ draft: { ...draft, category_input: value }, categoryFocused: true, }); this.setCategorySearch(value); }, onCategoryBlur() { setTimeout(() => this.setData({ categoryFocused: false }), 220); }, pickCategory(e) { const index = Number(e.currentTarget.dataset.index); const option = this.data.categorySuggestions[index]; if (!option) return; const draft = applyManualCategory(this.data.draft, option); this.setData({ draft: { ...draft, category_input: categoryInputValue(draft) }, categoryFocused: false, categoryCanCreate: false, }); }, async createCategory() { if (this.data.creatingCategory) return; const name = String(this.data.categoryQuery || '').trim(); if (!name) return; this.setData({ creatingCategory: true }); try { const result = await createPurchaseCategory(name); const created = result.data || {}; const createdOption = buildCategoryPickerOptions([created]).find((item) => item.category_code) || created; const categoryOptions = [ ...this.data.categoryOptions.filter( (item) => item.category_code !== createdOption.category_code ), createdOption, ]; const draft = applyManualCategory(this.data.draft, createdOption); this.setData({ categoryOptions, draft: { ...draft, category_input: categoryInputValue(draft) }, categoryFocused: false, categoryCanCreate: false, }); wx.showToast({ title: '分类已创建', icon: 'success' }); } catch (err) { wx.showToast({ title: err.message || '创建失败', icon: 'none' }); } finally { this.setData({ creatingCategory: false }); } }, onEditItemInput(e) { const index = Number(e.currentTarget.dataset.index); const field = e.currentTarget.dataset.field; if (!field || Number.isNaN(index)) return; this.setData({ [`editItems[${index}].${field}`]: e.detail.value }); }, toggleRemoveItem(e) { const index = Number(e.currentTarget.dataset.index); const item = this.data.editItems[index]; if (!item) return; this.setData({ [`editItems[${index}].pending_remove`]: !item.pending_remove }); }, async save() { if (this.data.saving || !this.data.orderCode) return; if (this.data.detail && this.data.detail.can_edit_items === false) { wx.showToast({ title: '当前订单不可修改', icon: 'none' }); return; } let payload; if (this.data.mode === 'add') { const draft = this.data.draft; if (!String(draft.item_name || '').trim()) { wx.showToast({ title: '请输入商品名称', icon: 'none' }); return; } if (!String(draft.sku_code || '').trim() && draft.create_product !== true) { wx.showToast({ title: '请选择已有商品或新建商品', icon: 'none' }); return; } if (!(Number(draft.quantity) > 0)) { wx.showToast({ title: '数量须大于 0', icon: 'none' }); return; } if (!(Number(draft.price) > 0)) { wx.showToast({ title: '销售价须大于 0', icon: 'none' }); return; } if (!String(draft.category_code || draft.category_name || '').trim()) { wx.showToast({ title: '请选择或新增分类', icon: 'none' }); return; } payload = { mode: 'add', items: [ { ...draft, is_extra_dish: extraDishFromOrderStatus(this.data.detail?.order_status), processing_owner: purchaserAddProcessingOwner( draft.processing_method, draft.processing_owner ), }, ], }; } else { const kept = this.data.editItems.filter((item) => !item.pending_remove); if (!kept.length) { wx.showToast({ title: '订单至少保留一项商品', icon: 'none' }); return; } for (const item of kept) { if (!String(item.item_name || '').trim()) { wx.showToast({ title: '商品名称不能为空', icon: 'none' }); return; } if (!(Number(item.quantity) > 0)) { wx.showToast({ title: '数量须大于 0', icon: 'none' }); return; } if (!String(item.unit || '').trim()) { wx.showToast({ title: '请填写单位', icon: 'none' }); return; } if (!(Number(item.price) > 0)) { wx.showToast({ title: '销售价须大于 0', icon: 'none' }); return; } if (Number(item.cost_price) < 0) { wx.showToast({ title: '采购成本不能小于 0', icon: 'none' }); return; } } payload = { mode: 'edit', items: kept.map((item) => ({ id: item.id, item_name: String(item.item_name || '').trim(), quantity: Number(item.quantity), unit: String(item.unit || '').trim(), price: Number(item.price), cost_price: Math.max(0, Number(item.cost_price) || 0), })), }; } this.setData({ saving: true, error: '' }); try { await savePurchaserOrderItems(this.data.orderCode, payload); wx.showToast({ title: this.data.mode === 'add' ? '加单成功' : '改单成功', icon: 'success' }); this.setData({ visible: false }); this.triggerEvent('saved', { mode: this.data.mode, orderCode: this.data.orderCode }); } catch (err) { this.setData({ error: err.message || '保存失败' }); wx.showToast({ title: err.message || '保存失败', icon: 'none' }); } finally { this.setData({ saving: false }); } }, }, });