// form/nc/nc-stock/nc-stock.js

import { setState, updatePacket as updatePacketConvert, unitAmount as unitAmountConvert } from '/plugin/convert/product-convert.js'

setState(nc)
const recData = nc.recData
const recDataCopy = nc.recDataCopy
if (rec.packet == null) {
	message.setError(state, 'nc-stock rec.packet is null')
}
const packet = rec.packet || {}
const packetDefault = nc.clone(packet)
let rowIndex = 0
const columnWidth = {
	buttonWidth: Number(rec.width.button_width.replace('em', '')),
	margin: Number(rec.width.margin.replace('em', '')),
	labelInput: Number(rec.width.label_input.replace('em', '')),
	amount: Number(rec.width.amount.replace('em', '')),
	unit: Number(rec.width.unit.replace('em', '')),
	multiplier: Number(rec.width.multiplier.replace('em', ''))
}

/* onMounted(() => {
	nc.grid.activateRows(state, 'stock', 1)
	gridRowClicked('stock', 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([])

const showStockUnit2Column = ref(packet.stock_unit_2 !== packet.stock_unit_1)
const showDesignUnit1Column = ref(packet.design_unit_1 !== packet.stock_unit_1 && packet.design_unit_1 !== packet.stock_unit_2)
const showDesignUnit2Column = ref(false)
const showPacketCount2Column = ref(false)
const showMultiplierColumn = ref(rec.show_multiplier)
const designUnit2ColumnVisible = () => {
	const pr = packet.row?.pr
	if (pr == null) {
		return false
	}
	if (packet.design_unit_2 === packet.stock_unit_1 || packet.design_unit_2 === packet.stock_unit_2 || packet.design_unit_2 === packet.design_unit_1) {
		return false
	}
	return true
}
const packetCount2ColumnVisible = () => {
	if (packet.packet_unit == null) {
		message.setError(state, 'nc-stock showPacketCount2Column: packet.packet_unit is null')
		return false
	}
	if (packet.stock_unit_2 !== packet.stock_unit_1 && packet.packet_unit.includes(packet.stock_unit_2) && packet.stock_unit_2 !== 'pcs') {
		return true
	}
	if (
		packet.design_unit_1 !== packet.stock_unit_1 &&
		packet.design_unit_1 !== packet.stock_unit_2 &&
		packet.packet_unit.includes(packet.design_unit_1) &&
		packet.design_unit_1 !== 'pcs'
	) {
		return true
	}
	if (
		packet.design_unit_2 !== packet.stock_unit_1 &&
		packet.design_unit_2 !== packet.stock_unit_2 &&
		packet.design_unit_2 !== packet.design_unit_1 &&
		packet.packet_unit.includes(packet.design_unit_2) &&
		packet.design_unit_2 !== 'pcs'
	) {
		return true
	}
	return false
}

const stockUnit1Width = ref('0em')
const stockUnit2Width = ref('0em')
const designUnit1Width = ref('0em')
const designUnit2Width = ref('0em')

const containerWidth = ref('')
let setWidthTimeout = null
let setVisibleTimeout = null

const widthDelay = 220
const animationDelay = 220
function setWidth() {
	/* 	Animation timing explanation:
	CSS transition is 0.4s (400ms) for width, transform, and opacity
	When EXPANDING (newWidth > currentWidth):
	1. Expand width immediately (widthTimeout = 0)
	2. Wait 220ms for width expansion (columnTimeout = animationDelay)
	3. Then show new columns
	This prevents new columns from appearing before there's space for them
	When SHRINKING (newWidth < currentWidth):
	1. Hide columns immediately (columnTimeout = 0)
	2. Wait 220ms for hide animation (widthTimeout = widthDelay)
	3. Then shrink container width
	This prevents container shrinking before columns disappear
	CSS directly animates width/transform/opacity on columns without move classes
	 */
	if (setWidthTimeout != null) {
		clearTimeout(setWidthTimeout)
		setWidthTimeout = null
	}
	if (setVisibleTimeout != null) {
		clearTimeout(setVisibleTimeout)
		setVisibleTimeout = null
	}
	const showStockUnit2 = packet.stock_unit_2 !== packet.stock_unit_1
	const showDesignUnit1 = packet.design_unit_1 !== packet.stock_unit_1 && packet.design_unit_1 !== packet.stock_unit_2
	const showDesignUnit2 = designUnit2ColumnVisible()
	const showPacketCount2 = packetCount2ColumnVisible()
	const showMultiplier = rec.show_multiplier
	const stockUnit1 = columnWidth.labelInput + columnWidth.unit + 0.14
	let stockUnit2 = 0
	let designUnit1 = 0
	let designUnit2 = 0
	const defaultWidth = columnWidth.amount + columnWidth.unit + columnWidth.margin
	if (showStockUnit2) {
		stockUnit2 = defaultWidth
		if (showMultiplier) {
			stockUnit2 += columnWidth.multiplier
		}
	}
	if (showDesignUnit1) {
		designUnit1 = defaultWidth
		if (showMultiplier) {
			designUnit1 += columnWidth.multiplier
		}
	}
	if (showDesignUnit2) {
		designUnit2 = defaultWidth
		if (showMultiplier) {
			designUnit2 += columnWidth.multiplier
		}
	}
	let newWidth = columnWidth.labelInput + columnWidth.unit + columnWidth.margin + stockUnit2 + designUnit1 + designUnit2
	let currentWidth = stockUnit1
	if (showStockUnit2Column.value) {
		currentWidth += defaultWidth
		if (showMultiplierColumn.value) {
			currentWidth += columnWidth.multiplier
		}
	}
	if (showDesignUnit1Column.value) {
		currentWidth += defaultWidth
		if (showMultiplierColumn.value) {
			currentWidth += columnWidth.multiplier
		}
	}
	if (showDesignUnit2Column.value) {
		currentWidth += defaultWidth
		if (showMultiplierColumn.value) {
			currentWidth += columnWidth.multiplier
		}
	}
	let widthTimeout = 0
	let columnTimeout = 0
	if (newWidth > currentWidth) {
		columnTimeout = animationDelay
	} else if (newWidth < currentWidth) {
		widthTimeout = widthDelay
	}
	setWidthTimeout = setTimeout(() => {
		setWidthTimeout = null
		if (newWidth < stockUnit1 + columnWidth.buttonWidth) {
			newWidth = stockUnit1 + columnWidth.buttonWidth
		}
		containerWidth.value = newWidth + 'em'
		stockUnit1Width.value = stockUnit1 + 'em'
		stockUnit2Width.value = stockUnit2 + 'em'
		designUnit1Width.value = designUnit1 + 'em'
		designUnit2Width.value = designUnit2 + 'em'
	}, widthTimeout)
	setVisibleTimeout = setTimeout(() => {
		setVisibleTimeout = null
		showStockUnit2Column.value = showStockUnit2
		showDesignUnit1Column.value = showDesignUnit1
		showDesignUnit2Column.value = showDesignUnit2
		showPacketCount2Column.value = showPacketCount2
		showMultiplierColumn.value = showMultiplier
	}, columnTimeout)
}
setWidth()

