// form/nc/report/nc-report/reclamation/reclamation.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() {
	if (rec[rec.tab].reclamation_type !== '' || rec[rec.tab].reclamation_state !== '') {
		return true
	}
	return false
}
 */

export function reclamationFilter(item) {
	if (rec[rec.tab].reclamation_type !== '' && item.reclamation_type !== rec[rec.tab].reclamation_type) {
		return false
	} else if (rec[rec.tab].reclamation_state !== '' && item.reclamation_state !== rec[rec.tab].reclamation_state) {
		return false
	} else if (rec[rec.tab].calculation_type !== '' && item.calculation_type !== rec[rec.tab].calculation_type) {
		return false
	}
	return true
}

function arrayIndex(arr) {
	arr.forEach(item => {
		item.count = 0
		if (item.orig_show == null) {
			item.orig_show = item.show // save original show value
		}
	})
	return nc.createIndex(arr, 'value').index
}

function setIndexCount(idx, value, arr) {
	const arrItem = idx[value]
	if (arrItem) {
		arrItem.count++
	} else {
		// add unknown data to array
		arr.push({
			show: value + ' (please, add this to dropdown)',
			value: value,
			count: 1
		})
		idx[value] = arr[arr.length - 1] // set index to last item
	}
	arr[0].count++ // increment all count
}

function setShowCount(arr) {
	arr.forEach(item => {
		item.show = item.orig_show + ' (' + item.count + ')'
	})
}

function setDropDownAndFilter(rowData) {
	const reclamationTypeIdx = arrayIndex(arr[rec.tab].reclamation_type)
	const reclamationStateIdx = arrayIndex(arr[rec.tab].reclamation_state)
	const calculationTypeIdx = arrayIndex(arr[rec.tab].calculation_type)
	let allow
	let filteredData = rowData.filter(item => {
		setIndexCount(reclamationTypeIdx, item.reclamation_type, arr[rec.tab].reclamation_type)
		setIndexCount(reclamationStateIdx, item.reclamation_state, arr[rec.tab].reclamation_state)
		setIndexCount(calculationTypeIdx, item.calculation_type, arr[rec.tab].calculation_type)
		allow = true
		if (rec[rec.tab].reclamation_type !== '' && item.reclamation_type !== rec[rec.tab].reclamation_type) {
			allow = false
		} else if (rec[rec.tab].reclamation_state !== '' && item.reclamation_state !== rec[rec.tab].reclamation_state) {
			allow = false
		} else if (rec[rec.tab].calculation_type !== '' && item.calculation_type !== rec[rec.tab].calculation_type) {
			allow = false
		}
		return allow
	})
	setShowCount(arr[rec.tab].reclamation_type)
	setShowCount(arr[rec.tab].reclamation_state)
	setShowCount(arr[rec.tab].calculation_type)
	return filteredData
}

export function doesExternalFilterPass(node) {
	if (node.grid.info?.query_table === 'reclamation') {
		return reclamationFilter(node.data)
	}
	return true
}

export function setRowData(rowData) {
	rec.show_date_row = false
	rec.show_grid2 = true
	const dt = nc.dt
	const recData = nc.recData
	const dateField = 'create_time' // rcl.create_time
	const nullDate = dt.parseDate('1970-01-01')
	let date
	rowData.map(rcl => {
		// calculate dates to all data
		rcl.calc = {}
		date = recData(rcl, dateField)
		if (date > '1970-01-01') {
			rcl.calc.target_date = date
			rcl.calc.date = new Date(date)
			rcl.calc.year = rcl.calc.date.getFullYear()
			rcl.calc.month = rcl.calc.date.getMonth() + 1
		} else {
			rcl.calc.target_date = '1970-01-01'
			rcl.calc.date = new Date(nullDate.getTime())
			rcl.calc.year = rcl.calc.date.getFullYear()
			rcl.calc.month = rcl.calc.date.getMonth() + 1
		}
		return rcl
	})
}

