// form/nc/nc-list-form/nc-list-form.js
const mainState = nc.mainState()
const recordTypeSeparator = mainState.rec.recordTypeSeparator
mainState.list = state

const area = 'list' // grid area name
const baseCallParam = {
	rec: { tab: '', table: '' } // , query: { field: '', operator: '', query_value1: '', query_value2: '', query_name: '' } }
}
let prevTable = ''
let allSelected = ref(false)
let rowsLoaded = ref(0)
let rowsInSelection = ref(0)
let rowsInTable = ref(0)
let gridStyle = ref('')
setGridStyle(1)

callServer('init')

onDeactivated(() => {
	mainState.rec.in_form = ''
	rec.progress_bar.message = ''
	rec.progress_bar.status = ''
})

onActivated(() => {
	// using keep-alive
	mainState.rec.in_form = 'list'
	if (rec.row_index != null && rec.first_displayed_row != null && rec.start_row_index != null) {
		nc.grid.redrawRows(state, area)
		nc.grid.activateRows(state, area, rec.row_index, rec.first_displayed_row + rec.row_index - rec.start_row_index, 'unselectOther')
	}
	/* if (rec.record_id) {
				const selectIdx = nc.recordArrayIndex(state.grid.list.data, rec.table_prefix + '.record_id', rec.record_id)
				nc.grid.activateRows(state, area, selectIdx + 1, 'scroll-first', 'unselectOther')
			} */
})

/* onDeactivated(() => {
			// using keep-alive
		}) */

onMounted(() => {
	mainState.rec.in_form = 'list'
	// window.removeEventListener('keyup', globalKeypress)
	window.addEventListener('keyup', globalKeypress)
})

onBeforeUnmount(() => {
	mainState.rec.in_form = ''
	window.removeEventListener('keyup', globalKeypress)
})

function globalKeypress() {}

watchEffect(() => {
	if (mainState.rec.table !== '' && rec.table !== mainState.rec.table) {
		if (arr.query && nc.isArray(arr.query[mainState.rec.table]) && nc.isArray(arr.query[rec.table])) {
			if (arr.query[mainState.rec.table].length > arr.query[rec.table].length) {
				setGridStyle(arr.query[mainState.rec.table].length) // make grid area smaller, never bigger to prevent scrollbar flash
			}
		}
		arr.default_query[0].field = '' // re-set this
		rec.table = mainState.rec.table
		arr.tab_orig = null
		callServer('init')
	}
})

function addSavedQuery(name) {
	const queryArr = arr.query[rec.table]
	const value = nc.clone(queryArr) // nc.clone(queryArr, ['table_field'])
	rec.saved_query = value
	arr.saved_query.splice(0, 0, { show: name, value: value })
	if (nc.isArray(arr.saved_query) && arr.saved_query.length > rec.saved_query_count) {
		arr.saved_query.splice(rec.saved_query_count, 10) // delete from end
	}
}

function setQueryArray() {
	if (!arr.default_query[0].field) {
		arr.default_query[0].field = rec.field
	}
	const queryArr = arr.query[rec.table]
	if (queryArr == null || !nc.isArray(queryArr)) {
		arr.query[rec.table] = nc.clone(arr.default_query)
	} else {
		arr.query[rec.table] = queryArr
		if (queryArr.length > 0 && (queryArr[0].query_value1 || queryArr[0].operator !== '=')) {
			let save = true
			if (arr.saved_query.length > 0) {
				for (const item of arr.saved_query)
					if (nc.isEqual(queryArr, item.value, ['table_field'])) {
						save = false
						break
					}
			}
			if (save) {
				let name = queryArr[0].query_value1 // arr.saved_query.length + 1 + '. ' + queryArr[0].query_value1
				if (queryArr[0].query_value2) {
					name += ' - ' + queryArr[0].query_value2
				}
				name += ` (${queryArr.length})`
				addSavedQuery(name)
			}
		}
	}
	const tblField = arr.table_field[rec.table]
	if (tblField) {
		for (const item of arr.query[rec.table]) {
			item.table_field = tblField
			if (!item.field) {
				item.field = rec.field // item.field is '' or null
			} else {
				rec.field = item.field // set rec.field to last in query array
			}
		}
	}
	if (nc.isArray(arr.query[rec.table])) {
		setGridStyle(arr.query[rec.table].length, 'remove')
	}
}