watch(
	() => [packet.stock_unit_1, packet.stock_unit_2, packet.design_unit_1, packet.design_unit_2, packet.row?.pr?.json_data?.design_conversion_multiplier],
	() => {
		setWidth()
	},
	{ deep: true }
)

function copyOrderRowFieldToPacket() {
	const fromData = nc.grid.activatedRow(state, 'stock_row')
	if (fromData == null) {
		return
	}
	for (const key in packetDefault) {
		recDataCopy(packetDefault, key, packet, key)
	}
	for (const item of rec.copy_order_row_field_to_packet) {
		const fromValue = recData(fromData, item.from)
		if (fromValue == null) {
			message.setError(state, `nc-stock: rec.copy_order_row_field_to_packet field '${item.from}' is '${fromValue}', product_id='${fromData.product_id}'`)
		}
		recDataCopy(fromData, item.from, packet, item.to)
	}
	packet.row = fromData
	updatePacketConvert('', packet, true)
	unitAmountConvert('', packet)
}

// eslint-disable-next-line no-unused-vars
function updatePacket(changedField) {
	updatePacketConvert(changedField, packet)
}

// eslint-disable-next-line no-unused-vars
function createRow() {
	const data = state.grid.stock_location.data
	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_stock) {
			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, 'stock_location')
}

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

// eslint-disable-next-line no-unused-vars
function update() {
	const param = {
		tab: rec.tab,
		transfer_id: rec.show_all_events ? '%' : '',
		search_product: rec.search_product
	}
	const gridParam = [
		{
			name: 'stock',
			tab: param.tab
		}
	]
	if (rec.tab === 'stock-receive' || rec.tab === 'stock-send') {
		gridParam.push({
			name: 'stock_row',
			tab: param.tab
		})
		gridParam.push({
			name: 'stock_location',
			tab: param.tab
		})
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/nc-stock/grid.json',
			return: { grid: gridParam },
			parameter: param
		},
		() => {
			if (rowIndex > 0 && rec.tab === 'product') {
				const data = state.grid?.stock?.data
				if (data && rowIndex > data.length) {
					rowIndex = 1
				}
			}
			nc.grid.activateRows(state, 'stock', rowIndex)
			gridRowClicked('stock', 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 = {}
			arr.forEach(item => {
				selectedOrderIdx[item.order_id] = true
			})
		}
		nc.grid.updateFilter(state, 'stock_row')
	}, 0)
}

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

function gridRowClicked(area, row, event, selected) {
	if (area === 'stock_row') {
		copyOrderRowFieldToPacket()
	} else if (selected && area === 'stock' && rec.tab === 'stock-receive') {
		const data = state.grid?.stock?.data
		const stockEvent = state.grid?.stock_location
		if (data && stockEvent) {
			rowIndex = row // || event?.data?.idx
			if (rowIndex > 0 && rowIndex <= data.length) {
				rec.product_info = data[rowIndex - 1].info // rodo: what this is?
				const newData = data[rowIndex - 1].stock_location || []
				nc.grid.dataChanged(stockEvent, newData)
			} else {
				nc.grid.dataChanged(stockEvent, [])
			}
		} else {
			nc.grid.dataChanged(stockEvent, [])
		}
		if (!selected) {
			rowIndex = 0
			nc.grid.dataChanged(stockEvent, [])
		}
	}
	if (area === 'stock' && rec.tab === 'stock-receive') {
		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 (node.grid_name === 'stock_row') {
		if (selectedOrderIdx && !selectedOrderIdx[node.data.order_id]) {
			return false
		}
	}
	return true
}

// eslint-disable-next-line no-unused-vars
function packetEnabled() {
	return nc.grid.activatedRow(state, 'stock_row') != null
}

// eslint-disable-next-line no-unused-vars
function roundAmount(amount) {
	return nc.round(amount, packet.round_decimals)
}

watch(
	() => rec.location_id,
	() => {
		mapSelected.value.length = 0
		mapSelected.value.push(rec.location_id)
	}
)

// eslint-disable-next-line no-unused-vars
function stockMapToggleSelected(param) {
	if (param.id && param.id !== '') {
		rec.location_id = param.id
		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 stockMapDoubleClick(param) {
	console.debug('map double click', param.id, param.event)
}
