<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 listHelmetData" :key="index"
							:right-options="listHelmetOptions" @click="onHelmetListClick($event, index, item)"
							: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="listHelmetOptions" 
							: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": "",
		"createdUser": "",
		"createdAt": "",
		"state": "0",
		"updateUser": "",
		"updateAt": ""
	});

	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) => {
		if (options.componentEnterRecordId) {
			componentEnterRecordId.value = options.componentEnterRecordId;
		}
		userInfo.value = uni.getStorageSync('userInfo');
	})

	onShow(() => {
		if (!isNullOrEmpty(scancode.code)) {
			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;
			}
			
			scancode.clearCode();
		}
	});

	// 假设这是从接口加载的数据
	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);
				}
				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 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.state = '-1';
		} else if (state == '1') {
			sucessMsg = "入库成功";
			errorMsg = "入库失败";
			baseFormData.value.state = '1';
		}
		const params = baseFormData.value;
		saveBaseInfo((bresult) => {
			if (!bresult) {
				uni.showToast({
					title: errorMsg,
					icon: 'error',
					duration: 5000
				});
			} else {
				if (params.componentType == '262711452730000') {
					saveBatteryData((bresult1) => {
						if (!bresult1) {
							uni.showToast({
								title: errorMsg,
								icon: 'error',
								duration: 5000
							});
						} else {
							uni.showToast({
								title: sucessMsg,
								icon: 'success',
								duration: 1000,
								success: (res) => {
									if (params.state != '0') {
										setTimeout(function() {
											uni.navigateBack();
										}, 1000);
									}
								}
							});
						}
					})
				} else if (params.componentType == '262711452730001') {
					saveHelmetData((bresult1) => {
						if (!bresult1) {
							uni.showToast({
								title: errorMsg,
								icon: 'error',
								duration: 5000
							});
						} else {
							uni.showToast({
								title: sucessMsg,
								icon: 'success',
								duration: 1000,
								success: (res) => {
									if (params.state != '0') {
										setTimeout(function() {
											uni.navigateBack();
										}, 1000);
									}
								}
							});
						}
					})
				} else {
					uni.showToast({
						title: sucessMsg,
						icon: 'success',
						duration: 1000,
						success: (res) => {
							if (params.state != '0') {
								setTimeout(function() {
									uni.navigateBack();
								}, 1000);
							}
						}
					});
				}
			}
		});
	};

	const saveBaseInfo = (callback) => {
		const params = baseFormData.value;
		if (isNullOrEmpty(baseFormData.value.createdUser)) baseFormData.value.createdUser = userInfo.value.username;
		if (isNullOrEmpty(baseFormData.value.createdAt)) baseFormData.value.createdAt = dataFormat(new Date(),
			'yyyy-MM-dd HH:mm:ss');
		if (!isNullOrEmpty(componentEnterRecordId.value)) {
			baseFormData.value.updateUser = userInfo.value.username;
			baseFormData.value.updateAt = dataFormat(new Date(), 'yyyy-MM-dd HH:mm:ss');
			api.callOperateApi("ebikeComponentEnterRecords/update", params).then((res) => {
				if (res.code == '200') callback(true);
				else callback(false);
			});
		} else {
			api.callOperateApi("ebikeComponentEnterRecords/save", params).then((res) => {
				if (res.code == '200') {
					componentEnterRecordId.value = res.data;
					callback(true);
				} else callback(false);
			});
		}
	}

	const saveBatteryData = (callback) => {
		const listdatas = [];
		listBatteryData.value.forEach((item, index) => {
			listdatas.push(item.batteryCode);
		});
		const params = {
			componentEnterRecordId: componentEnterRecordId.value,
			batteryCodes: listdatas
		}
		api.callOperateApi("ebikeBatteryEnterRecords/batchSaveByComponentEnterRecordId", params).then((res) => {
			if (res.code == '200') {
				if (baseFormData.value.state == '1') {
					api.callEbikeInfo("saveBatteryInfo", listdatas).then((res) => {
						if (res.code == '200') {
							callback(true);
						} else {
							callback(false);
						}
					});
				} else {
					callback(true);
				}
			} else {
				callback(false);
			}
		});
	}

	const saveHelmetData = (callback) => {
		const listdatas = [];
		listHelmetData.value.forEach((item, index) => {
			listdatas.push(item.helmetCode);
		});
		const params = {
			componentEnterRecordId: componentEnterRecordId.value,
			helmetCodes: listdatas
		}
		api.callOperateApi("ebikeHelmetEnterRecords/batchSaveByComponentEnterRecordId", params).then((res) => {
			if (res.code == '200') {
				if (baseFormData.value.state == '1') {
					api.callEbikeInfo("saveHelmetInfo", listdatas).then((res) => {
						if (res.code == '200') {
							callback(true);
						} else {
							callback(false);
						}
					});
				} else {
					callback(true);
				}
			} else {
				callback(false);
			}
		});
	}

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

	const listHelmetOptions = 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 onBatteryScanClick = (e) => {
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=inBattery`, //
		});
		// uni.scanCode({
		// 	onlyFromCamera: true, //只能扫码
		// 	scanType: ["qrCode"],
		// 	success: function(res) {
		// 		const {
		// 			result
		// 		} = res;
		// 		console.log(result);
		// 		const oneBattery = {
		// 				"batteryEnterRecordId": "",
		// 				"componentEnterRecordId": componentEnterRecordId.value,
		// 				"batteryCode": result
		// 		}
		// 		listBatteryData.value.push(oneBattery)
		// 		baseFormData.value.enterQuantity = listBatteryData.value.length
		// 	}
		// })
	}

	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;
		} 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>