// form/nc/report/nc-report/nc-report.js
// import { drawChart } from '/plugin/nc-report/delivery-reliability.js'
// import { drawChart } from '/plugin/nc-report/reclamation.js'

function pageInit(ret) {
	/* const selectionId = nc.searchParameter('id')
	if (selectionId) {
		rec.query_type = 'selection'
		rec.selection_id = selectionId
	} else { */
	rec.query_type = 'time_period'
	rec.selection_id = ''
	// }
	if (grid.nats_name && grid.report1) {
		const unwatch = watch(grid.report1, () => {
			if (grid.report1.data.length > 0) {
				unwatch()
				drawChart()
			}
		})
	}
	callServerCallback(ret)
}

const reportCodeCache = {}
function reportCode() {
	return reportCodeCache[rec.tab]
}
function getReportCode(callback) {
	if (callback && reportCodeCache[rec.tab]) {
		callback(reportCodeCache[rec.tab]) // note: no return values from callback function
	}
	let url = nc.urlPath()
	const fileName = peg.replace(rec.tab, '_', '-')
	url += `/plugin/nc-report/${fileName}.js`
	return import(/* @vite-ignore */ url)
		.then(code => {
			if (typeof code.setState === 'function') {
				code.setState(nc, state)
			} else {
				message.setError(state, `code setState() for report page '${rec.tab}' is not a function`)
			}
			reportCodeCache[rec.tab] = code
			if (callback) {
				callback(reportCodeCache[rec.tab])
			}
		})
		.catch(err => {
			message.setError(state, `Error loading report code from url: ${url}, error: ${err}`)
		})
}
getReportCode() // load first tab code early

let prevTab = rec.tab
const tabCache = nc.createTabCache(rec.tab_field)
arr.tab.forEach(function (tab) {
	rec.report_type = rec[tab.value].report_type
})
tabCache.save(prevTab, rec)
arr.report_type = arr[prevTab].report_type
// eslint-disable-next-line no-unused-vars
function changeDate() {
	tabCache.save(rec.tab, rec)
	drawChart()
}

function initTabRec(subRec, mainRec) {
	if (subRec.run) {
		for (let i = 0; i < subRec.run.length; i++) {
			const entry = subRec.run[i]
			if (entry.result == null) {
				continue
			}
			const param = (entry.parameter || []).map(function (p) {
				if (typeof p === 'string') {
					if (subRec[p] != null) return subRec[p]
					if (mainRec[p] != null) return mainRec[p]
				}
				return p
			})
			if (entry.function === 'currentDateString') {
				subRec[entry.result] = new Date().toISOString().split('T')[0]
			} else if (entry.function === 'ymdAddDateString') {
				const d = new Date(param[0])
				d.setFullYear(d.getFullYear() + (param[1] || 0))
				d.setMonth(d.getMonth() + (param[2] || 0))
				d.setDate(d.getDate() + (param[3] || 0))
				subRec[entry.result] = d.toISOString().split('T')[0]
			} else if (entry.function === 'currentYearStartString') {
				subRec[entry.result] = (new Date().getFullYear() + (param[0] || 0)) + '-01-01'
			}
		}
	}
	for (let i = 0; i < rec.tab_field.length; i++) {
		const key = rec.tab_field[i]
		if (subRec[key] != null) {
			mainRec[key] = subRec[key]
		}
	}
}

// eslint-disable-next-line no-unused-vars
function tabChanged(tab) {
	tabCache.save(prevTab, rec)
	if (!tabCache.restore(tab, rec)) {
		initTabRec(rec[tab], rec)
		tabCache.save(tab, rec)
	}
	arr.report_type = arr[tab].report_type
	prevTab = tab
	callServer()
}

let updateTimeout
function callServerCallback() {
	// rec.query_type = queryType // restore after init call
	// rec.selection_id = selectionId
	rec.query_start_date = rec.start_date // in html, update button as red if out of date range
	rec.query_end_date = rec.end_date
	rec.query_warning = ''
	drawChart() // will call setDropdown(state, data)
	if (updateTimeout) {
		clearTimeout(updateTimeout)
	}
	if (rec.update_seconds > 0) {
		updateTimeout = setTimeout(() => {
			callServer('init')
		}, rec.update_seconds * 1000)
	}
}

function callServer() {
	// queryType = rec.query_type // save now and restore after rest call
	// selectionId = rec.selection_id
	// if (action === 'update') {
	let param = {
		return: {
			grid: [
				{
					name: 'report1',
					tab: rec[rec.tab]?.grid_1 || rec.report_type
				}
			]
		}
	}
	if (rec[rec.tab]?.grid_2) {
		param.return.grid.push({
			name: 'report2',
			tab: rec[rec.tab].grid_2
		})
	}
	if (rec.query_type === 'selection') {
		param.selection_id = rec.selection_id
	} else {
		param.start_date = rec.start_date // dt.dateToString(rec.start_date),
		param.end_date = rec.end_date // dt.dateToString(rec.end_date)
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/report/nc-report/grid.json',
			parameter: param
		},
		callServerCallback
	)
}