export function drawChart(rowData) {
	const chart = nc.clone(rec[rec.tab].chart.option)
	const data = nc.clone(chart.dataset[0].source)
	if (!data) {
		return
	}
	rowData = setDropDownAndFilter(rowData)
	data.forEach(item => {
		item.count = 0
		item.delivery_amount = 0
		item.failed_amount = 0
		item.rejected_amount = 0
		item.repair_amount = 0
		item.total_charges = 0
		item.percent = 0
	})
	const yearData = {}
	const errorDetail = state.grid.error_detail.data
	state.grid.error_detail.option.table_prefix = 'rcl'
	errorDetail.length = 0
	const nullDate = dt.parseDate('1970-01-01')
	let item, orderId, ordArr, ordr, rowNumber
	const salesOrderRowData = state.grid.report2.data
	const salesOrderIdx = nc.createIndexArray(salesOrderRowData, 'order_id')
	rowData.map(rcl => {
		// calculate values from filtered data
		// todo: reclamation percentage and value data calculations here
		if (rcl.calc.date > nullDate) {
			if (yearData[rcl.calc.year] == null) {
				yearData[rcl.calc.year] = nc.clone(data) // 12 months
			}
			item = yearData[rcl.calc.year][rcl.calc.month - 1]
			orderId = peg.parseBefore(rcl.sales_order_id, '/')
			rowNumber = Number(peg.parseAfter(rcl.sales_order_id, '/')) // Number('') is 0
			ordArr = salesOrderIdx[orderId]
			item.count++
			if (ordArr) {
				ordr = null
				for (let rec of ordArr) {
					if (rowNumber && rec.row_number === rowNumber) {
						// if rowNumber is not 0
						ordr = rec
						break
					} else if (!ordr && rec.product_id === rcl.product_id) {
						ordr = rec
					}
				}
				if (ordr) {
					// todo: logic here by rec.report_type
					rcl.link_rec_arr_idx = ordr.idx
					ordr.link_rec_arr_idx = rcl.idx
					item.delivery_amount += ordr.delivery_amount
					item.failed_amount += rcl.failed_amount
					item.rejected_amount += rcl.rejected_amount
					item.repair_amount += rcl.repair_amount
					item.total_charges += rcl.total_charges
					item.percent = item.failed_amount / item.delivery_amount
				} else {
					errorDetail.push(rcl)
				}
			}
		} else {
			errorDetail.push(rcl)
		}
		return rcl
	})
	rec.number_of_deliveries = '' // clean subheaders
	rec.delivery_percent = ''
	const yearArr = []
	for (const [key, value] of Object.entries(yearData)) {
		yearArr.push({
			year: key,
			data: value
		})
	}
	yearArr.sort((a, b) => a.year - b.year)
	// set chart
	const defaultSerie = nc.clone(chart.series?.[0])
	const defaultDataset = nc.clone(chart.dataset[0])
	if (!defaultSerie) {
		message.setWarning('chart series is missing')
	} else if (!defaultDataset) {
		message.setWarning('chart dataset is missing')
	} else {
		chart.series.length = 0
		chart.dataset.length = 0
		let index = 0
		let serie, dataset, year, prevCount
		for (let i = 0; i < yearArr.length; i++) {
			year = yearArr[i]
			prevCount = 0
			// todo: logic here by rec.report_type
			year.data.forEach(item => {
				item.cumulative = prevCount + item.count
				prevCount = item.cumulative
			})
			// count bar
			serie = nc.clone(defaultSerie)
			serie.name = year.year // + ' ' + nc.l('count')
			serie.datasetIndex = index
			serie.yAxisIndex = 0
			chart.series.push(serie)
			dataset = nc.clone(defaultDataset)
			dataset.source = nc.clone(year.data)
			dataset.dimensions[1].name = 'count' // percentage
			chart.dataset.push(dataset)
			// cumulative line
			index++
			serie = nc.clone(defaultSerie)
			serie.type = 'line'
			serie.name = year.year + ' ' // can't be same as count, so add ' '  - or nc.l('cumulative')
			serie.datasetIndex = index
			serie.yAxisIndex = 1
			chart.series.push(serie)
			dataset = nc.clone(dataset)
			dataset.dimensions[1].name = 'cumulative'
			chart.dataset.push(dataset)
			index++
		}
		rec.chart.option = chart
	}
	// headers
	rec.selected_company = nc.recordArrayField(arr.company, 'value', rec.company, 'show')
	rec.selected_company = nc.peg.parseBefore(rec.selected_company, ' (')
	hdr.report_name = nc.recordArrayField(arr.report_type, 'value', rec.report_type, 'show')
	rec.report_header1 = rec.selected_company
	rec.report_header2 = ''
	return rowData
}
