// form/nc/nc-warehouse/nc-warehouse.js

import { amountStock1ToStock2, amountStock2ToStock1 } from '/plugin/convert/product-convert.js'

const recDataCopy = nc.recDataCopy
const packetDefault = nc.clone(rec.packet)
let rowIndex = 0

/* onMounted(() => {
	nc.grid.activateRows(state, 'warehouse', 1)	-- DEV
	gridRowClicked('warehouse', 1, null, true)
}) */

// eslint-disable-next-line no-unused-vars
function tabChanged() {}
// nc-svg-map
let mapSelected = ref([])
// eslint-disable-next-line no-unused-vars
let mapHover = ref([])

function copyOrderRowFieldToPacket() {
	const fromData = nc.grid.activatedRow(state, 'warehouse_row') // nc.grid.activatedRecordArr(state, 'warehouse_row')
	const packet = rec.packet
	for (const key in packetDefault) {
		// set default values to packet
		recDataCopy(packetDefault, key, packet, key)
	}
	for (const item of rec.copy_order_row_field_to_packet) {
		// copy from row to packet
		recDataCopy(fromData, item.from, packet, item.to)
	}
	packet.row = fromData
	unitAmount('', packet) // amountStock1ToStock2
}

function unitAmount(changedField, packet) {
	const pr = packet?.row?.pr
	if (pr) {
		if (changedField.endsWith('2')) {
			packet.total_amount = amountStock2ToStock1(pr, packet.total_amount2)
			packet.packet_count = amountStock2ToStock1(pr, packet.packet_count2)
			packet.full_packet_size = amountStock2ToStock1(pr, packet.full_packet_size2)
			packet.last_packet_size = amountStock2ToStock1(pr, packet.last_packet_size2)
		} else {
			packet.total_amount2 = amountStock1ToStock2(pr, packet.total_amount)
			packet.packet_count2 = amountStock1ToStock2(pr, packet.packet_count)
			packet.full_packet_size2 = amountStock1ToStock2(pr, packet.full_packet_size)
			packet.last_packet_size2 = amountStock1ToStock2(pr, packet.last_packet_size)
		}
	}
}

// eslint-disable-next-line no-unused-vars
function updatePacket(changedField) {
	const packet = rec.packet
	// debugger
	if (packet.packet_count <= 0 || packet.total_amount <= 0) {
		packet.full_packet_size = 0
		packet.full_packet_size2 = 0
		packet.last_packet_size = 0
		return
	}
	packet[changedField] = Number(packet[changedField]) // change entered value to number
	if (changedField === 'total_amount') {
		packet.full_packet_size = packet.total_amount / packet.packet_count
	} else if (changedField === 'packet_count') {
		packet.full_packet_size = packet.total_amount / packet.packet_count
	} else if (changedField === 'full_packet_size') {
		if (packet.packet_count === 0) {
			packet.packet_count = Math.trunc(packet.total_amount / packet.full_packet_size)
			if (packet.total_amount - packet.full_packet_size * packet.packet_count > 0) {
				packet.last_packet_size = packet.total_amount - packet.full_packet_size * packet.packet_count
				packet.last_packet_size = packet.last_packet_size + packet.full_packet_size
			} else {
				packet.last_packet_size = packet.full_packet_size
			}
			// when total amount > packet count * full packet size
		} else if (packet.total_amount > packet.packet_count * packet.full_packet_size) {
			packet.last_packet_size = packet.total_amount - packet.full_packet_size * packet.packet_count + packet.full_packet_size
			// when total amount < packet count * full packet size
		} else if (packet.total_amount < packet.packet_count * packet.full_packet_size) {
			packet.last_packet_size = packet.total_amount - packet.full_packet_size * (packet.packet_count - 1)
		}
	} else if (changedField === 'full_packet_size2') {
		packet.full_packet_size = Math.trunc(packet.total_amount / packet.packet_count)
		packet.last_packet_size = packet.total_amount - packet.packet_count * packet.full_packet_size
	} else if (changedField === 'packet_count2') {
		packet.full_packet_size = Math.trunc(packet.total_amount / packet.packet_count)
		packet.last_packet_size = packet.total_amount - packet.packet_count * packet.full_packet_size
	} else if (changedField === 'last_packet_size2') {
		packet.full_packet_size = Math.trunc(packet.total_amount / packet.packet_count)
		packet.last_packet_size = packet.total_amount - packet.packet_count * packet.full_packet_size
	} else {
		message.setWarning(state, `unknown updatePacket field '${changedField}'`)
	}
	/*
	if (packet.full_packet_size === packet.last_packet_size) {
		packet.full_packet_size = packet.full_packet_size + 1
		packet.last_packet_size = 0
	}
	if (packet.last_packet_size < 0) {
		packet.packet_count = packet.packet_count - 1
		// packet.full_packet_size = Math.trunc(packet.total_amount / packet.packet_count)
		// packet.last_packet_size = packet.total_amount - packet.packet_count * packet.full_packet_size
	}
	*/
	unitAmount(changedField, packet)
}

