form-field-select.js 10.8 KB
/**
 * select 单选字段 — 标量 value,弹框 mode=single
 * @see packageDynamicForm/docs/field-options-api.md
 *
 * optionsKey 存在时打开前 fetchFieldOptions;确认写入单个 option.value
 */
const { fetchFieldOptions } = require('../../api/fieldOptionsService.js')
const { normalizeOptionRecord } = require('../../form-engine/field-submit-value.js')
const { getVisibleFieldOptions } = require('../../form-engine/option-visibility.js')
const { resolveSelectFieldState } = require('../form-picker-popup/select-display.js')
const {
	resolveOrderListSaleDate,
	isDealDateMissingForOrderList,
	isOrderListField,
	resolveCarBrandTypeFlagFromField
} = require('../../utils/order-list-params.js')
const {
	shouldRefreshOptionsOnPopup,
	isEmployeeListPickerSearchable
} = require('../../utils/field-options-popup.js')
const {
	buildUpgradeIconUrl,
	FORM_FIELD_ARROW_ICON
} = require('../../utils/upgrade-icon-url.js')

Component({
	properties: {
		field: { type: Object, value: {} },
		value: { type: null },
		disabled: { type: Boolean, value: false },
		error: { type: String, value: '' },
		requestContext: { type: Object, value: {} },
		rowValues: { type: Object, value: {} },
		groupBrandIds: { type: Array, value: [] },
		groupKey: { type: String, value: '' },
		rowIndex: { type: Number, value: -1 }
	},

	data: {
		displayLabel: '',
		showPicker: false,
		pickerOptions: [],
		pickerValue: [],
		loadingOptions: false,
		pickerSearchable: false,
		searchKeyword: '',
		arrowIconUrl: ''
	},

	lifetimes: {
		attached() {
			this._optionsSyncSeq = 0
			this._lastDisplaySyncKey = ''
			this.setData({
				arrowIconUrl: buildUpgradeIconUrl(FORM_FIELD_ARROW_ICON)
			})
		}
	},

	observers: {
		'field, value, pickerOptions': function (field, value) {
			this.refreshDisplayLabel(field, value)
		},
		'field, value': function (field, value) {
			this.syncPickerValueFromField(field, value)
		},
		'field.optionsKey, value, requestContext': function () {
			this.syncDisplayOptions()
		}
	},

	methods: {
		getOptionsForDisplay(field = this.data.field) {
			if (this.data.pickerOptions.length) {
				return this.data.pickerOptions
			}
			return field?.optionsKey ? field.options || [] : this.getStaticOptions()
		},

		resolveFieldState(field = this.data.field, value = this.data.value) {
			return resolveSelectFieldState(field, value, this.getOptionsForDisplay(field))
		},

		syncPickerValueFromField(field = this.data.field, value = this.data.value) {
			const { optionId } = this.resolveFieldState(field, value)
			this.setData({
				pickerValue: optionId ? [optionId] : []
			})
		},

		/** 根据 options / App 双 key 解析展示文案 */
		refreshDisplayLabel(field = this.data.field, value = this.data.value) {
			const { displayLabel } = this.resolveFieldState(field, value)
			this.setData({ displayLabel })
		},

		/** 详情回显:有 value 且具备门店上下文时静默预拉 options */
		async syncDisplayOptions() {
			const field = this.data.field || {}
			const value = this.data.value
			if (!field.optionsKey || value == null || value === '') return
			const ctx = this.data.requestContext || {}
			const merchantKey = ctx.yqMerchantId || ctx.merchantId
			if (!merchantKey) return

			const rowValues = this.properties.rowValues || {}
			const saleDate = isOrderListField(field)
				? resolveOrderListSaleDate(field, rowValues)
				: ''
			const { optionId } = resolveSelectFieldState(field, value, [])
			const groupBrandIds = this.properties.groupBrandIds || []
			const carBrandTypeFlag = isOrderListField(field)
				? resolveCarBrandTypeFlagFromField(field, groupBrandIds)
				: ''
			const sceneKey = JSON.stringify(ctx.sceneList || [])
			const syncKey = `${field.optionsKey}|${merchantKey}|${saleDate}|${carBrandTypeFlag}|${sceneKey}|${optionId || value}`
			if (syncKey === this._lastDisplaySyncKey && this.data.pickerOptions.length) {
				this.refreshDisplayLabel(field, value)
				return
			}

			const seq = ++this._optionsSyncSeq
			const options = await this.loadOptions({ silent: true })
			if (seq !== this._optionsSyncSeq) return
			this._lastDisplaySyncKey = syncKey
			if (options.length) {
				this.refreshDisplayLabel(field, value)
			}
		},
		buildChangeDetail(value, displayLabel, extra = {}) {
			const detail = { key: this.data.field.key, value, ...extra }
			if (displayLabel != null && displayLabel !== '') {
				detail.displayLabel = displayLabel
			}
			if (this.properties.groupKey) {
				detail.groupKey = this.properties.groupKey
				const rowIndex = Number(this.properties.rowIndex)
				if (!Number.isNaN(rowIndex) && rowIndex >= 0) {
					detail.rowIndex = rowIndex
				}
			}
			return detail
		},

		getStaticOptions() {
			const requestContext = this.data.requestContext || {}
			const activeSceneCode = requestContext.baseSceneCode
			const optionContext = activeSceneCode == null || activeSceneCode === ''
				? requestContext
				: {
					...requestContext,
					sceneList: [{ baseSceneCode: activeSceneCode }]
				}
			return getVisibleFieldOptions(
				this.data.field || {},
				optionContext
			)
		},

		/** storeStaffList / 4sStaffList 弹框启用服务端姓名搜索(门店驻店人员、洽谈驻店人员、销售/交付专员) */
		isStaffPickerSearchable(field = this.data.field) {
			return isEmployeeListPickerSearchable(field?.optionsKey)
		},

		/** 组装 optionsKey 远程拉取参数(merchantId、reportDate、saleDate 等) */
		buildFetchParams() {
			const ctx = this.data.requestContext || {}
			const field = this.data.field || {}
			const rowValues = this.properties.rowValues || {}
			const groupBrandIds = this.properties.groupBrandIds || []
			const saleDate = isOrderListField(field)
				? resolveOrderListSaleDate(field, rowValues)
				: ''
			const carBrandTypeFlag = isOrderListField(field)
				? resolveCarBrandTypeFlagFromField(field, groupBrandIds)
				: ''
			return {
				optionsKey: field.optionsKey,
				merchantId: ctx.merchantId,
				yqMerchantId: ctx.yqMerchantId,
				staffUuid: ctx.staffUuid,
				reportDate: ctx.reportDate,
				saleDate,
				carBrandTypeFlag,
				reportType: ctx.reportType || 'store',
				sceneType: ctx.sceneType,
				sceneList: ctx.sceneList || [],
				groupBrandIds,
				name: this.data.searchKeyword || ''
			}
		},

		/**
		 * 打开前拉取或读取静态 options,写入 pickerOptions 并返回列表
		 * @param {Object} [options={}]
		 * @param {boolean} [options.silent=false] 静默拉取(详情回显 label,不展示 loading)
		 * @param {boolean} [options.useCache=true] 是否使用 fieldOptionsService 进程内缓存;orderList/storeStaffList/4sStaffList 打开弹框时应传 false
		 * @returns {Promise<Array>}
		 */
		async loadOptions({ silent = false, useCache = true } = {}) {
			const field = this.data.field || {}
			if (!field.optionsKey) {
				const options = this.getStaticOptions()
				this.setData({ pickerOptions: options })
				return options
			}

			if (!silent) {
				this.setData({ loadingOptions: true })
			}
			try {
				const res = await fetchFieldOptions(this.buildFetchParams(), { useCache })
				if (res?.code !== 0) {
					if (!silent) {
						wx.$util?.showToast?.(res?.message || '获取选项失败')
					}
					return []
				}
				const options = Array.isArray(res.data) ? res.data : []
				this.setData({ pickerOptions: options })
				return options
			} catch (error) {
				console.error(error)
				if (!silent) {
					wx.$util?.showToast?.('获取选项失败')
				}
				return []
			} finally {
				if (!silent) {
					this.setData({ loadingOptions: false })
				}
			}
		},

		buildSubmitValue(selected) {
			if (!selected) return selected
			const field = this.data.field || {}
			if (isOrderListField(field) && selected?.raw) {
				const orderCode = selected.value ?? selected.raw?.orderCode ?? ''
				return {
					id: orderCode,
					name: orderCode,
					orderCode,
					raw: selected.raw
				}
			}
			if (field?.optionsKey) {
				return normalizeOptionRecord(selected) || selected.value
			}
			return selected.value
		},

		buildOrderChangeExtra(selected) {
			if (!isOrderListField(this.data.field) || !selected) {
				return {}
			}
			const raw = selected.raw || selected
			const orderCode = selected.value ?? raw?.orderCode ?? ''
			return {
				metaValue: { id: orderCode, name: orderCode, orderCode, ...raw },
				orderRaw: raw
			}
		},

		/** 点击字段:拉选项,≤6 项用 ActionSheet 否则打开 picker 弹框 */
		async onTap() {
			if (this.data.disabled) return

			const field = this.data.field || {}
			const rowValues = this.properties.rowValues || {}
			const ctx = this.data.requestContext || {}
			if (isDealDateMissingForOrderList(field, rowValues)) {
				wx.$util?.showToast?.('请先选择成交日期')
				return
			}

			const pickerSearchable = this.isStaffPickerSearchable(field)
			this.setData({ searchKeyword: '', pickerSearchable })

			let options = this.data.pickerOptions
			if (field?.optionsKey) {
				// 远程 optionsKey 每次打开弹框重新拉取,避免进程内缓存展示过期数据
				options = await this.loadOptions({
					useCache: !shouldRefreshOptionsOnPopup(field)
				})
			} else {
				options = this.getStaticOptions()
				this.setData({ pickerOptions: options })
			}

			if (!options.length && !pickerSearchable) {
				return wx.$util?.showToast?.('暂无可选项')
			}

			if (options.length <= 6 && !this.data.field?.optionsKey) {
				wx.showActionSheet({
					itemList: options.map(item => item.label),
					success: res => {
						const selected = options[res.tapIndex]
						if (!selected) return
						const submitValue = this.buildSubmitValue(selected)
						this.triggerEvent(
							'change',
							this.buildChangeDetail(
								submitValue,
								selected.label,
								this.buildOrderChangeExtra(selected)
							)
						)
					}
				})
				return
			}

			const { optionId } = this.resolveFieldState(this.data.field, this.data.value)
			this.setData({
				showPicker: true,
				pickerValue: optionId ? [optionId] : []
			})
		},

		/** 弹框内搜索:带 name 重拉员工列表(对齐 Merchant-Seles) */
		async onPickerSearch(e) {
			const searchKeyword = e.detail?.value || ''
			this.setData({ searchKeyword })
			await this.loadOptions({ useCache: false })
		},

		/** 弹框确认:关闭 picker 并 triggerEvent('change') 写入选中值 */
		onPickerConfirm(e) {
			let selected = e.detail?.value
			if (Array.isArray(selected)) {
				selected = selected[0]
			}
			this.setData({ showPicker: false, searchKeyword: '' })
			const options = this.data.pickerOptions.length
				? this.data.pickerOptions
				: this.data.field?.options || []
			const matched = options.find(item => String(item.value) === String(selected))
			const submitValue = matched ? this.buildSubmitValue(matched) : selected
			this.triggerEvent(
				'change',
				this.buildChangeDetail(
					submitValue,
					matched?.label,
					matched ? this.buildOrderChangeExtra(matched) : {}
				)
			)
		},

		onPickerCancel() {
			this.setData({ showPicker: false, searchKeyword: '' })
		}
	}
})