<template>
	<view class="wrap">
		<common-navbar title="扫描设置"></common-navbar>
		<u-gap height="20" bg-color="#f5f5f5"></u-gap>
		<u-cell-group :border="false">
			<u-cell-item title="扫码方式" :value="form.name || '请选择'" @click="brandSelectShow = true"></u-cell-item>
			<template v-if="!form.isPhoneScan">
				<u-cell-item title="广播动作" :arrow="false">
					<u-input
						slot="right-icon"
						v-model="form.action"
						placeholder="请输入广播动作"
						input-align="right"
						:clearable="false"
					></u-input>
				</u-cell-item>
				<u-cell-item title="数据标签" :arrow="false">
					<u-input
						slot="right-icon"
						v-model="form.dataKey"
						placeholder="请输入数据标签"
						input-align="right"
						:clearable="false"
					></u-input>
				</u-cell-item>
			</template>
		</u-cell-group>
		<view class="form-footer">
			<u-button type="primary" :loading="submitting" @click="submit">确定</u-button>
		</view>
		<u-select v-model="brandSelectShow" :list="brandSelectList" @confirm="onBrandConfirm"></u-select>
	</view>
</template>

<script>
import CommonNavbar from '@/components/common-navbar/index';
import scanMixin from '@/common/scanMixin.js';
import {
	getScanConfig,
	DICTIONARY_TYPE_SCANNER,
	isPhoneScanConfig,
	mapDictionaryToScannerConfig,
	PHONE_SCAN_BRAND,
	saveScanConfig,
} from '@/common/scanConfig.js';

export default {
	components: {
		CommonNavbar,
	},
	mixins: [scanMixin],
	data() {
		return {
			brandSelectShow: false,
			submitting: false,
			configList: [],
			form: {
				brand: '',
				name: '',
				action: '',
				dataKey: '',
				isPhoneScan: false,
				needSetup: false,
				setupAction: '',
				setupParams: null,
			},
		};
	},
	computed: {
		brandSelectList() {
			return this.configList.map((item) => ({
				value: item.brand,
				label: item.name,
			}));
		},
	},
	onLoad() {
		this.loadConfigList();
	},
	methods: {
		async loadConfigList() {
			try {
				const res = await this.$u.api.dictionary.getDetailEnumList({
					dictionary_id: DICTIONARY_TYPE_SCANNER,
				});
				const list = Array.isArray(res) ? res : [];
				const builtinConfigs = this.getScannerConfigs();
				if (list.length) {
					this.configList = list
						.map((item) => mapDictionaryToScannerConfig(item, builtinConfigs))
						.filter(Boolean);
					this.remoteScannerConfigs = this.configList.filter((item) => !isPhoneScanConfig(item));
				} else {
					this.useFallbackConfigList();
				}
			} catch (error) {
				console.log('获取扫码枪字典配置失败，使用内置配置', error);
				this.useFallbackConfigList();
			}
			this.ensurePhoneScanOption();
			this.initFormFromSaved();
		},
		useFallbackConfigList() {
			this.configList = this.getScannerConfigs();
			this.remoteScannerConfigs = [];
		},
		ensurePhoneScanOption() {
			const phoneConfig = this.getPhoneScanConfig();
			if (!this.configList.find((item) => item.brand === PHONE_SCAN_BRAND)) {
				this.configList.push(phoneConfig);
			}
		},
		initFormFromSaved() {
			const savedConfig = getScanConfig(this.getScannerConfigs());
			if (savedConfig) {
				this.applyConfig(savedConfig);
				return;
			}
			if (!this.isPdaDevice()) {
				this.applyConfig(this.getPhoneScanConfig());
				return;
			}
			const pdaConfigs = this.configList.filter((item) => !isPhoneScanConfig(item));
			if (pdaConfigs.length) {
				this.applyConfig(pdaConfigs[0]);
			}
		},
		applyConfig(config) {
			const isPhoneScan = isPhoneScanConfig(config);
			this.form = {
				brand: config.brand || '',
				name: config.name || '',
				action: config.action || '',
				dataKey: config.dataKey || '',
				isPhoneScan,
				needSetup: !!config.needSetup,
				setupAction: config.setupAction || '',
				setupParams: config.setupParams || null,
			};
		},
		onBrandConfirm(selected) {
			const brand = selected[0]?.value;
			const config = this.configList.find((item) => item.brand === brand);
			if (config) {
				this.applyConfig(config);
			}
		},
		submit() {
			if (!this.form.brand) {
				this.$u.toast('请选择扫码方式');
				return;
			}

			let payload;
			if (this.form.isPhoneScan) {
				payload = this.getPhoneScanConfig();
			} else {
				const action = (this.form.action || '').trim();
				const dataKey = (this.form.dataKey || '').trim();
				if (!action) {
					this.$u.toast('请输入广播动作');
					return;
				}
				if (!dataKey) {
					this.$u.toast('请输入数据标签');
					return;
				}
				payload = {
					...this.form,
					action,
					dataKey,
				};
			}

			this.submitting = true;
			if (!saveScanConfig(payload)) {
				this.submitting = false;
				this.$u.toast('保存失败');
				return;
			}

			// #ifdef APP-PLUS
			this.unregisterScanBroadcast();
			const registered = this.registerScanBroadcastByConfig(payload, null);
			if (!registered) {
				this.submitting = false;
				this.$u.toast('保存成功，但广播注册失败');
				return;
			}
			// #endif

			this.submitting = false;
			this.$u.toast('保存成功');
			setTimeout(() => {
				uni.navigateBack();
			}, 500);
		},
	},
};
</script>

<style lang="scss">
page {
	background-color: #f5f5f5;
}

.form-footer {
	padding: 40rpx 30rpx;
}

::v-deep .u-cell_title {
	color: #202328;
}

::v-deep .u-input__input {
	min-width: 360rpx;
}
</style>
