// form/nc/report/stock-value/stock-value.js

let rowIndex = 0

onMounted(() => {
	nc.grid.activateRows(state, 'stock_value', 1)
	gridRowClicked('stock_value', 1, null, true)
})

function update() {
	let tab = rec.tab
	let returnPdf = false
	if (rec.tab === 'pdf') {
		tab = 'product'
		returnPdf = true
	}
	const param = {
		tab: tab,
		return_pdf: returnPdf,
		search_product: rec.search_product,
		value_date: rec.value_date,
		main_currency: rec.main_currency,
		product_currency: rec.product_currency,
		target_currency: rec.target_currency,
		show_all_events: rec.show_all_events,
		use_cost_price: rec.use_cost_price,
		use_product_price: rec.use_product_price,
		use_sales_price_for_own_work: rec.use_sales_price_for_own_work,
		use_stock_event_price_for_own_work: rec.use_stock_event_price_for_own_work,
		remove_zero_balance_row: rec.remove_zero_balance_row
	}
	const gridParam = [
		{
			name: 'stock_value',
			tab: param.tab
		}
	]
	if (rec.tab === 'product') {
		gridParam.push({
			name: 'stock_event'
		})
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/report/stock-value/grid.json',
			return: { grid: gridParam },
			parameter: param
		},
		() => {
			if (rowIndex > 0 && rec.tab === 'product') {
				const data = state.grid?.stock_value?.data
				if (data && rowIndex > data.length) {
					rowIndex = 1
				}
			}
			nc.grid.activateRows(state, 'stock_value', rowIndex)
			gridRowClicked('stock_value', null, null, true)
		}
	)
}

// eslint-disable-next-line no-unused-vars
function tabChanged() {
	update()
}

function gridRowClicked(area, rowIndex, event, selected) {
	if (selected && area === 'stock_value' && rec.tab === 'product') {
		const data = state.grid?.stock_value?.data
		const stockEvent = state.grid?.stock_event
		if (data && stockEvent) {
			rowIndex = event?.data?.idx || rowIndex
			if (rowIndex > 0 && rowIndex <= data.length) {
				rec.product_info = data[rowIndex - 1].info
				const newData = data[rowIndex - 1].stock_event || []
				nc.grid.dataChanged(stockEvent, newData)
			} else {
				nc.grid.dataChanged(stockEvent, [])
			}
		} else {
			nc.grid.dataChanged(stockEvent, [])
		}
		if (!selected) {
			rowIndex = 0
			nc.grid.dataChanged(stockEvent, [])
		}
	}
}

// eslint-disable-next-line no-unused-vars
function doesExternalFilterPass(node) {
	if (rec.show_all_events === false && node.data.idx !== 1 && !rec.stock_event_type_value_show[node.data.event_type]) {
		return false
	}
	return true
}
