// form/nc/nc-load/nc-load.js
let returnRec
function update(action, reload) {
	if (action == 'capacity' && rec.old_capacity) {
		rec.old_work_date = true
	}
	if (action == 'work_date' && rec.old_work_date) {
		rec.old_capacity = true
		action = 'capacity'
	}
	if (action !== 'work_date') {
		if (returnRec == null) {
			returnRec = nc.clone(rec)
		}
		const parameter = {
			reload_data: reload === 1 ? false : reload ? true : rec.reload_data,
			create_schedule: rec.create_schedule,
			virtual_production_order: rec.virtual_production_order,
			old_capacity: rec.old_capacity,
			return_rec: returnRec !== false
		}
		nc.callServer(state, 'calc/loading', { parameter: parameter }, ret => {
			if (returnRec) {
				for (const key in returnRec) {
					if (typeof returnRec[key] === 'boolean') {
						rec[key] = returnRec[key]
					}
				}
				returnRec = false // after first call we want to keep user changed values
			}
			if (!ret.grid) {
				message.setWarning(state, `Return grid was not found.`)
				return
			}
			if (rec && ret.grid?.gridIdx?.capacityIdx) {
				/* 	let arr = ret.grid['product_work-schedule']?.data.filter(r => r.resource_id == 'VALMISTUS')
				// .slice(-5)
				// .slice(0, 2)
				ret.grid['product_work-schedule'].data = arr */
				rec.gantt_data = {
					work_phase: ret.grid?.['product_work-schedule']?.data,
					resource: ret.grid?.['resource-load_group']?.data,
					product: ret.grid?.['product']?.data,
					capacityIdx: ret.grid.gridIdx.capacityIdx
				}
			}
		})
	}
}

onMounted(() => {
	nc.incrementalUpdate(state)
	/* if (!rec.gantt_data?.resource) {
		update('update')
	} else */
	if (!state.grid?.nats_name) {
		update('update', 1) // fill the grid with data by calling the server
	}
	rec.reload_data = rec.reload_data || rec.constant?.reload_default >= 1
	watch(
		() => rec.only_open + rec.only_started * 10 + rec.show_connection * 100, // track all values together, boolean will be converted to 0 or 1: 0, 1, 10, 11, ...
		newValue => {
			rec.gantt_update = newValue
		},
		{ immediate: true }
	)
})