function loadParam(callParam) {
	if (!rec.table) {
		const param = nc.getParam()
		if (param && param.rec.table) {
			rec.table = param.rec.table
		} else {
			rec.table = ''
		}
	} else {
		const param = nc.getParam('nc-list-form')
		if (param && param[rec.table]) {
			callParam.rec = Object.assign(callParam.rec, param[rec.table].rec)
			param[rec.table].rec = undefined
			callParam = Object.assign(callParam, param[rec.table])
		}
	}
}

function setCallParamRec(callParam, option) {
	callParam.rec.tab = rec.tab
	const arrRec = nc.findRecFromArr(arr.tab, 'value', rec.tab)
	callParam.rec.query_name = arrRec && arrRec.query_name ? arrRec.query_name : ''
	callParam.rec.table = rec.table
	if (arr.query[rec.table] == null) {
		callParam.rec.query = nc.clone(arr.default_query)
		// delete callParam.rec.query[0].query_dropdown
	} else {
		callParam.rec.query = []
		for (const item of arr.query[rec.table]) {
			callParam.rec.query.push({
				field: item.field || '',
				selection_type: item.selection_type,
				operator: item.operator,
				query_value1: item.query_value1,
				query_value2: item.query_value2
			})
		}
	}
	allSelected.value = option === 'all'
	callParam.rec.all_records = allSelected.value
	/* if (!nc.isEqual(callParam.rec, prevCallParamRec)) {
				saveParam()
			} */
}

function setTabCount() {
	if (state.grid.list.info && state.grid.list.info.row_count != null) {
		rowsLoaded.value = state.grid.list.info.row_count || 0
		rowsInSelection.value = state.grid.list.info.row_count_total || 0
		rowsInTable.value = state.grid.list.info.rowCountTable || 0
		let rows = rowsLoaded.value.toLocaleString() // rowsInSelection.value.toLocaleString()
		if (state.new_record && state.new_record.length > 0) {
			rows += ` + ${state.new_record.length.toLocaleString()} = ${(rowsInSelection.value + state.new_record.length).toLocaleString()}`
		}
		arr.tab_orig = arr.tab_orig || nc.clone(arr.tab) // null arr.tab_orig on table change
		const arrRecOrig = nc.findRecFromArr(arr.tab_orig, 'value', rec.tab)
		const arrRec = nc.findRecFromArr(arr.tab, 'value', rec.tab)
		if (arrRec && arrRec.show && arrRecOrig && arrRecOrig.show) {
			let pos = arrRecOrig.show.indexOf('rowsInSelection')
			const pos2 = arrRecOrig.show.indexOf('rowsInTable')
			if (pos2 > 0 && pos2 < pos) {
				pos = pos2
			}
			if (pos > 0) {
				arrRecOrig.show = arrRecOrig.show.substring(0, pos - 1)
			}
			arrRec.show = arrRecOrig.show + rec.table_count_format.replace('rowsInSelection', `${rows}`).replace('rowsInTable', `${rowsInTable.value.toLocaleString()}`)
		}
	}
}

function callServer(action, option) {
	const return_object = []
	let callParam = nc.clone(baseCallParam)
	if (action === 'init') {
		loadParam(callParam)
		return_object.push('load_batch_size')
		return_object.push('arr.tab')
		if (!mainState.rec.table) {
			return_object.push('arr.table')
		}
		if (rec.table !== prevTable || rec.table === '') {
			prevTable = rec.table
			return_object.push('arr.table_field')
		}
		action = 'query'
	}
	return_object.push('grid')
	callParam.action = action
	setCallParamRec(callParam, option)
	callParam.return_object = return_object
	if (option && typeof option === 'object') {
		for (let key in option) {
			callParam[key] = option[key]
		}
	}
	function serverCallback(ret) {
		state.new_record = []
		loadRows(ret)
		if (ret.rec) {
			rec.field = peg.parseBefore(rec.field, ',') // todo: temporary fix for multiple fields
			setQueryArray()
			mainState.arr.table = arr.table
			mainState.rec.table = rec.table
			mainState.rec.schema = rec.schema
			setListDataRec(state.grid.list.data && state.grid.list.data[0])
			if (arr.tab) {
				// this should run only when arr.tab changes
				arr.tab = arr.tab.map(item => {
					if (item.query_name && !item.icon) item.icon = 'filter'
					return item
				})
			}
		}
	}
	nc.callServer(state, area, callParam, serverCallback)
}

