// form/nc/report/nc-report/delivery-reliability/delivery-reliability.js

let nc // , dt, message, peg
let state, rec, arr, hdr
export function setState(nc_, state_) {
	nc = nc_
	state = state_
	rec = state.rec
	arr = state.arr
	hdr = state.hdr
	// dt = nc.dt
	// message = nc.message
	// peg = nc.peg
}

// export function isExternalFilterPresent() {}
// export function doesExternalFilterPass(node) {}

export function setRowData(rowData) {
	rec.show_date_row = true
	rec.show_grid2 = false
	const recData = nc.recData
	const dayDifference = nc.dt.dayDifference
	// const productGroupAllValue = rec.product_group
	// called from layout html
	// const retArr = nc.map(state, rowData, 'day_difference', param) // todo: create nc.map() function
	const dateFrom = rec.table === 'sales' ? rec.sales_calculate_date : rec.purchase_calculate_date
	const arrName = rec.table === 'sales' ? 'sales_calculate_date' : 'purchase_calculate_date'
	const arrItem = nc.recordArrayRecord(arr[arrName], 'value', dateFrom)
	hdr.delivery_reliability.used_delivery_date = arrItem?.show || 'unknown date'
	let targetDateName
	if (arrItem && arrItem.show2) {
		targetDateName = arrItem.show2
	}
	const compareDateFrom = rec.table === 'sales' ? rec.sales_compare_date : rec.purchase_compare_date
	const compareArrName = rec.table === 'sales' ? 'sales_calculate_date' : 'purchase_calculate_date'
	const compareArrItem = nc.recordArrayRecord(arr[compareArrName], 'value', compareDateFrom)
	hdr.delivery_reliability.used_compare_date = compareArrItem?.show || 'unknown date'
	let compareDateName
	if (compareArrItem && compareArrItem.show2) {
		compareDateName = compareArrItem.show2
	}
	const errorDetail = state.grid.error_detail.data
	state.grid.error_detail.option.table_prefix = 'ordr'
	errorDetail.length = 0
	let actualDate, targetDate
	rowData.map(ordr => {
		ordr.calc = {}
		actualDate = recData(ordr, compareDateFrom)
		ordr.calc.compare_date_name = compareDateName || compareDateFrom.replaceAll('json_data.', ' ').replaceAll('_', ' ')
		if (actualDate <= '1970-01-01') {
			if (ordr.actual_delivery_date <= '1970-01-01') {
				actualDate = ordr.delivery_date
				ordr.calc.compare_date_name = 'delivery date'
			} else {
				actualDate = ordr.actual_delivery_date
				ordr.calc.compare_date_name = 'actual delivery date'
			}
		}
		ordr.calc.compare_date = targetDate
		targetDate = recData(ordr, dateFrom)
		if (targetDate > '1970-01-01') {
			ordr.calc.target_date = targetDate
			ordr.calc.target_date_name = targetDateName || dateFrom.replaceAll('json_data.', ' ').replaceAll('_', ' ')
			ordr.calc.day_difference = dayDifference(targetDate, actualDate)
		} else if (ordr.confirmed_delivery_date > '1970-01-01') {
			ordr.calc.target_date = ordr.confirmed_delivery_date
			ordr.calc.target_date_name = 'confirmed delivery date'
			ordr.calc.day_difference = dayDifference(ordr.confirmed_delivery_date, actualDate)
		} else if (ordr.delivery_date > '1970-01-01') {
			ordr.calc.target_date = ordr.delivery_date
			ordr.calc.target_date_name = 'delivery date'
			ordr.calc.day_difference = dayDifference(ordr.delivery_date, actualDate)
		} else {
			ordr.calc.target_date = actualDate
			ordr.calc.target_date_name = ''
			ordr.calc.day_difference = 0
			// todo: web tilaus, toteutunutta päivää verrataan vaan toimituspäivään
			// ignore_customer as an array
			if (ordr.ord?.company_id && ordr.ord.company_id !== rec.ignore_customer) {
				errorDetail.push(ordr)
				// `Error in order row: ${ordr.order_id}.${ordr.row_number}, delivery date = ${ordr.delivery_date}, actual delivery date = ${ordr.actual_delivery_date}, confirmed delivery date = ${ordr.confirmed_delivery_date}, delivery state = ${ordr.delivery_state}`
			}
		}
		rec.days_late_allowed = parseInt(rec.days_late_allowed) || 0
		if (rec.days_late_allowed !== 0) {
			// && ordr.calc.target_date_name === 'delivery date'
			if (ordr.calc.day_difference - rec.days_late_allowed > 0) {
				ordr.calc.day_difference -= rec.days_late_allowed
			} else {
				ordr.calc.day_difference = 0
			}
		}
		return ordr
	})
}

export function drawChart(rowData) {
	let count = 0
	let inTimeCount = 0
	// let date
	const data = rec[rec.tab].chart_data
	if (!data) {
		return
	}
	data.forEach(item => {
		item.deliveries = 0
	})
	const translate = state.hdr?.[rec.tab]
	data[0].label = translate?.ahead_of_time
	data[1].label = translate?.on_time
	data[data.length - 1].label = translate?.over + ' ' + data[data.length - 1].start
	let filteredData = data
		.map(function (item) {
			item.deliveries = rowData.reduce(function (sum, ordr) {
				// use nc.arrayStartStopRecord()
				if ((item.start == null || ordr.calc.day_difference > item.start) && (item.stop == null || ordr.calc.day_difference <= item.stop)) {
					item.deliveries = item.deliveries + 1
					count = count + 1
					if (item.stop !== null && item.stop <= 0) {
						inTimeCount = inTimeCount + 1
					}
					sum = sum + 1
				}
				return sum
			}, 0)
			return item
		})
		.map(function (item) {
			item.category = item.label + ' (' + nc.percent(item.deliveries, count) + '%)'
			return item
		})
	if (count !== rowData.length) {
		message.setError(state, `chart deliveries count ${count} is not equal to data row count ${rowData.length}`)
	}
	rec.number_of_deliveries = count
	rec.delivery_percent = nc.percent(inTimeCount, count)
	// set chart
	const chart = nc.clone(rec[rec.tab].chart.option)
	chart.series[0].name = translate?.days_late
	chart.dataset[0].source = filteredData
	chart.yAxis[0].name = translate?.deliveries
	rec.chart.option = chart
	// headers
	hdr.report_name = rec.report_type === 'delivery-sales' ? hdr.delivery_reliability.sales_delivery_reliability : hdr.delivery_reliability.purchase_delivery_reliability
	rec.report_header1 = hdr.delivery_reliability?.used_delivery_date + ' / ' + hdr.delivery_reliability?.used_compare_date
	if (rec.days_late_allowed !== 0) {
		rec.report_header1 += ', ' + hdr.delivery_reliability.days_late_allowed.toLowerCase() + ': ' + rec.days_late_allowed
	}
	rec.report_header2 =
		hdr.delivery_reliability.number_of_deliveries +
		': ' +
		rec.number_of_deliveries +
		', ' +
		hdr.delivery_reliability.delivery_reliability_percent +
		': ' +
		rec.delivery_percent +
		'%' +
		(rec.selected_company ? ' - ' + rec.selected_company : '') // rec.selected_company contains also product_group if it is selected
	return rowData
}
