<template>
	<z-paging ref="paging" v-model="listdata" @query="loadMoreData" :default-page-no="1" :default-page-size="5"
		:auto-show-back-to-top="true">
		<template #top>
			<view class="flex">
				<view class="search">
					<uni-search-bar radius="5" placeholder="输入车辆编号查询" v-model="bikeCodeValue" @blur="searchInfo"
						@confirm="search" />
				</view>
				<view class="searchmore" @click="showDrawer('showRight')">
					<image :src="`${imgPath}static/image/更多.png`" alt="" />
				</view>
			</view>
		</template>
		<view class="container">
			<checkbox-group @change="checkboxGroupChange">
				<view v-for="(item, index) in listdata" :key="index" class="list-item">
					<view class="flex list-title" @click="opendetail(item.bikeId)">
						<view v-if="item.state==1 && item.stateName=='待投放'" class="title-xz">
							<checkbox :value="item.bikeCode" @click.stop></checkbox>
						</view>
						<view class="title-wz">
							{{item.bikeCode}}
						</view>
						<view v-if="item.state==1" class="title-zt">
							<view v-if="item.stateName=='投放中'" class="cu-tag bg-blue sm ">{{item.stateName}}</view>
							<view v-else class="cu-tag bg-orange sm ">{{item.stateName}}</view>
						</view>
						<view v-else class="title-zt">
							<view class="cu-tag bg-green sm ">{{item.stateName}}</view>
						</view>
					</view>
					<view class="flex row">
						<view class="list-name">
							车辆编号
						</view>
						<view class="list-value">
							{{item.bikeCode}}
						</view>
					</view>
					<view class="flex row">
						<view class="list-name">
							车辆型号
						</view>
						<view class="list-value">
							{{item.bikeModel}}
						</view>
					</view>
					<view class="flex row">
						<view class="list-name">
							入库时间
						</view>
						<view class="list-value">
							{{item.enterTime}}
						</view>
					</view>
				</view>
			</checkbox-group>
		</view>
		<template #bottom>

			<view class="nav-panel">
				<uni-goods-nav :fill="true" :options="[]" :buttonGroup="navButtonGroup" @buttonClick="navButtonClick" />
			</view>
		</template>
	</z-paging>
	<uni-drawer ref="showRight" mode="right" :mask-click="false">
		<view>
			<uni-nav-bar left-icon="left" leftText="返回" rightText="X" title="筛选" @clickLeft="closeDrawer('showRight')"
				@clickRight="closeDrawer('showRight')" />
		</view>
		<view class="searchlist">
			<uni-section title="入库时间" type="line">
				<uni-datetime-picker type="date" return-type="timestamp" v-model="enterTime" />
			</uni-section>
			<uni-section title="状态" type="line">
				<uni-data-checkbox mode="tag" v-model="statevalue" :localdata="sjztlist" />
			</uni-section>
		</view>
	</uni-drawer>
	<view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="changepopup">
			<view class="popup-content" :class="{ 'popup-height': typepopup === 'left' || typepopup === 'right' }">
				<view class="padding plcrk">
					<uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData">
						<uni-section v-if="statusZT==2" title="站点" type="line">
							<uni-forms-item required name="reginvalue">
								<uni-data-select v-model="customFormData.reginvalue" :localdata="regindata"
									@change="changeZT"></uni-data-select>
							</uni-forms-item>
						</uni-section>
						<uni-section title="请添加设备" type="line">
							<uni-forms-item required name="deviceValues">
								<uni-easyinput type="textarea" v-model="customFormData.deviceValues"
									placeholder="请输入车辆编号，用逗号(，)隔开，一次最多添加1000个" />
							</uni-forms-item>
						</uni-section>
					</uni-forms>
					<view class="button-group">
						<button style="width: 100%;" type="primary" @click="submit" size="mini">提交</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view> 
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import * as api from '@/utils/api.js';
	import config from '@/utils/config';
	import {
		onShow
	} from '@dcloudio/uni-app';
	const imgPath = config.imgPath;
	const listdata = ref([]);
	const popup = ref(null)
	const typepopup = ref("center"); 
	const navButtonGroup = [{
		text: '批量投放',
		backgroundColor: '#0078D4',
		color: '#fff'
	}, {
		text: '批量下架',
		backgroundColor: '#0078D4',
		color: '#fff'
	}];
	const searchValue = ref("")
	const rangevalue = ref(0);

	//运营区域下拉值 和列表 
	const regindata = ref([])
	onShow(() => {
		loadMoreData(1, 5);
		selectedItems.value=[]
	})

	//提交表单相关信息
	const customForm = ref(null)
	const customFormData = ref({
		reginvalue: "",
		deviceValues: ""
	})

	// 校验规则
	const customRules = ref({
		reginvalue: {
			rules: [{
				required: true,
				errorMessage: '站点信息不能为空',
				trigger: 'blur'
			}]
		},
		deviceValues: {
			rules: [{
				required: true,
				errorMessage: '车辆编号不能为空！',
				trigger: 'blur'
			}]
		}
	})


	// 查询条件定义
	const pageNum = ref(1);
	const pageSize = ref(10);
	const bikeCodeValue = ref(""); //车辆编号
	const enterTime = ref(null); //入库时间
	const statevalue = ref('1,2'); //状态
	const sjztlist = ref([{
		text: '全部',
		value: '1,2'
	}, {
		text: '待投放',
		value: 1
	}, {
		text: '已投放',
		value: 2
	}])

	const paging = ref(null);
	const status = ref('more'); //,more,loading，noMore
	const selectedItems = ref([]);
	const usableHeight = ref(0);
	onMounted(() => {
		// 获取设备信息
		const systemInfo = uni.getSystemInfoSync();
		// 获取屏幕高度和状态栏高度
		const screenHeight = systemInfo.screenHeight;
		const statusBarHeight = systemInfo.statusBarHeight;
		// 计算去掉状态栏后的可用区域高度
		usableHeight.value = screenHeight - statusBarHeight - 170;
		// getUserRegionInfo(); 
		let userDefultOperation = uni.getStorageSync('userDefultOperation');
		//获取站点信息 
		api.callOperateApi("ebikeRegion/getRegion?regionId=" + userDefultOperation.operationRegionId, {}, "get").then(
			res => {
				if (res.code == 200) {
					res.data.forEach(res => {
						let quyuemap = {
							"text": res.siteName,
							"value": res.siteRegionId
						};
						regindata.value.push(quyuemap);
					});
				}
			})


	});

	const getUserRegionInfo = () => {
		api.callOperateApi("ebikeRegion/pageSite?pageNum=1&pageSize=20", {}, "get").then(res => {
			if (res.code == 200) {

			}
		})
	}
	const checkboxGroupChange = (e) => {
		selectedItems.value = e.target.value
	}
	const opendetail = (id) => {
		setTimeout(() => {
			uni.navigateTo({
				url: `/pages/warehouse/ebikehouse/vehicleoperation_view?ebikeId_zcck=${id}`, //
			});
		}, 200); // 延迟100毫秒后执行 
	}
	const loadMoreData = (pageNo, pageSize) => { 
		// 组装参数
		const params = {
			"bikeCode": bikeCodeValue.value, //车辆编号
			"enterTime": enterTime.value, //入库时间 例：2025-03-21
			"state": statevalue.value,
			"pageParam": {
				"pageNum": pageNo,
				"pageSize": pageSize
			}
		}

		api.callEbikeInfo("getOperationalBikeList", params).then((res) => {
			if (res.code === 200) {
				const records = res.data.records;
				paging.value.complete(res.data.records);
			} else {
				paging.value.complete(false);
			} 
		});
	};

	const submit = (ref) => {
		customForm.value.validate().then(res => {
			if (statusZT.value == 0) { // 下架
				handleLeaveWarehouse();
			} else { // 投放
				handleLaunch();
				// uni.navigateTo({
				// 	url: `/pages/warehouse/vehicledispatch/vehicledispatch?orderId=274372153543897088`
				// });
			}
		}).catch(err => {
			console.log('err', err);
		});
	}

	// 处理下架逻辑
	const handleLeaveWarehouse = () => {
		const params = {
			"bikeCode": customFormData.value.deviceValues, // 车辆编号
			"status": statusZT.value,
			"reginId": ""
		}
		api.callEbikeInfo("vehicleLeaveWarehouse", params).then((res) => {
			if (res.code == 200) {
				popup.value.close("center");
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 2000
				});
				searchInfo();
			} else {
				uni.showToast({
					title: '操作失败',
					icon: 'error',
					duration: 2000
				});
			}
		})
	}

	// 处理投放逻辑
	const handleLaunch = () => {
		// 在这里编写投放的具体逻辑
		console.log('投放逻辑执行');
		const params = {
			"bikeCodes": customFormData.value.deviceValues, // 车辆编号
			"status": statusZT.value,
			"siteId": customFormData.value.reginvalue,
			"dispatchType": "仓库车调度"
		}
		// 例如，调用API处理投放
		api.callEbikeInfo("createWorkOrderDispatch", params).then((res) => {
			if (res.code == 200) {
				popup.value.close("center");
				// 显示成功提示
				uni.showToast({
					title: '操作成功',
					icon: 'success',
					duration: 1000
				});
				// 延时跳转，确保提示完毕后再跳转
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/warehouse/vehicledispatch/vehicledispatch?orderId=${res.data}`
					});
				}, 1000); // 跳转延迟与提示时长一致
			} else {
				uni.showToast({
					title: '操作失败',
					icon: 'error',
					duration: 2000
				});
			}
		})
	}



	const onPullDownRefresh = () => {
		console.log('onPullDownRefresh')
		setTimeout(function() {
			uni.stopPullDownRefresh()
			console.log('stopPullDownRefresh')
		}, 1000)
	}
	// 创建 drawer 的 ref 引用
	const showRight = ref(null);

	// 打开窗口
	const showDrawer = (e) => {
		const drawer = showRight.value
		drawer.open()
	}
	// 关闭窗口
	const closeDrawer = (e) => {
		const drawer = showRight.value
		drawer.close();
		searchInfo();
	}

	//搜索
	const searchInfo = () => {
		paging.value.reload();
	}
	const changeZT = (e) => {
		console.log("e:", e);
	}
	const statusZT = ref(1);

	const handleScroll = (e) => {
		// scroTop.value = e.target.scrollTop
	}
	const scrollToTop = () => { //回到顶部
		scroTop.value = scroTop.value != 0 ? 0 : 1
	}
	const changepopup = (e) => {

	}
	//批量出库事件按钮
	const navButtonClick = (res) => {
		const {
			index,
			content
		} = res;
		if (index == 0) //批量投放
		{
			uni.showModal({
				title: '批量投放',
				content: '您确定要进行投放操作吗？',
				success: (res) => {
					if (res.confirm) {
						customFormData.value.deviceValues = selectedItems.value
						popup.value.open("center");
						statusZT.value = 2;
					} else if (res.cancel) {}
				}
			});
		} else if (index == 1) { //批量下架 
			uni.showModal({
				title: '批量下架',
				content: '您确定要进行下架操作吗？',
				success: (res) => {
					if (res.confirm) {
						customFormData.value.deviceValues = selectedItems.value
						popup.value.open("center");
						statusZT.value = 0;
					} else if (res.cancel) {
						// 用户点击了取消 
					}
				}
			});

		}
	}
</script>

<style scoped>
	.container {
		padding: 10px 0px 0px 0px;
		background-color: #f3f4f6;
	}

	.list-title {
		margin: 5px 0px;
		border-bottom: 1px solid #f0f0f0;
	}

	.list-title .title-xz {
		margin: 5px;
	}

	.list-title .title-wz {
		margin-left: 5px;
		font-size: 14px;
		line-height: 35px;
		font-weight: bold;
	}

	.list-title .title-zt {
		margin-left: 8px;
		margin-top: 5px;
	}

	.list-item {
		background: #fff;
		padding: 10px;
		margin: 10px;
		border-radius: 5px;
	}

	button {
		margin-top: 20px;
		padding: 10px;
		background-color: #007aff;
		color: white;
		border-radius: 5px;
	}

	.list-name {
		color: #999999;
		font-size: 12px;
		width: 30%;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
	}

	.list-value {
		width: 70%;
		color: #4F4F53;
		font-size: 13px;
		font-weight: 400;
	}

	.row {

		margin: 8px 5px;
	}

	.scroll-view {
		height: 100%;
	}

	.example-body {
		padding: 10px;
	}

	.scroll-view {
		/* #ifndef APP-NVUE */
		width: 100%;
		height: 100%;
		/* #endif */
		flex: 1
	}

	.scroll-view-box {
		flex: 1;
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
	}

	.info {
		padding: 15px;
		color: #666;
	}

	.info-text {
		font-size: 14px;
		color: #666;
	}

	.info-content {
		padding: 5px 15px;
	}

	.close {
		padding: 10px;
	}

	.search {
		width: 90%;
	}

	.searchmore {
		width: 10%;
		padding-top: 15px;
	}

	.searchmore image {
		width: 25px;
		height: 25px;
	}

	.searchlist {
		padding: 15px;
	}

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

	.plcrk {
		width: 240px;
		height: 360px;
	}
</style>