function loadRows(ret) {
	// ret.grid or state.grid does not contain state.grid.grid until redraw
	if (ret.grid && ret.grid.list && ret.grid.list.info) {
		nc.grid.deactivateAll(state, area)
		state.new_record = state.new_record || mainState.list.new_record || []
		if (state.new_record.length > 0) {
			const removeIdx = []
			let idx = 0
			for (const item of state.new_record) {
				if (item.record_id == '') {
					removeIdx.push[idx]
				} else {
					state.grid.list.data.push(item)
				}
				idx++
			}
			for (const idx of removeIdx) {
				state.new_record.splice(idx, 1)
			}
		}
		setTabCount()
	}
}

function setListDataRec(listDataRec) {
	if (listDataRec) {
		rec.row_index = listDataRec.idx // not js 0-based but 1-based
		rec.start_row_index = rec.row_index // not js 0-based but 1-based
		if (nc.grid.getFirstDisplayedRow) {
			rec.first_displayed_row = nc.grid.getFirstDisplayedRow(state, area)
		} else {
			rec.first_displayed_row = 0
		}
		if (rec.first_displayed_row > 0) {
			rec.first_displayed_row += 11 // some bug in ag-grid?
		}
		if (listDataRec) {
			rec.record_id = listDataRec.record_id
			if (rec.record_id == null) {
				rec.record_id = listDataRec[`record_id${recordTypeSeparator}${rec.record_type || listDataRec.record_type}`]
			}
		} else {
			rec.record_id = null
		}
	}
}

function getEventData(event) {
	/* if (event?.detail?.recid) {
		// w2 grid
		const listDataRec = state.grid.list.data[parseInt(event.detail.recid) - 1]
		return listDataRec
	} */
	return event?.data // || event?.detail?.model // event.data for ag-grid and event.detail.model for revo grid
}

function setGridStyle(arrLength, remove) {
	const queryEm = (arrLength - 1) * 2.7 + 14.5 // 2.9
	gridStyle.value = `width: 100%; min-height: 4.4em; height: calc(100vh - ${queryEm}em)`
	if (remove) {
		gridStyle.value += '; transition: height 0.001s' // ease-in
	}
}

function setQueryDropdown(index, value) {
	let queryArr = arr.query_dropdown_field && nc.recData(arr.query_dropdown_field, value)
	if (nc.isArray(queryArr) && queryArr.length > 0) {
		queryArr = nc.clone(queryArr)
		arr.query_dropdown = queryArr
		arr.query[rec.table][index].query_dropdown = queryArr
		arr.query[rec.table][index].query_value1 = ''
		arr.query[rec.table][index].query_value2 = ''
	} else {
		delete arr.query[rec.table][index].query_dropdown
	}
	arr.query[rec.table][index].operator = arr.default_query[0].operator
}

// eslint-disable-next-line no-unused-vars
function gridContextMenu(event) {
	console.debug(`🚀 ~ gridContextMenu:`, event)
}

// eslint-disable-next-line no-unused-vars
function gridCellValueChanged(area, node, data, newValue, oldValue, colId, rowIndex) {
	const gridData = state.grid.list.data
	nc.gridSetNewChangeRecord(gridData, data, rowIndex) // need to set value before cleaned
	if (typeof newValue === 'string') {
		const cleaned = peg.cleanBeforeAfterDoubleSpace(newValue)
		if (cleaned !== newValue) {
			newValue = cleaned
			nc.recDataSet(data, colId, newValue)
			nc.gridSetNewChangeRecord(gridData, data, rowIndex)
		}
	}
	nc.gridSetChangeRecord(data, colId, oldValue, newValue)
	nc.grid.refreshCells(state, area, node)
	// state.grid.list.data[rowIndex-1] = data

	/* 	const origValue = nc.recData(loadedRec, fieldName)
			if (origValue !== newValue) {
				nc.recDataSet(changeRecord.value, fieldName, newValue)
			} else {
				const clearEmptySubkeyLevel = 2 // tbl.json_data.xxx
				nc.recDataSet(changeRecord.value, fieldName, undefined, clearEmptySubkeyLevel)
			}
			const tblRec = changeRecord.value
			saveEnabled.value = tblRec && !nc.isEmptyObject(tblRec)
			mainState.input.save_enabled = saveEnabled.value */
}

// eslint-disable-next-line no-unused-vars
function gridRowClicked(area, rowIndex, event, selected) {
	if (selected) {
		setListDataRec(getEventData(event))
	}
	// let activatedArr = nc.grid.activatedRecordArr(state, area)
	// console.debug('gridRowClicked', area, rowIndex, event, selected, activatedArr)
}