function setDropdown(state, data) {
	let date, arrItem
	const companyFound = {}
	const filteredData = data.filter(function (item) {
		// filter out data that is not in selected date range
		if (rec.query_type !== 'time_period') {
			return true
		}
		date = item.calc.target_date // nc.parseDate(item.calc.target_date)
		item.calc.in_date_range = date >= rec.start_date && date <= rec.end_date
		return item.calc.in_date_range
	})
	let companyId
	const dropdown = filteredData.reduce(function (result, item) {
		companyId = item.company_id != null ? item.company_id : item.ord.company_id
		if (!companyFound[companyId]) {
			arrItem = {
				count: 1,
				show: item.co.name + ' - ' + companyId,
				value: companyId
			}
			companyFound[companyId] = arrItem
			result.push(arrItem)
		} else {
			arrItem = companyFound[companyId]
			arrItem.count = arrItem.count + 1
		}
		return result
	}, [])
	dropdown.forEach(function (arrItem) {
		arrItem.show = arrItem.show + ' (' + arrItem.count + ')'
	})
	dropdown.sort(nc.dynamicSort('show', '>'))
	dropdown.unshift({
		// unshift adds to start of array
		show: state.hdr?.all_companies + ' (' + filteredData.length + ')',
		value: ''
	})
	nc.setArr(state, 'company', dropdown)
	return setProductGroupDropdown(state, filteredData)
}

const productGroupAllValue = rec.product_group
function setProductGroupDropdown(state, filteredData) {
	if (rec.company) {
		let companyId
		filteredData = filteredData.filter(function (item) {
			companyId = item.company_id != null ? item.company_id : item.ord.company_id
			return companyId === rec.company
		})
	}
	const productGroupFound = {}
	let arrItem
	const dropdown = filteredData.reduce(function (result, item) {
		if (!productGroupFound[item.pr.product_group]) {
			arrItem = {
				count: 1,
				show: item.pr.product_group,
				value: item.pr.product_group
			}
			productGroupFound[item.pr.product_group] = arrItem
			result.push(arrItem)
		} else {
			arrItem = productGroupFound[item.pr.product_group]
			arrItem.count = arrItem.count + 1
		}
		return result
	}, [])
	const dropdownValueIdx = {}
	dropdown.forEach(function (arrItem) {
		arrItem.show = arrItem.show + ' (' + arrItem.count + ')'
		dropdownValueIdx[arrItem.value] = true
	})
	dropdown.sort(nc.dynamicSort('show', '>'))
	dropdown.unshift({
		// unshift adds to the start of the array
		show: state.hdr.all_companies + ' (' + filteredData.length + ')',
		value: productGroupAllValue
	})
	rec.selected_company = rec.company ? nc.recordArrayField(arr.company, 'value', rec.company, 'show') : ''
	rec.selected_company = nc.peg.parseBefore(rec.selected_company, ' (')
	if (rec.product_group !== productGroupAllValue) {
		const productGroup = nc.recordArrayField(dropdown, 'value', rec.product_group, 'show')
		if (rec.selected_company) {
			rec.selected_company += ', ' + state.hdr.delivery_reliability.product_group_prefix + peg.parseBefore(productGroup, ' (')
		} else {
			rec.selected_company = state.hdr.delivery_reliability.product_group_prefix + peg.parseBefore(productGroup, ' (')
		}
		filteredData = filteredData.filter(function (item) {
			return item.pr.product_group === rec.product_group
		})
	}
	if (!dropdownValueIdx[rec.product_group]) {
		rec.product_group = productGroupAllValue
	}
	nc.setArr(state, 'product_group', dropdown)
	return filteredData
}

function drawChart() {
	// also called from layout html
	// wait for grids to draw first
	getReportCode(code => {
		const rowData = state.grid?.report1?.data
		if (!rowData) {
			return
		}
		code.setRowData(rowData)
		const filteredData = setDropdown(state, rowData)
		// nc.grid.updateFilter(state, 'report1')
		setTimeout(() => {
			// wait for grids to set idx on records
			code.drawChart(filteredData)
			rec.update_chart = rec.update_chart + 1 // update chart
			nc.grid.redrawRows(state, 'report1')
			if (rec.show_grid2) {
				nc.grid.redrawRows(state, 'report2')
			}
		}, 10)
	})
}

// eslint-disable-next-line no-unused-vars
function isExternalFilterPresent() {
	return true
	/* if (rec.company !== '' || rec.product_group !== '') {
		return true
	}
	const code = reportCode()
	if (!code) {
		return false
	}
	if (code.isExternalFilterPresent != null) {
		if (typeof code.isExternalFilterPresent === 'function') {
			return code.isExternalFilterPresent()
		} else {
			message.setError(state, `code isExternalFilterPresent() for report page '${rec.tab}' is not a function`)
		}
	}
	return false
	*/
}

// eslint-disable-next-line no-unused-vars
function doesExternalFilterPass(node) {
	if (node.data.calc?.in_date_range === false) {
		return false
	} else if (rec.company !== '' && (node.data.company_id || node.data.ord.company_id) !== rec.company) {
		return false
	} else if (rec.product_group !== '' && node.data.pr.product_group !== rec.product_group) {
		return false
	}
	const code = reportCode()
	if (!code) {
		return true
	}
	if (code.doesExternalFilterPass != null) {
		if (typeof code.doesExternalFilterPass === 'function') {
			return code.doesExternalFilterPass(node)
		} else {
			message.setError(state, `code doesExternalFilterPass() for report page '${rec.tab}' is not a function`)
		}
	}
	return true
	// const find = rec.company.toLowerCase()
	// return node.data.product_id.toLowerCase().includes(find) || node.data.product_id.toLowerCase().includes(find) || node.data.name.toLowerCase().includes(find)
}

pageInit()
