radio-value.js 2.8 KB
/** radio 字段值归一化 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import { ATTENDANCE_KEY, flattenFields } from './visibility.js'

export const ON_DUTY_LABEL = '在岗'
export const OFF_DUTY_LABEL = '调休'
export const LEGACY_ON_DUTY = '1'
export const LEGACY_OFF_DUTY = '2'

/** 按 options 将 label/value/legacy 值归一化为 option.value */
export function resolveRadioOptionValue(field, rawValue) {
	if (rawValue == null || rawValue === '' || !field?.options?.length) {
		return rawValue
	}
	const str = String(rawValue)
	const byValue = field.options.find(option => String(option.value) === str)
	if (byValue) {
		return byValue.value
	}
	const byLabel = field.options.find(
		option => option.label === rawValue || option.label === str
	)
	if (byLabel) {
		return byLabel.value
	}
	if (str === LEGACY_ON_DUTY) {
		const onDuty =
			field.options.find(option => option.label === ON_DUTY_LABEL) ||
			field.options.find(option => String(option.value) === LEGACY_ON_DUTY) ||
			field.options[0]
		return onDuty?.value ?? rawValue
	}
	if (str === LEGACY_OFF_DUTY) {
		const offDuty =
			field.options.find(option => option.label === OFF_DUTY_LABEL) ||
			field.options.find(option => String(option.value) === LEGACY_OFF_DUTY) ||
			field.options[1]
		return offDuty?.value ?? rawValue
	}
	return rawValue
}

/** @returns {object|undefined} 出勤字段(F1-1)的 schema 定义 */
export function getAttendanceField(list = []) {
	return flattenFields(list).find(field => field.key === ATTENDANCE_KEY)
}

/** @returns {object|null} 「在岗」选项对象 */
export function getOnDutyOption(field) {
	if (!field?.options?.length) {
		return null
	}
	return (
		field.options.find(option => option.label === ON_DUTY_LABEL) ||
		field.options.find(option => String(option.value) === LEGACY_ON_DUTY) ||
		field.options[0]
	)
}

/** 判断当前出勤状态是否为「在岗」 */
export function isAttendanceOnDuty(list = [], values = {}) {
	const field = getAttendanceField(list)
	const raw = values[ATTENDANCE_KEY]
	if (raw == null || raw === '') {
		return false
	}
	if (!field?.options?.length) {
		return raw === LEGACY_ON_DUTY || raw === ON_DUTY_LABEL
	}
	const onDutyOption = getOnDutyOption(field)
	if (!onDutyOption) {
		return false
	}
	const normalized = resolveRadioOptionValue(field, raw)
	return String(normalized) === String(onDutyOption.value)
}

/** 批量归一化 values 中所有 radio 字段 */
export function normalizeRadioValuesInMap(list = [], values = {}) {
	const radioFields = flattenFields(list).filter(field => field.type === 'radio')
	if (!radioFields.length) {
		return values
	}
	const nextValues = { ...values }
	radioFields.forEach(field => {
		if (nextValues[field.key] === undefined) {
			return
		}
		nextValues[field.key] = resolveRadioOptionValue(field, nextValues[field.key])
	})
	return nextValues
}