function gridRowDoubleClicked(area, rowIndex, event) {
	nc.grid.stopEditing(state, area, event, true)
	nc.grid.activateRows(state, area, rowIndex, false) // no-scroll
	setListDataRec(getEventData(event))
	if (rec.record_id == null) {
		message.setWarning(state, `Selected array item does not contain record_id -field, table prefix: '${rec.table_prefix}'`)
	} else {
		delete rec.return
		/* for (var key in listDataRec) {
							// copy all subkeys for input
							if (nc.isObject(listDataRec[key])) {
								// if (key === listRec.table_prefix) {
								rec[key] = nc.clone(listDataRec[key])
							}
						} */
		nc.gotoUrl(state, 'input') // dynamic component will make rest call and create input components: nc-input-form and table's input page
	}
}

// eslint-disable-next-line no-unused-vars
function selectSavedQuery(value, prevValue) {
	if (value !== prevValue) {
		if (rec.saved_query === 'save_query') {
			const name = prompt('Anna haun nimi:', '')
			if (name != null) {
				addSavedQuery(name)
			}
			return
		}
		if (nc.isArray(rec.saved_query) && rec.saved_query.length > 0) {
			arr.query[rec.table] = nc.clone(rec.saved_query)
			setGridStyle(arr.query[rec.table].length)
		}
	}
}

// eslint-disable-next-line no-unused-vars
function query(event, option) {
	if (event) {
		event.preventDefault()
		if (event.key === 'Enter') {
			callServer('query', option)
		}
	} else {
		callServer('query', option)
	}
}

// eslint-disable-next-line no-unused-vars
function queryValue2Disabled(index) {
	if (!arr.query[rec.table] && arr.query[rec.table][index]) {
		return true
	}
	return ['!==', '==', '<', '<=', '>', '>='].includes(arr.query[rec.table][index].operator)
}

// eslint-disable-next-line no-unused-vars
function setQueryItem(key, index, value) {
	if (typeof value === 'object' && value.target) {
		value = value.target.value // value is event
	}
	const queryRec = arr.query[rec.table][index]
	queryRec[key] = value
	if (key === 'field' && rec.field !== value) {
		rec.field = value
		setQueryDropdown(index, value)
	}
}

// eslint-disable-next-line no-unused-vars
function addQueryRow(index) {
	const addRec = nc.clone(arr.query[rec.table][index])
	if (addRec.selection_type === 'new') {
		addRec.selection_type = rec.new_selection_type
	}
	setGridStyle(arr.query[rec.table].length + 1)
	index++
	arr.query[rec.table].splice(index, 0, addRec)
}

// eslint-disable-next-line no-unused-vars
function removeQueryRow(index) {
	if (!nc.isArray(arr.query[rec.table])) {
		console.warn('arr.query[rec.table] is not an array')
		return
	}
	if (index < 1 && arr.query[rec.table].length === 1) {
		arr.query[rec.table][0].query_value1 = ''
		arr.query[rec.table][0].query_value2 = ''
		arr.query[rec.table][0].field = arr.default_query[0].field
		setQueryDropdown(index, '')
	} else {
		arr.query[rec.table].splice(index, 1)
		setTimeout(() => {
			setGridStyle(arr.query[rec.table].length, 'remove')
		}, 210) // NOTE: 200ms = 0.2s of nc-fade-fast transition, + x ms to be just after query row removal transition
	}
	if (arr.query[rec.table][0].selection_type !== 'new') {
		arr.query[rec.table][0].selection_type = 'new'
	}
}

// eslint-disable-next-line no-unused-vars
function gridCellKeyDown(area, rowIndex, event) {
	if (!event.event) {
		gridRowDoubleClicked(area, rowIndex, event)
	} else {
		const cmdOrCtrlKey = event.event && nc.isMac() ? event.event.metaKey : event.event.ctrlKey
		if (event.event.key === 'Enter' && cmdOrCtrlKey === true) {
			gridRowDoubleClicked(area, rowIndex, event)
			// event.event.preventDefault()// these do
			// event.event.stopPropagation()
		}
	}
}

// eslint-disable-next-line no-unused-vars
function gridToolSelected(area, action) {
	nc.gridToolSelected(state, area, action)
}

// eslint-disable-next-line no-unused-vars
function importFile(fileName, data) {
	nc.gridImportFile(state, area, fileName, data, setTabCount)
}
