// form/nc/report/form/form.js

const loadPdf = nc.debounce(loadPdfFunc, (rec.update_pdf_seconds && rec.update_pdf_seconds * 1000) || 200, false) // default delay of 200 ms

onMounted(() => {
	changeTab() // first data load
	watch(
		() => rec.pdf_update_trigger, // nc-include pages loadPdf() this by "v-on:change": "rec.pdf_update_trigger++"
		() => {
			loadPdf()
		}
	)
})

function showPdf(noDelay) {
	if (rec.show_pdf) {
		if (noDelay) {
			loadPdfFunc()
		} else {
			loadPdf()
		}
	}
}

function setRecord(item, noDelay) {
	nc.mergeState(state, 'rec', item, 'form/nc/report/form/form.js')
	const formRec = rec[rec.tab]
	if (formRec) {
		delete rec.document_data
		if (formRec.run_code) {
			nc.callServer(
				state,
				'run_code',
				{
					run_code: formRec.run_code,
					rec: rec,
					data: [rec]
				},
				ret => {
					if (ret.data && ret.data[0]) {
						nc.mergeState(state, 'rec', ret.data[0], 'form/nc/report/form/form.js')
					}
					showPdf(noDelay)
				}
			)
		}
	} else {
		showPdf(noDelay)
	}
}

function pdfCallback(ret) {
	if (rec.show_pdf && ret && ret.page) {
		// ret.page is pdf render result
		const tab = state?.rec?.tab || 'Form'
		const tabShow = nc.recordArrayField(state.arr.tab, 'value', tab, 'show') || 'Form'
		rec.document_data = {
			data: ret.page,
			mime_type: 'application/pdf',
			document_name: tab === 'pallet-label' ? tabShow + '-' + rec.dispatch_note + '.pdf' : tabShow + '.pdf'
		}
		return
	}
}

function setSelected() {
	const arr = nc.grid.activatedRecordArr(state, 'form_row')
	rec.selected = (arr && arr.length) || 0
}

function callback(ret) {
	pdfCallback(ret)
	const arr = state?.grid?.form_row?.data
	rec.pro = { json_data: {} }
	rec.pr = { json_data: {} }
	rec.co = { json_data: {} }
	if (arr && arr.length > 0) {
		setRecord(arr[0], true)
		nc.grid.activateRows(state, 'form_row', 1)
	}
	setSelected()
}

// eslint-disable-next-line no-unused-vars
function gridRowClicked(area, rowIndex, event, selected) {
	setSelected()
	if (selected) {
		setRecord(event.data, true)
	}
}

function loadPdfFunc() {
	if (rec.show_pdf) {
		delete rec.document_data
		nc.callServer(
			state,
			'print',
			{
				render_preference: {
					document_type: 'pdf',
					output_path: rec.output_path,
					paper_type: rec.paper_type,
					landscape: rec.landscape,
					parameter: { picture_path_replace: rec[rec.tab]?.picture_path_replace || rec.picture_path_replace }
				},
				component: rec.layout_component,
				state: {
					rec: rec,
					hdr: hdr
				}
			},
			pdfCallback
		)
	}
}

function printParam(option) {
	const formRec = rec[rec.tab] || rec
	if (formRec && formRec.run_print_code) {
		if (!state.grid?.form_row?.data) {
			message.setWarning(state, 'Form row data does not exist')
			return
		}
		let data
		if (option === 'all') {
			data = state.grid.form_row.data
		} else if (option === 'selected') {
			data = nc.grid.activatedRecordArr(state, 'form_row')
		}
		if (data.length === 0) {
			message.setWarning(state, 'No form row data selected')
			return
		}
		let param = (rec[rec.tab] || rec)?.print_parameter_field?.reduce((acc, field) => {
			acc[field] = rec[field]
			return acc
		}, {})
		if (param == null) {
			message.setWarning(state, 'Print parameter fields are not defined')
			return
		}
		if (rec[rec.tab]) {
			for (const [key, value] of Object.entries(rec[rec.tab])) {
				param[key] = value
			}
		}
		param.paper_type = rec.paper_type
		delete param.document_data
		return param
	}
	return null
}

// eslint-disable-next-line no-unused-vars
function print(option) {
	const param = printParam(option)
	if (param) {
		nc.callServer(
			state,
			'run_code',
			{
				run_code: param.run_print_code,
				rec: param,
				hdr: hdr,
				data: data
			} /* ,
				ret => {
					if (ret.rec) {
						nc.mergeState(state, 'rec', ret.rec, 'form/nc/report/form/form.js')
					}
					showPdf(noDelay)
				} */
		)
	}
}

function changeTab() {
	rec.layout_component = 'form/nc/report/form/' + rec.tab
	const arrItem = arr.tab.find(item => item.value === rec.tab)
	if (arrItem && arrItem.paper_type) {
		rec.paper_type = arrItem.paper_type
	}
	if (arrItem && arrItem.landscape != null) {
		rec.landscape = arrItem.landscape
	}
	delete rec.document_data
	update()
}

function update() {
	const param = {
		invoice: rec.invoice,
		dispatch_note: rec.dispatch_note,
		program_number: rec.program_number,
		production_order: rec.production_order,
		start_date: rec.start_date,
		invoice_start_date: rec.invoice_start_date,
		production_order_state_skip: rec.production_order_state_skip
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/report/form/grid.json',
			return: {
				grid: [
					{
						name: 'form_row',
						tab: rec.tab
					}
				]
			},
			parameter: param
		},
		callback
	)
}
