dailyReportPageMethods.js 5.87 KB
/**
 * 三份日报 Page behavior 方法表(供 Behavior 注册与页面覆盖委托)
 * 微信小程序 Behavior() 返回 behaviorId 字符串,不可在其上挂 .methods
 * @see packageDynamicForm/docs/ARCHITECTURE.md
 */
const { createFormEngine } = require('../../form-engine/core.js')
const {
	mergeGroupRowMapsIntoData,
	patchGroupRowMapForKey
} = require('../../utils/merge-form-group-view.js')
const { resolveApiFailureMessage } = require('../../utils/api-failure-message.js')
const {
	resolveReportSubmittedPatch
} = require('../../utils/daily-report-edit-state.js')

const dailyReportPageMethods = {
	getEngineKey(reportDate) {
		return reportDate
	},

	ensureEngine(engineKey) {
		if (this.engine && this.engineKey === engineKey) {
			return this.engine
		}
		this.engine = createFormEngine()
		this.engineKey = engineKey
		return this.engine
	},

	isStaleLoad(seq) {
		return seq !== this.loadSeq
	},

	isStaleRefresh(seq) {
		return seq !== this.refreshSeq
	},

	/**
	 * 将 engine.getViewState 写入 data;合并 subform 行显隐 map
	 * @param {Object} [extraData] structureChanged / refreshFixedFields / errors / changedGroupKey / groupActiveIndex / keepErrors
	 */
	applyEngineView(viewState = {}, extraData = {}) {
		const structureChanged = extraData.structureChanged !== false
		const nextData = {
			values: viewState.values || {},
			groupRowsCache: viewState.groupRowsCache || {},
			formDisabled:
				typeof this.getFormDisabled === 'function'
					? this.getFormDisabled()
					: !!this.data.formDisabled,
			requestContext:
				typeof this.buildFormRequestContext === 'function'
					? this.buildFormRequestContext()
					: this.data.requestContext || {}
		}
		if (structureChanged || extraData.refreshFixedFields) {
			nextData.fixedFields = viewState.fixedFields || []
		}
		if (structureChanged) {
			nextData.sectionGroups = viewState.sectionGroups || []
			nextData.groupFields = viewState.groupFields || []
		}
		if (extraData.errors !== undefined) {
			nextData.errors = extraData.errors
		} else if (!extraData.keepErrors) {
			nextData.errors = {}
		}
		let groupActiveIndex = this.data.groupActiveIndex || {}
		if (extraData.groupActiveIndex !== undefined) {
			nextData.groupActiveIndex = extraData.groupActiveIndex
			groupActiveIndex = extraData.groupActiveIndex
		} else if (structureChanged) {
			nextData.groupActiveIndex = {}
			groupActiveIndex = {}
		}
		const groupFields = structureChanged
			? viewState.groupFields || []
			: this.data.groupFields || []
		const cache = viewState.groupRowsCache || {}
		const values = viewState.values || {}
		const visibilityContext =
			this.engine && typeof this.engine.getPageContext === 'function'
				? {
						ctx: this.engine.getPageContext(),
						values,
						list: this.engine.getSchemaList()
					}
				: null
		if (groupFields.length) {
			if (extraData.changedGroupKey) {
				patchGroupRowMapForKey(
					nextData,
					groupFields,
					extraData.changedGroupKey,
					cache,
					groupActiveIndex,
					values,
					visibilityContext
				)
			} else {
				mergeGroupRowMapsIntoData(
					nextData,
					groupFields,
					cache,
					groupActiveIndex,
					values,
					visibilityContext
				)
			}
		}
		this.setData(nextData)
	},

	/** 提交/保存失败 Toast:优先后端 message,其次异常 message */
	showSubmitFailureToast(res, error, fallback = '提交失败') {
		wx.$util.showToast(resolveApiFailureMessage(res, error, fallback))
	},

	/** 从 detail + weeklyList 同步 reportStatus / isReportSubmitted */
	syncReportSubmittedState(detail = {}) {
		const patch = resolveReportSubmittedPatch({
			detail,
			reportDate: this.data.reportDate,
			weeklyList: this.data.weeklyList || []
		})
		Object.assign(this.data, patch)
		this.setData(patch)
		return patch.isReportSubmitted
	},

	/** 进入编辑态(已提交日报解锁) */
	editReport() {
		this.data.isEditReport = true
		this.setData({
			isEditReport: true,
			formDisabled: false
		})
	},

	/** 退出编辑态,不重载详情 */
	cancelReport() {
		this.data.isEditReport = false
		this.setData({
			isEditReport: false,
			formDisabled:
				typeof this.getFormDisabled === 'function'
					? this.getFormDisabled()
					: !!this.data.formDisabled
		})
	},

	/** 换周/换日时重置编辑态 */
	resetEditReport() {
		if (!this.data.isEditReport) return
		this.data.isEditReport = false
		this.setData({
			isEditReport: false,
			formDisabled:
				typeof this.getFormDisabled === 'function'
					? this.getFormDisabled()
					: !!this.data.formDisabled
		})
	},

	/**
	 * 提交后重拉详情:用最新 pageContext(含 echo 元数据)重新 init engine
	 * @param {Object} loadRes.data - loadDailyForm 返回值
	 */
	reinitEngineFromLoadData(loadData = {}) {
		if (!this.engine) {
			return null
		}
		const { pageContext, schema, initialValues } = loadData
		return this.engine.init(schema, {
			...pageContext,
			initialValues: initialValues || {}
		})
	},

	/**
	 * 首屏 applyEngineView 后,空闲时后台刷新 brand/scene/schema 缓存(不热更新 UI)
	 * @param {Object} api 日报 API 门面(须含 revalidateCachedMetadata)
	 * @param {Object} params userContext、baseSceneCode、reportTemplateId
	 * @param {number} loadSeq 当前 loadSeq,过期则放弃
	 * @returns {void}
	 */
	scheduleMetadataCacheRevalidate(api, params, loadSeq) {
		if (this._metadataRevalidateTimer) {
			clearTimeout(this._metadataRevalidateTimer)
			this._metadataRevalidateTimer = null
		}
		const run = () => {
			this._metadataRevalidateTimer = null
			if (this.isStaleLoad(loadSeq)) {
				return
			}
			if (!api || typeof api.revalidateCachedMetadata !== 'function') {
				return
			}
			api.revalidateCachedMetadata(params).catch(() => {})
		}
		const schedule = () => {
			this._metadataRevalidateTimer = setTimeout(run, 0)
		}
		if (typeof wx !== 'undefined' && typeof wx.nextTick === 'function') {
			wx.nextTick(schedule)
		} else {
			schedule()
		}
	}
}

module.exports = dailyReportPageMethods