<template>
	<view class="container">
		<view class="form-panel">
			<uni-section title="部件出库" type="line">
				<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"></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" @click="onBatteryListClick($event, index, item)"  :disabled="readOnly">
								<view class="content-box">{{item.batteryCode}}</view>
							</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">
								<view class="content-box">{{item.helmetCode}}</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</uni-section>
					<uni-forms-item label="出库数量" required name="outQuantity" :rules="[{ required: true, errorMessage: '请输入出库数量' }]">
						<uni-number-box v-model="baseFormData.outQuantity" placeholder="请输入出库数量" :disabled="readOnly"/>
					</uni-forms-item>
					<uni-section v-if="baseFormData.componentType == '262711452730000'" title="归还电池列表" type="line">
						<template v-slot:right>
							<uni-icons type="scan" size="20" @click="onInBatteryScanClick" v-if="!readOnly1"></uni-icons>
						</template>
 						<uni-swipe-action>
							<uni-swipe-action-item v-for="(item,index) in listInBatteryData" :key="index" :right-options="listInBatteryOptions" @click="onInBatteryListClick($event, index, item)"  :disabled="readOnly1">
								<view class="content-box">{{item.batteryCode}}</view>
							</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="onInHelmetScanClick" v-if="!readOnly1"></uni-icons>
						</template>
						<uni-swipe-action>
							<uni-swipe-action-item v-for="(item,index) in listInHelmetData" :key="index" :right-options="listInHelmetOptions" @click="onInHelmetListClick($event, index, item)"  :disabled="readOnly1">
								<view class="content-box">{{item.helmetCode}}</view>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</uni-section>
					<uni-forms-item  v-if="baseFormData.componentType == '262711452730000' || baseFormData.componentType == '262711452730001'" label="归还数量" name="enterQuantity" > <!--:rules="[{ required: true, errorMessage: '请输入归还数量' }]"-->
						<uni-number-box v-model="baseFormData.enterQuantity" placeholder="请输入归还数量" :disabled="readOnly1"/>
					</uni-forms-item>
					<uni-forms-item label="原部件处理方案" required name="oldComponentHandleOption"> <!-- :rules="[{ required: true, errorMessage: '请选择原部件处理方案' }]"-->
						<uni-data-select
								v-model="baseFormData.oldComponentHandleOption"
								:localdata="componentHandleOptionRange"
								@change="componentHandleOptionChange"
								placeholder="请选择原部件处理方案"
								:disabled="readOnly1"
							></uni-data-select>
					</uni-forms-item>
				</uni-forms>
			</uni-section>
		</view>
	</view>
	<view class="nav-panel" v-if="baseFormData.state == '0' || (baseFormData.state == '1' && (baseFormData.componentType == '262711452730000' || baseFormData.componentType == '262711452730001'))">
		<c-uni-goods-nav :fill="true" :options="navOptions" @click="navOptionsClick" :buttonGroup="navButtonGroup" @buttonClick="navButtonClick" />
	</view>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive
	} 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 readOnly1 = ref(false);
	const userInfo = ref(null);

	const componentOutRecordId = ref("");
	// 基础表单数据
	const baseFormData = ref({
		"componentOutRecordId": "",
		"owningRegion": "",
		"componentType": "",
		"outQuantity": 0,
		"oldComponentHandleOption": "",
		"createdUser": "",
		"createdAt": "",
		"state": "0",
		"updateUser": "",
		"updateAt": "",
		"enterQuantity": 0
	});
	
	let navOptions = reactive([{
		icon: 'download',
		text: '暂存',
		disable: false
	}, {
		icon: 'closeempty',
		text: '取消',
		disable: false
	}]);
	
	let navButtonGroup = reactive([{
		text: '出库',
		backgroundColor: '#0078D4',
		color: '#fff',
		disable: false
	}]);
	
	const componentHandleOptionRange = [
		{ value: "报废", text: "报废" },
		{ value: "返修", text: "返修" }
	]
	
	const componentHandleOptionChange = (value) =>{
		baseFormData.value.oldComponentHandleOption = value;
	};
	
	// 在组件挂载完成后加载数据
	onMounted(() => {
		if(!isNullOrEmpty(componentOutRecordId.value)){
			loadData();
		}
	});
	onLoad((options)=>{
		if(options.componentOutRecordId){
			componentOutRecordId.value=options.componentOutRecordId;
		}
		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 == 'outBattery'){
					const oneBattery = {
							"batteryEnterRecordId": "",
							"componentOutRecordId": componentOutRecordId.value,
							"batteryCode": arr[i]
					}
					listBatteryData.value.push(oneBattery)
					baseFormData.value.outQuantity = listBatteryData.value.length
				}
				else if(scancode.type == 'outHelmet'){
					const oneHelmet = {
							"helmetEnterRecordId": "",
							"componentOutRecordId": componentOutRecordId.value,
							"helmetCode": arr[i]
					}
					listHelmetData.value.push(oneHelmet)
					baseFormData.value.outQuantity = listHelmetData.value.length
				}
				else if(scancode.type == 'inBattery'){
					const oneBattery = {
							"batteryEnterRecordId": "",
							"componentOutRecordId": componentOutRecordId.value,
							"batteryCode": arr[i]
					}
					listInBatteryData.value.push(oneBattery)
					baseFormData.value.enterQuantity = listInBatteryData.value.length
				}
				else if(scancode.type == 'inHelmet'){
					const oneHelmet = {
							"helmetEnterRecordId": "",
							"componentOutRecordId": componentOutRecordId.value,
							"helmetCode": arr[i]
					}
					listInHelmetData.value.push(oneHelmet)
					baseFormData.value.enterQuantity = listInHelmetData.value.length
				}
				else break;
			}
			scancode.clearCode();
		}	
	});
	
	// 假设这是从接口加载的数据
	const loadData = () => {
		api.callOperateApi("ebikeComponentOutRecords/getInfo?id=" + componentOutRecordId.value,{},"get").then((res) => {
			if (res.code === 200) {
				baseFormData.value = res.data;
				if(baseFormData.value.componentType == '262711452730000'){
					getBatteryList(baseFormData.value.componentOutRecordId);
					getInBatteryList(baseFormData.value.componentOutRecordId);
				}
				else if(baseFormData.value.componentType == '262711452730001'){
					getHelmetList(baseFormData.value.componentOutRecordId);
					getInHelmetList(baseFormData.value.componentOutRecordId);
				}
				if(baseFormData.value.state != "0"){
					readOnly.value = true;
					readOnly1.value = true;
					if(baseFormData.value.state == "1"){
						readOnly1.value = false;
						navOptions = [];
						navButtonGroup[0].text = "归还";
					}
					else
					{
						navOptions[0].disable = true;
						navOptions[1].disable = true;
						navButtonGroup[0].disable = true;
					}
				}
			}
		})
	};
	
	const listBatteryData = ref([]);
	const listHelmetData = ref([]);
	
	const getBatteryList = (componentOutRecordId,pageNo = 1,pageSize = 100) =>{
		// 组装参数
		const params = {
			"componentOutRecordId": componentOutRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeBatteryOutRecords/list", params).then((res) => {
			if (res.code === 200) {
				listBatteryData.value.push(...res.data.records);
				baseFormData.value.outQuantity = listBatteryData.value.length;
				if(res.data.totalRow > pageNo* pageSize){
					pageNo += 1;
					getBatteryList(componentOutRecordId, pageNo, pageSize);
				}
			}
		});
	}
	
	const getHelmetList = (componentOutRecordId,pageNo = 1,pageSize = 100) =>{
		// 组装参数
		const params = {
			"componentOutRecordId": componentOutRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeHelmetOutRecords/list", params).then((res) => {
			if (res.code === 200) {
				listHelmetData.value.push(...res.data.records);
				baseFormData.value.outQuantity = listHelmetData.value.length;
				if(res.data.totalRow > pageNo* pageSize){
					pageNo += 1;
					getHelmetList(componentOutRecordId, pageNo, pageSize);
				}
			}
		});
	}
	
	const listInBatteryData = ref([]);
	const listInHelmetData = ref([]);
	
	const getInBatteryList = (componentOutRecordId,pageNo = 1,pageSize = 100) =>{
		// 组装参数
		const params = {
			"componentEnterRecordId": componentOutRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeBatteryEnterRecords/list", params).then((res) => {
			if (res.code === 200) {
				listInBatteryData.value.push(...res.data.records);
				baseFormData.value.enterQuantity = listInBatteryData.value.length;
				if(res.data.totalRow > pageNo* pageSize){
					pageNo += 1;
					getInBatteryList(componentOutRecordId, pageNo, pageSize);
				}
			}
		});
	}
	
	const getInHelmetList = (componentOutRecordId,pageNo = 1,pageSize = 100) =>{
		// 组装参数
		const params = {
			"componentEnterRecordId": componentOutRecordId,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}
		api.callOperateApi("ebikeHelmetEnterRecords/list", params).then((res) => {
			if (res.code === 200) {
				listInHelmetData.value.push(...res.data.records);
				baseFormData.value.enterQuantity = listInHelmetData.value.length;
				if(res.data.totalRow > pageNo* pageSize){
					pageNo += 1;
					getInHelmetList(componentOutRecordId, 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.state == "1"){
						if(baseFormData.value.componentType == '262711452730000'){
							if(listInBatteryData.value.length == 0){
								showModelMessage("归还电池列表不能为空！");
								return false;
							}
						}
						if(baseFormData.value.componentType == '262711452730001'){
							if(listInHelmetData.value.length == 0){
								showModelMessage("归还头盔列表不能为空！");
								return false;
							}
						}
						handleSubmit('2');
					}
					else
					{
						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';
		}
		else if(state == '2'){
			sucessMsg = "归还成功";
			errorMsg = "归还失败";
			baseFormData.value.state = '2';
		}
		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
						{
							saveInBatteryData((bresult2) =>{
								if(!bresult2){
									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
							{
								saveInHelmetData((bresult2) =>{
									if(!bresult2){
										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(componentOutRecordId.value)){
			baseFormData.value.updateUser = userInfo.value.username;
			baseFormData.value.updateAt = dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss');
			api.callOperateApi("ebikeComponentOutRecords/update", params).then((res)=>{
				if(res.code == '200') callback(true);
				else callback(false);
			});
		}
		else
		{
			api.callOperateApi("ebikeComponentOutRecords/save", params).then((res)=>{
				if(res.code == '200') {
					componentOutRecordId.value = res.data;
					callback(true);
				}
				else callback(false);
			});
		}
	}
	
	const saveBatteryData = (callback) =>{
		const listdatas = [];
		listBatteryData.value.forEach((item, index) => {
			listdatas.push(item.batteryCode);
		});
		const params = {
			componentOutRecordId: componentOutRecordId.value,
			batteryCodes: listdatas
		}
		api.callOperateApi("ebikeBatteryOutRecords/batchSaveByComponentOutRecordId", params).then((res)=>{
			if(res.code == '200'){
				callback(true);
			}
			else
			{
				callback(false);
			}
		});
	}
	
	const saveHelmetData = (callback) =>{
		const listdatas = [];
		listHelmetData.value.forEach((item, index) => {
			listdatas.push(item.helmetCode);
		});
		const params = {
			componentOutRecordId: componentOutRecordId.value,
			helmetCodes: listdatas
		}
		api.callOperateApi("ebikeHelmetOutRecords/batchSaveByComponentOutRecordId", params).then((res)=>{
			if(res.code == '200'){
				callback(true);
			}
			else
			{
				callback(false);
			}
		});
	}
	
	const saveInBatteryData = (callback) =>{
		const listdatas = [];
		listInBatteryData.value.forEach((item, index) => {
			listdatas.push(item.batteryCode);
		});
		const params = {
			componentEnterRecordId: componentOutRecordId.value,
			batteryCodes: listdatas
		}
		api.callOperateApi("ebikeBatteryEnterRecords/batchSaveByComponentEnterRecordId", params).then((res)=>{
			if(res.code == '200'){
				callback(true);
			}
			else
			{
				callback(false);
			}
		});
	}
	
	const saveInHelmetData = (callback) =>{
		const listdatas = [];
		listInHelmetData.value.forEach((item, index) => {
			listdatas.push(item.helmetCode);
		});
		const params = {
			componentEnterRecordId: componentOutRecordId.value,
			helmetCodes: listdatas
		}
		api.callOperateApi("ebikeHelmetEnterRecords/batchSaveByComponentEnterRecordId", params).then((res)=>{
			if(res.code == '200'){
				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.outQuantity = 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.outQuantity = listHelmetData.value.length;
				}
			}
		}
	}
	
	const onBatteryScanClick = (e) =>{
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=outBattery`, //
		});
		// uni.scanCode({
		// 	onlyFromCamera: true, //只能扫码
		// 	scanType: ["qrCode"],
		// 	success: function(res) {
		// 		const {
		// 			result
		// 		} = res;
		// 		console.log(result);
		// 		const oneBattery = {
		// 				"batteryEnterRecordId": "",
		// 				"componentOutRecordId": componentOutRecordId.value,
		// 				"batteryCode": result
		// 		}
		// 		listBatteryData.value.push(oneBattery)
		// 		baseFormData.value.outQuantity = listBatteryData.value.length
		// 	}
		// })
	}
	
	const onHelmetScanClick = (e) =>{
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=outHelmet`, //
		});
		// uni.scanCode({
		// 	onlyFromCamera: true, //只能扫码
		// 	scanType: ["qrCode"],
		// 	success: function(res) {
		// 		const {
		// 			result
		// 		} = res;
		// 		const oneHelmet = {
		// 				"helmetEnterRecordId": "",
		// 				"componentOutRecordId": componentOutRecordId.value,
		// 				"helmetCode": result
		// 		}
		// 		listHelmetData.value.push(oneHelmet)
		// 		baseFormData.value.outQuantity = listHelmetData.value.length
		// 	}
		// })
	}
	
	const listInBatteryOptions = ref([{
		text: '删除',
		style: {
			backgroundColor: '#007aff'
		}
	}]);
	
	const listInHelmetOptions = ref([{
		text: '删除',
		style: {
			backgroundColor: '#007aff'
		}
	}]);
	
	const onInBatteryListClick = (e, index, item) =>{
		if(e.position == 'right'){
			if(e.index == 0){
				if (index != -1) {
				  listInBatteryData.value.splice(index,1); // 删除索引位置的元素
					baseFormData.value.enterQuantity = listInBatteryData.value.length;
				}
			}
		}		
	}
	
	const onInHelmetListClick = (e, index, item) =>{
		if(e.position == 'right'){
			if(e.index == 0){
				if (index != -1) {
				  listInHelmetData.value.splice(index, 1); // 删除索引位置的元素
					baseFormData.value.enterQuantity = listInHelmetData.value.length;
				}
			}
		}
	}
	
	const onInBatteryScanClick = (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": "",
		// 				"componentOutRecordId": componentOutRecordId.value,
		// 				"batteryCode": result
		// 		}
		// 		listInBatteryData.value.push(oneBattery)
		// 		baseFormData.value.enterQuantity = listInBatteryData.value.length
		// 	}
		// })
	}
	
	const onInHelmetScanClick = (e) =>{
		uni.navigateTo({
			url: `/pages/common/batchscancode?type=inHelmet`, //
		});
		// uni.scanCode({
		// 	onlyFromCamera: true, //只能扫码
		// 	scanType: ["qrCode"],
		// 	success: function(res) {
		// 		const {
		// 			result
		// 		} = res;
		// 		const oneHelmet = {
		// 				"helmetEnterRecordId": "",
		// 				"componentOutRecordId": componentOutRecordId.value,
		// 				"helmetCode": result
		// 		}
		// 		listInHelmetData.value.push(oneHelmet)
		// 		baseFormData.value.enterQuantity = listInHelmetData.value.length
		// 	}
		// })
	}
</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{
		line-height: 50px;
		border-bottom: 1px solid #f4f4f4;
	}
	
	.uni-section{
		margin: 20px 0px;
	}
	
	.uni-section-header{
		border-top: 1px solid #f4f4f4;
		border-bottom: 1px solid #f4f4f4;
	}
</style>