<template>
	<view>
		<!-- 顶部导航栏 -->
		<u-navbar :title="title" placeholder :autoBack="true" leftIconSize='35' bgColor='#d3832a' leftIconColor='#ffffff'
			titleStyle='color:#ffffff'></u-navbar>
	</view>

	<!-- 主体内容 -->
	<view class="main">
		<!-- 随机盘点 -->
		<template v-if="pageType === 1">
			<!-- 表格 -->
			<view class="table">
				<!-- 表格头部 -->
				<view class="thead">

				</view>

				<!-- 表格主体 -->
				<view class="tbody">

				</view>
			</view>
		</template>

		<!-- 按库位盘点 -->
		<template v-if="pageType === 2">
			<!-- 顶部 -->
			<view class="main_top">
				<input type="text" v-model="details.scancode" placeholder="请输入库位码" class="main_top_search" />
				<view class="button" @click="scandata">搜索</view>
			</view>

			<!-- 表格 -->
			<view class="table" v-for="item in renderList">
				<view class="tpbx" @click="goStorageDetails(item)">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>库位码：{{item.positionCode}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>总件数：{{item.total}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>盘点件数：{{item.unTotal}}</view>
				</view>
			</view>
		</template>

		<!-- 按合同号盘点 -->
		<template v-if="pageType === 3">
			<!-- 顶部 -->
			<view class="main_top">
				<view class="select">
					<view class="dropdown-btn" @tap="toggleDropdown">
						{{ selectedValue.label }}
					</view>
					<view v-show="isDropdownOpen" class="dropdown-list">
						<view v-for="option in options" :key="option.value" @tap="selectOption(option)">
							{{ option.label }}
						</view>
					</view>
				</view>
				<input @input="handleInputChange" type="text" v-model="details.scancode"
					:placeholder="selectedValue.placeholder" class="main_top_search htselect" />
				<view class="button" @click="ContractSearch">搜索</view>
			</view>

			<!-- 表格 -->
			<view class="table" v-for="item in renderList">
				<view class="tpbx" @click="contract(item)">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>合同号：{{item.orderCode}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>总件数：{{item.total}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>在库件数：{{item.zktotal}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>盘点件数：{{item.unTotal}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>是否库存品: {{ item.isInventory === 0 ? "不是" : "是" }}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>是否零担: {{ item.isZero === 0 ? "不是" : "是" }}</view>
				</view>
			</view>
		</template>

		<!-- 按托盘盘点 -->
		<template v-if="pageType === 4">
			<!-- 顶部 -->
			<view class="main_top">
				<input type="text" v-model="details.scancode" placeholder="请输入托盘码" class="main_top_search" />
				<view class="button" @click="searchTary">搜索</view>
			</view>

			<!-- 表格 -->
			<view class="table" v-for="item in renderList">
				<view class="tpbx" @click="goTrayDetails(item)">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>托盘码：{{item.trayCode}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>总件数：{{item.total}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>货物类型：{{item.goodsType}}</view>
				</view>
				<view class="tpbx">
					<image src="/pagesHome/static/kuweiicon.png"></image>
					<view>盘点件数：{{item.unTotal}}</view>
				</view>
			</view>
		</template>

		<view v-show="isEnd" class="footer-end">
			到底啦
		</view>
	</view>
	<saomiao2></saomiao2>
</template>

<script setup lang="ts">
	import {
		onShow,
		onLoad,
		onHide,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import { ref, reactive, toRefs } from "vue";

	import {
		getWarehouseTaskAllocationList,
		getWarehouseTrayList,
		getWarehouseTaskAllocationDetailByStrip,
		postqueryContractList,
		pgetContractList
	} from '@/api/user.js';
	import utils from '@/utils/utils.js';

	const details = reactive({
		// 页面标题
		title: '',
		// 页面类型 1: 随机盘点; 2: 按库位盘点; 3: 按合同号盘点; 4: 按托盘盘点;
		pageType: 1,
		// 扫描后的值
		scancode: '',
		searchText: {
			storageText: '',
			taryText: ''
		},
		// 商场名称
		marketName: [],
		id: '',
		isscan: true,
		page: {
			// 当前页码
			current: 1,
			// 每页数量
			size: 10,
		},
		// 渲染列表
		renderList: [],
		// 数据是否加载完毕
		isEnd: false,
		warehouseId: '',
		questNum: ''
	})
	const placeholder = ref('请输入')
	const isDropdownOpen = ref(false) // 控制下拉选择列表的显示隐藏
	const selectedValue = ref({
		value: '1', label: '定制品', placeholder: '请输入或扫描包条码'
	})   // 选中的值
	const options = ref([  // 下拉选项
		{ value: '1', label: '定制品', placeholder: '请输入或扫描包条码' },
		{ value: '2', label: '库存品', placeholder: '请输入物料编码' },
	])

	const toggleDropdown = () => {
		isDropdownOpen.value = !isDropdownOpen.value;  // 点击下拉按钮，切换下拉列表显示隐藏
	}
	const selectOption = (option) => {
		selectedValue.value = option; // 选中某个选项后，更新选择的值
		if (option.value == 1) {//修改
			placeholder.value = '请输入合同号'
		} else {
			placeholder.value = '请输入物料编码'
		}
		console.log(option);
		isDropdownOpen.value = false; // 关闭下拉列表
	}
	// 页面地址初始化值用于input清空重新渲染
	const infodata = ref({

	})
	// 页面初始化执行回调
	onLoad((info) => {
		console.log('info :>> ', info);
		const { pageType, data } = JSON.parse(info.data)
		details.title = data.title
		details.pageType = pageType
		details.id = data.id
		details.warehouseId = data.warehouseId
		details.marketName = data.marketName
		details.questNum = data.questNum

		if (details.pageType === 3) {
			infodata.value = data
		}
	})

	// 开启监听扫描
	onShow(() => {
		uni.$on('scancodedate', function (code) {
			if (code) {
				console.log('code :>> ', code);
				details.scancode = code

				scandata()
			}
		})
		// 库位盘点时, 允许扫码
		if (details.pageType === 1) details.isscan = false

		// 初始化请求页面数据
		initPage()

		if (details.pageType === 1) return
		else if (details.pageType === 2) return utils.ttsspke('请扫描库位码')
		else if (details.pageType === 3) return utils.ttsspke('请扫描包条码或输入订单自编码')
		else if (details.pageType === 4) return utils.ttsspke('请扫描托盘')
	})

	// 关闭扫描监听
	onHide(() => {
		uni.$off('scancodedate')
	})

	// 添加防抖函数
	let antiShake : any = null
	// 触底加载
	onReachBottom(() => {
		// 数据请求完毕, 不再请求
		if (details.isEnd) return uni.showToast({
			title: '数据加载完毕',
			icon: 'success'
		})
		if (antiShake) {
			uni.hideLoading()
			// 清空定时器
			clearTimeout(antiShake)
			return antiShake = null
		}
		uni.showLoading({
			mask: true,
			title: '数据加载中'
		})
		antiShake = setTimeout(async () => {
			// // 当前页码 +1
			// details.page.current += 1
			// // 请求页面数据
			// await initPage()
			uni.hideLoading()
		}, 500)
	})

	// 下拉刷新
	onPullDownRefresh(() => {
		console.log('111 :>> ', 111);
		// 重置页码
		details.page.current = 1
		// 恢复结束状态
		details.isEnd = false
		// 清空渲染列表
		details.renderList = []
		const timer = setTimeout(async () => {
			const res = await initPage()
			uni.stopPullDownRefresh()
			clearTimeout(timer)
		}, 500)
	})

	// 请求页面数据
	async function initPage() {
		try {
			let res : any = null
			uni.showLoading({
				mask: true,
				title: '数据加载中'
			})
			if (details.pageType === 1) return
			if (details.pageType === 2) {
				// 货位id
				// type: 搜索的type, 1是手输, 2是扫描
				res = await getWarehouseTaskAllocationList({
					...details.page,
					questId: details.id,
					questNum: details.questNum
				})
			}

			else if (details.pageType === 3) {
				res = await pgetContractList({
					...details.page,
					taskId: infodata.value.id,
					warehouseId: infodata.value.warehouseId,
					questNum: details.questNum
				})
			}

			else if (details.pageType === 4) {
				res = await getTaryList()
			}
			console.log('res :>> ', res);
			const { code, data } = res
			if (code === 200 && data) {
				if (details.pageType === 3) {
					details.renderList = res.data.records
				} else details.renderList = data.list || []
				console.log('data.list :>> ', data.list);
				if (data.length < details.page.size) details.isEnd = true
			} else if (code === 3001) {
				const msg = data.audio
				utils.ttsspke(msg)
				uni.showToast({
					icon: 'error',
					title: msg
				})
			}
			return res
		} catch (error) {
			//TODO handle the exception
			console.log('error :>> ', error);
		} finally {
			uni.hideLoading()
		}
	}

	async function getTaryList() {
		console.log('details.id :>> ', details.id);
		const submitData : any = {
			...details.page,
			taskId: details.id,
			questNum: details.questNum
		}
		submitData.trayCode = details.scancode
		console.log('submitData :>> ', submitData);
		return getWarehouseTrayList(submitData)
	}

	// 扫描后执行的回调
	async function scandata() {
		try {
			// 是否允许扫码
			if (!details.isscan) return
			console.log('222 :>> ', 222);
			uni.showLoading({
				mask: true,
				title: '数据请求中'
			})

			// 库位盘点
			if (details.pageType === 2) {
				getWarehouseTaskAllocationDetailByStrip({
					questId: details.id,
					allocationId: details.scancode,
					questNum: details.questNum
				}).then(res => {
					console.log(res);
					if (res.code != 403) {
						console.log('跳转')
						uni.navigateTo({
							url: `/pagesTask/pages/storageLocationCheckDetails/storageLocationCheckDetails?allocationId=${details.scancode}&questId=${details.id}&marketName=${JSON.stringify(details.marketName)}&questNum=${details.questNum}`
						})
					}
				})
				return
			}

			if (details.pageType == 3) {
				postqueryContractList({
					taskId: details.id,
					goodsType: selectedValue.value.value,
					warehouseId: details.warehouseId,
					type: '1',
					code: details.scancode,
					questNum: details.questNum
				}).then(res => {
					console.log(res, 'res===');
					utils.ttsspke(res.audio)
					if (res.code != 3001) {
						details.renderList = res.data
					}
				})
				return
			}

			if (details.pageType === 4) {
				const res = await initPage()
				console.log('res :>> ', res);
				const { msg, code, data } = res
				uni.showToast({
					title: msg,
					icon: 'none'
				})
				if (code === 200 && data) {
					const info = {
						trayCode: data[0].trayCode,
						taskId: details.id,
						trayId: data[0].trayId,
						type: data[0].goodsType,
						marketName: details.marketName,
						// 是否阻止初始化请求
						holdBackFirstPost: true,
						questNum: details.questNum
					}
					console.log('info :>> ', info);
					uni.navigateTo({
						url: `/pagesTask/pages/trayCheckDetails/trayCheckDetails?info=${JSON.stringify(info)}`
					})
				}
			}
		} catch (err) {
			console.log('err :>> ', err);
			//TODO handle the exception
		} finally {
			uni.hideLoading()
		}
	}

	// 搜索
	const searchStorage = () => {
		getWarehouseTaskAllocationDetailByStrip({
			questId: details.id,
			allocationId: details.scancode,
			questNum: details.questNum
		}).then(res => {
			console.log('res >>>>>>>>', res);
			if (res.code !== 403) {
				uni.navigateTo({
					url: `/pagesTask/pages/storageLocationCheckDetails/storageLocationCheckDetails?allocationId=${details.scancode}&questId=${details.id}&marketName=${JSON.stringify(details.marketName)}&questNum=${details.questNum}`
				})
			}
		})
	}

	// 按库位盘点点击跳转到详情
	const goStorageDetails = (val) => {
		console.log('val :>> ', val);
		getWarehouseTaskAllocationDetailByStrip({
			questId: details.id,
			allocationId: val.allocationId,
			questNum: details.questNum
		}).then(res => {
			console.log(res);
			if (res.code != 403) {
				uni.navigateTo({
					url: `/pagesTask/pages/storageLocationCheckDetails/storageLocationCheckDetails?allocationId=${val.allocationId}&questId=${details.id}&marketName=${JSON.stringify(details.marketName)}&questNum=${details.questNum}`
				})
			}
		})
	}

	// 搜素托盘
	const searchTary = () => {
		if (!details.scancode) return uni.showToast({
			icon: 'none',
			title: '请输入托盘码'
		})
		// goTrayDetails(details.searchText.taryText)
		scandata()
	}

	// 去托盘盘点页面
	function goTrayDetails(item) {
		const info = {
			// 托盘码
			trayCode: item.trayCode,
			// 任务Id
			taskId: details.id,
			// 托盘Id
			trayId: item.trayId,
			// 货物类型
			type: item.goodsType,
			// 商城数组
			marketName: details.marketName,
			// 是否阻止初始化请求
			holdBackFirstPost: false,
			questNum: details.questNum
		}
		uni.navigateTo({
			url: `/pagesTask/pages/trayCheckDetails/trayCheckDetails?info=${JSON.stringify(info)}`
		})
	}

	// 按合同号盘点,点击进入详情
	const contract = (val) => {
		uni.navigateTo({
			url: `/pagesTask/pages/contracts/contracts?warehouseId=${details.warehouseId}&taskId=${details.id}&orderCode=${val.orderCode}&isInventory=${val.isInventory}&marketName=${JSON.stringify(details.marketName)}&martialCode=${val.martialCode}&questNum=${details.questNum}`
		})
	}
	// 按合同搜索按钮
	const ContractSearch = () => {
		postqueryContractList({
			taskId: details.id,
			goodsType: selectedValue.value.value,
			warehouseId: details.warehouseId,
			type: '2',
			incomingBatch: details.scancode,
			questNum: details.questNum
		}).then(res => {
			console.log(res, 'res===');
			utils.ttsspke(res.audio)
			if (res.code != 3001) {
				details.renderList = res.data
			}
		})
	}

	// 监听Input当输入框没有值重新渲染
	const handleInputChange = () => {
		console.log(details.searchText.taryText);
		if (!details.scancode) {
			pgetContractList({
				taskId: infodata.value.id,
				warehouseId: infodata.value.warehouseId,
				questNum: details.questNum
			}).then(res => {
				if (res.code = 200 && res.data) {
					details.renderList = res.data.records
				}
				utils.ttsspke(res.msg)

			})
		}

	}

	const {
		title,
		pageType,
		isEnd,
		renderList
	} = toRefs(details)
</script>

<style lang="scss" scoped>
	$buttonColor: #d3832a;

	// 本页按钮样式
	.button {
		font-size: 28upx;
		padding: 10upx 20upx;
		border: 1upx solid $buttonColor;
		background-color: #fff;
		color: #d3832a;
		border-radius: 5upx;
	}

	.main {
		padding: 10upx;
		font-size: 28upx; // 本页字体大小
	}

	.main_top {
		display: flex;
		// align-items: center;
		justify-content: space-between;
		margin-bottom: 10upx;

		// 顶部搜索框
		&_search {
			flex: 1;
			padding-left: 20upx;
			margin-right: 20upx;
			box-sizing: border-box;
			height: 28upx * 2;
			border-radius: 28upx;
			border: 1upx solid #000;
		}

		.button {
			background-color: $buttonColor;
			color: #fff;
			padding: 0 60upx;
			display: inline-flex;
			align-items: center;
		}
	}

	.table {
		margin-top: 10upx;
		box-shadow: 0 0 20upx #6f5050;
	}

	// 列表
	.tpbx {
		display: flex;
		align-items: center;
		// padding: 18upx 24upx;
		box-sizing: border-box;
		border-bottom: 4upx solid #EEEEEE;

		>image {
			flex: none;
			width: 32upx;
			height: 32upx;
			margin-right: 15upx;
		}

		>view {
			flex: 1;
			font-size: 28upx;
			font-weight: 400;
			color: #020B18;

			.numb {
				font-size: 28upx;
				color: #178AF2;
			}
		}
	}

	// 底部结束标语
	.footer-end {
		padding: 20upx 0;
		text-align: center;
	}
</style>