// eslint-disable-next-line no-unused-vars
function createRow() {
	const packet = rec.packet
	const data = state.grid.warehouse_location.data
	// debugger
	let rowNum = data.length
	for (let i = 1; i <= packet.packet_count; i++) {
		rowNum++
		const row = { idx: rowNum }
		for (const item of rec.copy_packet_field_to_warehouse) {
			// todo: check logic
			if (i < packet.packet_count) {
				packet.save_amount = packet.full_packet_size
			} else {
				packet.save_amount = packet.last_packet_size
			}
			recDataCopy(packet, item.from, row, item.to)
		}
		data.push(row)
	}
	nc.grid.redrawGrid(state, 'warehouse_location')
}

// eslint-disable-next-line no-unused-vars
function save() {
	const saveData = state.grid.warehouse_location.data.filter(item => item.stock_id == null)
	console.debug(`🚀 ~ save data:`, saveData)
	if (saveData.length < 1) {
		message.setWarning(state, 'no warehouse location rows where warehouse id is empty, nothing to save')
		return
	}
	const param = { save: [{ table: 'warehouse', save_preference: 'form/nc/nc-warehouse/save/warehouse.json', data: saveData }] }
	nc.callServer(state, 'save', param, ret => {
		if (ret.status === 'ok') {
			message.setInfo(state, ret)
		}
		if (ret.result) {
			alert(ret.result)
		}
	})
}

// eslint-disable-next-line no-unused-vars
function update() {
	let tab = rec.tab
	const param = {
		tab: tab,
		transfer_id: rec.show_all_events ? '%' : '',
		search_product: rec.search_product
	}
	const gridParam = [
		{
			name: 'warehouse',
			tab: param.tab
		}
	]
	if (rec.tab === 'warehouse-receive' || rec.tab === 'warehouse-receive') {
		gridParam.push({
			name: 'warehouse_location'
		})
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/nc-warehouse/grid.json',
			return: { grid: gridParam },
			parameter: param
		},
		() => {
			if (rowIndex > 0 && rec.tab === 'product') {
				const data = state.grid?.warehouse?.data
				if (data && rowIndex > data.length) {
					rowIndex = 1
				}
			}
			nc.grid.activateRows(state, 'warehouse', rowIndex)
			gridRowClicked('warehouse', null, null, true)
		}
	)
}

let selectedOrderIdx = false
function setSelectedRecordArrIdx(area) {
	setTimeout(() => {
		const arr = nc.grid.activatedRecordArr(state, area)
		if (arr.length < 1) {
			selectedOrderIdx = false
		} else {
			selectedOrderIdx = {} // selectedOrderIdx = nc.createIndex(arr, 'order_id').index
			arr.forEach(item => {
				selectedOrderIdx[item.order_id] = true
			})
		}
		nc.grid.updateFilter(state, 'warehouse_row')
	}, 0)
}

// eslint-disable-next-line no-unused-vars
function gridSelectionChanged(area, event, arg) {
	setSelectedRecordArrIdx(area)
}

function gridRowClicked(area, rowIndex, event, selected) {
	if (area === 'warehouse_row') {
		copyOrderRowFieldToPacket()
	} else if (selected && area === 'warehouse' && rec.tab === 'warehouse-receive') {
		const data = state.grid?.warehouse?.data
		const warehouseEvent = state.grid?.warehouse_location
		if (data && warehouseEvent) {
			rowIndex = event?.data?.idx || rowIndex
			if (rowIndex > 0 && rowIndex <= data.length) {
				rec.product_info = data[rowIndex - 1].info
				const newData = data[rowIndex - 1].warehouse_location || []
				nc.grid.dataChanged(warehouseEvent, newData)
			} else {
				nc.grid.dataChanged(warehouseEvent, [])
			}
		} else {
			nc.grid.dataChanged(warehouseEvent, [])
		}
		if (!selected) {
			rowIndex = 0
			nc.grid.dataChanged(warehouseEvent, [])
		}
	}
	if (area === 'warehouse' && rec.tab === 'warehouse-receive') {
		// select order rows
		setSelectedRecordArrIdx(area)
	}
}

// eslint-disable-next-line no-unused-vars
function isExternalFilterPresent(node) {
	return true
}

// 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]) {
	if (node.grid_name === 'warehouse_row') {
		if (selectedOrderIdx && !selectedOrderIdx[node.data.order_id]) {
			return false
		}
	}
	return true
}

watch(
	() => rec.location_id, // changes in the dropdown change rec -value
	() => {
		mapSelected.value.length = 0 // empty array
		mapSelected.value.push(rec.location_id)
	}
)

// eslint-disable-next-line no-unused-vars
function storageMapToggleSelected(param) {
	// console.debug('map click', param.id, param.event)
	if (param.id && param.id !== '') {
		rec.location_id = param.id // param.id is the warehouse element id the svg map, thos changes dropdown selected value
		const i = mapSelected.value.indexOf(param.id)
		if (i === -1) {
			mapSelected.value.push(param.id)
		} else {
			mapSelected.value.splice(i, 1)
		}
	}
}

// eslint-disable-next-line no-unused-vars
function storageMapDoubleClick(param) {
	console.debug('map double click', param.id, param.event)
}
