export const STORAGE_KEY = 'pda_scan_config';

export const DICTIONARY_TYPE_SCANNER = 10046;

export const PHONE_SCAN_BRAND = 'phone';

export const PHONE_SCAN_CONFIG = {
	brand: PHONE_SCAN_BRAND,
	name: '手机扫码',
	isPhoneScan: true,
};

const NO_SETUP_HINT_KEY = 'pda_scan_config_hint_shown';

export function isPhoneScanConfig(config) {
	return !!(config && (config.isPhoneScan || config.brand === PHONE_SCAN_BRAND));
}

function enrichFromBuiltinConfig(config, builtinConfigs = []) {
	if (!config || !builtinConfigs.length) {
		return config;
	}

	const builtin = builtinConfigs.find((item) => {
		return item.action === config.action
			|| item.name === config.name
			|| item.brand === config.brand;
	});

	if (!builtin) {
		return config;
	}

	return {
		...config,
		needSetup: builtin.needSetup,
		setupAction: builtin.setupAction || '',
		setupParams: builtin.setupParams || null,
	};
}

export function normalizeConfig(raw, builtinConfigs = []) {
	if (!raw || typeof raw !== 'object') return null;

	const brand = String(raw.brand || raw.id || raw.dictionary_detail_id || raw.name || '');
	const isPhoneScan = raw.isPhoneScan === true || brand === PHONE_SCAN_BRAND;

	if (isPhoneScan) {
		return { ...PHONE_SCAN_CONFIG };
	}

	const config = enrichFromBuiltinConfig({
		brand,
		name: raw.name || '',
		action: raw.action || raw.code || '',
		dataKey: raw.dataKey || raw.data_key || raw.remark || '',
		needSetup: raw.needSetup != null ? raw.needSetup : !!raw.need_setup,
		setupAction: raw.setupAction || raw.setup_action || '',
		setupParams: raw.setupParams || raw.setup_params || null,
	}, builtinConfigs);

	if (!config.brand || !config.action || !config.dataKey) {
		return null;
	}

	return config;
}

export function mapDictionaryToScannerConfig(raw, builtinConfigs = []) {
	return normalizeConfig(raw, builtinConfigs);
}

export function getScanConfig(builtinConfigs = []) {
	try {
		const data = uni.getStorageSync(STORAGE_KEY);
		return normalizeConfig(data, builtinConfigs);
	} catch (e) {
		console.log('读取扫码枪配置失败', e);
		return null;
	}
}

export function saveScanConfig(config) {
	const normalized = normalizeConfig(config);
	if (!normalized) {
		return false;
	}
	try {
		uni.setStorageSync(STORAGE_KEY, normalized);
		return true;
	} catch (e) {
		console.log('保存扫码枪配置失败', e);
		return false;
	}
}

export function hasShownNoConfigHint() {
	try {
		return !!uni.getStorageSync(NO_SETUP_HINT_KEY);
	} catch (e) {
		return false;
	}
}

export function markNoConfigHintShown() {
	try {
		uni.setStorageSync(NO_SETUP_HINT_KEY, true);
	} catch (e) {
		console.log('记录扫码枪提示状态失败', e);
	}
}
