<template>
	<div class="container">
		<div class="form-panel">
			<uni-forms ref="baseForm" :modelValue="baseFormData" labelWidth="100px">
				<uni-forms-item label="所属区域" required name="owningRegion"
					:rules="[{ required: true, errorMessage: '请选择所属区域' }]">
					<selectOperation v-model="baseFormData.owningRegion" placeholder="请选择所属区域" :disabled="readOnly">
					</selectOperation>
				</uni-forms-item>
				<uni-forms-item label="选择部件" required name="componentType"
					:rules="[{ required: true, errorMessage: '请选择部件' }]">
					<selectComponentType v-model="baseFormData.componentType" placeholder="请选择部件" :disabled="readOnly"
						@change="changeType"></selectComponentType>
				</uni-forms-item>
				<uni-section v-if="baseFormData.componentType == '262711452730000'" title="电池列表" type="line">
					<template v-slot:right>
						<uni-icons type="scan" size="20" @click="onBatteryScanClick" v-if="!readOnly"></uni-icons>
					</template>
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item,index) in listBatteryData" :key="index"
							:right-options="listBatteryOptions" :disabled="readOnly">
							<div class="content-box">
								<label>{{item.batteryCode}}</label>
								<div v-show="readOnly" @click="delData(index)">
									<uni-icons custom-prefix="iconfont" type="icon-ebikeshanchu"
										color="rgb(121 116 116)" size="20" />
								</div>
							</div>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-section>
				<uni-section v-if="baseFormData.componentType == '262711452730001'" title="头盔列表" type="line">
					<template v-slot:right>
						<uni-icons type="scan" size="20" @click="onHelmetScanClick" v-if="!readOnly"></uni-icons>
					</template>
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item,index) in listEcuData" :key="index"
							:right-options="listHelmetOptions"
							:disabled="readOnly">
							<div class="content-box">
								<label>{{item.helmetCode}}</label>
								<div v-show="readOnly" @click="delData(index)">
									<uni-icons custom-prefix="iconfont" type="icon-ebikeshanchu"
										color="rgb(121 116 116)" size="20" />
								</div>
							</div>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-section>
				<uni-section v-if="baseFormData.componentType == '262711452730008'" title="中控列表" type="line">
					<template v-slot:right>
						<uni-icons type="scan" size="20" @click="onScanClick" v-if="!readOnly"></uni-icons>
					</template>
					<uni-swipe-action>
						<uni-swipe-action-item v-for="(item,index) in listEcuData" :key="index"
							:right-options="listEcuOptions" @click="onEcuListClick($event, index, item)" :disabled="readOnly">
							<div class="content-box">
								<label>sn：{{item.sn}}</label>
								<div v-show="readOnly" @click="delData(index)">
									<uni-icons custom-prefix="iconfont" type="icon-ebikeshanchu"
										color="rgb(121 116 116)" size="20" />
								</div>
							</div>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-section>
				<uni-forms-item label="入库数量" required name="enterQuantity"
					:rules="[{ required: true, errorMessage: '请输入入库数量' }]">
					<uni-number-box :background="(readOnly||disabledNum)?'#d8d9d0':'#ffffff'"
						v-model="baseFormData.enterQuantity" placeholder="请输入入库数量" :disabled="readOnly||disabledNum" />
				</uni-forms-item>
				<uni-forms-item label="部件单价(元)">
					<uni-easyinput v-model="baseFormData.componentPrice" placeholder="请输入部件单价,单位:元"
						:disabled="readOnly" />
				</uni-forms-item>
			</uni-forms>
		</div>
	</div>
	<div class="nav-panel" v-if="baseFormData.state == '0'">
		<c-uni-goods-nav :fill="true" :options="navOptions" @click="navOptionsClick" :buttonGroup="navButtonGroup"
			@buttonClick="navButtonClick" />
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		computed
	} from 'vue';
	import * as api from '@/utils/api.js';
	import {
		showModelMessage,
		isNullOrEmpty,
		dataFormat
	} from '@/utils/tools.js';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		useScanCodeStore
	} from '@/stores/scancode.js';
	const scancode = useScanCodeStore();

	const baseForm = ref(null);
	const readOnly = ref(false);
	const userInfo = ref(null);

	const componentEnterRecordId = ref("");
	// 基础表单数据
	const baseFormData = ref({
		"componentEnterRecordId": "",
		"owningRegion": "",
		"componentType": "",
		"enterQuantity": 0,
		"componentPrice": "",
		"stockInType": "0",
	});

	const navOptions = reactive([{
		icon: 'download',
		text: '暂存',
		disable: false
	}, {
		icon: 'closeempty',
		text: '取消',
		disable: false
	}]);

	const navButtonGroup = reactive([{
		text: '入库',
		backgroundColor: '#0078D4',
		color: '#fff',
		disable: false
	}]);

	const disabledNum = ref(false);

	// 在组件挂载完成后加载数据
	onMounted(() => {
		if (!isNullOrEmpty(componentEnterRecordId.value)) {
			loadData();
		}
	});
	onLoad((options) => {
		scancode.clearCode();
		baseFormData.value.enterQuantity = 0;
		if (options.componentEnterRecordId) {
			componentEnterRecordId.value = options.componentEnterRecordId;
		}
		userInfo.value = uni.getStorageSync('userInfo');
	})

	onShow(() => {
		if (!isNullOrEmpty(scancode.code)) {
			listBatteryData.value = [];
			baseFormData.value.enterQuantity = 0;
			listHelmetData.value = [];
			listEcuData.value = [];
			const arr = scancode.code;
			for (let i = 0; i < arr.length; i++) {
				if (scancode.type == 'inBattery') {
					const oneBattery = {
						"batteryEnterRecordId": "",
						"componentEnterRecordId": componentEnterRecordId.value,
						"batteryCode": arr[i]
					}
					listBatteryData.value.push(oneBattery)
					baseFormData.value.enterQuantity = listBatteryData.value.length
				} else if (scancode.type == 'inHelmet') {
					const oneHelmet = {
						"helmetEnterRecordId": "",
						"componentEnterRecordId": componentEnterRecordId.value,
						"helmetCode": arr[i]
					}
					listHelmetData.value.push(oneHelmet)
					baseFormData.value.enterQuantity = listHelmetData.value.length
				} else if (scancode.type == 'inEcu') {
					const arrCode = arr[i].split(" ");
					const imei = arrCode[0].replace("IMEI:", "");
					const sn = arrCode[1].replace("SN:", "");
					const oneHelmet = {
						id: "",
						imei: imei,
						sn: sn
					}
					listEcuData.value.push(oneHelmet);
					baseFormData.value.enterQuantity = listEcuData.value.length;
				} else break;
			}
		}
	});

	const loadData = () => {
		api.callOperateApi("ebikeComponentEnterRecords/getInfo?id=" + componentEnterRecordId.value, {}, "get").then((
			res) => {
			if (res.code === 200) {
				baseFormData.value = res.data;
				if (baseFormData.value.componentType == '262711452730000') {
					getBatteryList(baseFormData.value.componentEnterRecordId);
				} else if (baseFormData.value.componentType == '262711452730001') {
					getHelmetList(baseFormData.value.componentEnterRecordId);
				} else if (baseFormData.value.componentType == '262711452730008') {
					getEcuList(baseFormData.value.componentEnterRecordId);
				}
				if (baseFormData.value.state != "0") {
					readOnly.value = true;
					navOptions[0].disable = true;
					navOptions[1].disable = true;
					navButtonGroup[0].disable = true;
				}
			}
		})
	};

	const listBatteryData = ref([]);
	const listHelmetData = ref([]);
	const listEcuData = ref([]);

	function getBatteryList(componentEnterRecordId, pageNo = 1, pageSize = 100) {
		// 组装参数
		const params = {
			"componentEnterRecordId": componentEnterRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeBatteryEnterRecords/list", params).then((res) => {
			if (res.code === 200) {
				listBatteryData.value.push(...res.data.records);
				baseFormData.value.enterQuantity = listBatteryData.value.length;
				if (res.data.totalRow > pageNo * pageSize) {
					pageNo += 1;
					getBatteryList(componentEnterRecordId, pageNo, pageSize);
				}
			}
		});
	}

	const getHelmetList = (componentEnterRecordId, pageNo = 1, pageSize = 100) => {
		// 组装参数
		const params = {
			"componentEnterRecordId": componentEnterRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeHelmetEnterRecords/list", params).then((res) => {
			if (res.code === 200) {
				listHelmetData.value.push(...res.data.records);
				baseFormData.value.enterQuantity = listHelmetData.value.length;
				if (res.data.totalRow > pageNo * pageSize) {
					pageNo += 1;
					getHelmetList(componentEnterRecordId, pageNo, pageSize);
				}
			}
		});
	}

	const getEcuList = (componentEnterRecordId, pageNo = 1, pageSize = 100) => {
		// 组装参数
		const params = {
			"componentEnterRecordId": componentEnterRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeComponent/ecuEnterList", params).then((res) => {
			if (res.code === 200) {
				listEcuData.value.push(...res.data.records);
				baseFormData.value.enterQuantity = listEcuData.value.length;
				if (res.data.totalRow > pageNo * pageSize) {
					pageNo += 1;
					getEcuList(componentEnterRecordId, pageNo, pageSize);
				}
			}
		});
	}

	const navOptionsClick = (e) => {
		const index = e.index;
		if (index == 0) {
			handleSubmit('0');
		} else if (index == 1) {
			handleSubmit('-1');
		}
	}

	const navButtonClick = (e) => {
		const index = e.index;
		//navButtonGroup[index].disable = true;
		if (index == 0) {
			if (baseForm.value) { // 确保表单元素已挂载
				baseForm.value.validate().then((res) => {
					if (baseFormData.value.componentType == '262711452730000') {
						if (listBatteryData.value.length == 0) {
							showModelMessage("电池列表不能为空！");
							return false;
						}
					}
					if (baseFormData.value.componentType == '262711452730001') {
						if (listHelmetData.value.length == 0) {
							showModelMessage("头盔列表不能为空！");
							return false;
						}
					}
					handleSubmit('1');
				}).catch((err) => {
					//console.log('err', err);
				});
			} else {
				//console.error('Form element is not available'); // 调试信息，以防万一
			}
		}
	}

	const handleSubmit = (state) => {
		let sucessMsg = "保存成功";
		let errorMsg = "保存失败";
		if (state == '-1') {
			sucessMsg = "取消成功";
			errorMsg = "取消失败";
			baseFormData.value.stockInType = '-1';
			if (componentEnterRecordId.value) {
				api.callOperateApi("ebikeComponent/cancelDevicePart?componentEnterRecordId=" + componentEnterRecordId
					.value, {}, "get").then((res) => {
					if (res.code == '200') {
						uni.showToast({
							title: sucessMsg,
							icon: 'success',
							duration: 5000
						});
					} else {
						uni.showToast({
							title: errorMsg,
							icon: 'error',
							duration: 5000
						});
					};
				});
				return;
			}
		} else if (state == '1') {
			sucessMsg = "入库成功";
			errorMsg = "入库失败";
			baseFormData.value.stockInType = '1';
		}
		const params = baseFormData.value;

		if (params.componentType == '262711452730000') {
			params['ebikeBatteryEnterRecords'] = listBatteryData.value;
		} else if (params.componentType == '262711452730001') {
			params['ebikeHelmetEnterRecords'] = listHelmetData.value;
		} else if (params.componentType == '262711452730008') {
			params['ebikeEcuEnterRecords'] = listEcuData.value;
		}
		api.callOperateApi("ebikeComponent/componentInventoryEnterbound", params).then((res) => {
			if (res.code == '200') {
				componentEnterRecordId.value = res.data;
			} else {
				uni.showToast({
					title: errorMsg,
					icon: 'error',
					duration: 5000
				});
			};
		});
	};

	const listBatteryOptions = reactive([{
		text: '删除',
		style: {
			backgroundColor: '#007aff'
		}
	}]);

	const listHelmetOptions = reactive([{
		text: '删除',
		style: {
			backgroundColor: '#007aff'
		}
	}]);
	
	const listEcuOptions = reactive([{
		text: '删除',
		style: {
			backgroundColor: '#007aff'
		}
	}]);

	const onBatteryListClick = (e, index, item) => {
		if (e.position == 'right') {
			if (e.index == 0) {
				if (index != -1) {
					listBatteryData.value.splice(index, 1); // 删除索引位置的元素
					baseFormData.value.enterQuantity = listBatteryData.value.length;
				}
			}
		}
	}

	const onHelmetListClick = (e, index, item) => {
		if (e.position == 'right') {
			if (e.index == 0) {
				if (index != -1) {
					listHelmetData.value.splice(index, 1); // 删除索引位置的元素
					baseFormData.value.enterQuantity = listHelmetData.value.length;
				}
			}
		}
	}
	
	const onEcuListClick = (e, index, item) => {
		if (e.position == 'right') {
			if (e.index == 0) {
				if (index != -1) {
					listEcuData.value.splice(index, 1); // 删除索引位置的元素
					baseFormData.value.enterQuantity = listEcuData.value.length;
				}
			}
		}
	}

	const onBatteryScanClick = (e) => {
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=inBattery`, //
		});
	}

	const onHelmetScanClick = (e) => {
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=inHelmet`, //
		});
	}

	function onScanClick(e) {
		uni.navigateTo({
			url: `/pages/common/batchscancode?k=${Date.now()}`, //
		});
	}

	function changeType(value) {
		if (",262711452730000,262711452730001,262711452730008,".indexOf("," + value + ",") > -1) {
			disabledNum.value = true;
			scancode.clearCode();
		} else {
			disabledNum.value = false;
		}
		baseFormData.value.enterQuantity = 0;
	}

	function delData(index) {
		switch (baseFormData.value.componentType) {
			case "262711452730000":
				listBatteryData.value.splice(index, 1);
				break;
			case "262711452730001":
				listHelmetData.value.splice(index, 1);
				break;
			case "262711452730008":
				listEcuData.value.splice(index, 1);
				break;
		}
		baseFormData.enterQuantity.value = baseFormData.enterQuantity.value - 1;
	}
</script>

<style lang="scss">
	.container {
		padding: 15px;
		background-color: #fff;
	}

	.form-panel {
		padding-bottom: 55px;
	}

	.nav-panel {
		position: fixed;
		bottom: 0rpx;
		width: 100%;
		padding-bottom: 10px;
		z-index: 999;
		background-color: #fff;
	}

	.content-box {
		display: flex;
		line-height: 50px;
		border-bottom: 1px solid #f4f4f4;
	}

	.content-box label {
		flex: 1
	}

	.uni-section {
		margin: 20px 0px;
	}

	.uni-section-header {
		border-top: 1px solid #f4f4f4;
		border-bottom: 1px solid #f4f4f4;
	}
</style>