<template>
	<BasicContainer ref="basicContainer" :option="option">
		<template #head>
			<image mode="widthFix" class="bgimg" src="@/pagesHome/static/bgby.png"></image>
			<view class="header">
				<view class="">
					<text>订单号：</text>
					<text>{{details.pageInfo.orderCode}}</text>
				</view>

				<view class="mt20 flex-c-sb">
					<view class="text-center ">
						<view>计划数量</view>
						<view class="mt10 value ">{{details.data.planNum || 0}}</view>
					</view>

					<view class="text-center">
						<view>已备数量</view>
						<view class="mt10 value green">{{details.data.scanNum || 0}}</view>
					</view>

					<view class="text-center ">
						<view>未备数量</view>
						<view class="mt10 value red">{{(details.data.planNum || 0) - (details.data.scanNum || 0)}}</view>
					</view>
				</view>
			</view>
		</template>

		<template #body>
			<scroll-view scroll-y="true" @touchmove.stop :style="{height: details.scrollHeight}" class="scvew">
				<view class="pullDown_container">
					<!-- 在库数据 -->
					<view class="mb20" v-show="details.allocationList.length > 0">
						<PullDownBox ref="PullDownRef1">
							<template #title>
								<view class="fwb align-center">
									<text class="mr20">
										在 库 数 据
									</text>

									<text>
										{{
											details.allocationTotal
										}}
									</text>
								</view>
							</template>

							<template #content>
								<block v-for="(item, index) in details.allocationList" :key="item.allocationid">
									<view @click="()=>handleStockUpZero(item, 1)"
										:class="{mb20:index !== details.allocationList.length - 1, item_contariner: true}">
										<view class="flex-c-sb ">
											<view class="">
												<text class="mr10">库位：</text>
												<text>{{item.allocationName}}</text>
											</view>

											<view style="width: 35%;">
												<text class="mr10">在库数：</text>
												<text>{{item.num}}</text>
											</view>
										</view>
									</view>
								</block>
							</template>
						</PullDownBox>
					</view>

					<!-- 在托数据 -->
					<view class="mb20" v-show="details.trayList.length > 0">
						<PullDownBox ref="PullDownRef2">
							<template #title>
								<view class="fwb align-center">
									<text class="mr20">
										在 托 数 据
									</text>

									<text>
										{{
											details.trayTotal
										}}
									</text>
								</view>
							</template>

							<template #content>
								<block v-for="(item, index) in details.trayList" :key="item.allocationid">
									<view @click="()=>handleStockUpZero(item, 2)"
										:class="{mb20:index !== details.trayList.length - 1, item_contariner: true}">
										<view class="flex-c-sb ">
											<view class="">
												<text class="mr10">托盘名称：</text>
												<text>{{item.trayName}}</text>
											</view>

											<view style="width: 35%;">
												<text class="mr10">在库数：</text>
												<text>{{item.num}}</text>
											</view>
										</view>
									</view>
								</block>
							</template>
						</PullDownBox>
					</view>

					<!-- 其它数据 -->
					<view v-show="details.other.num">
						<PullDownBox ref="PullDownRef3">
							<template #title>
								<view class="fwb align-center">
									<text class="mr20">
										其 它 数 据
									</text>

									<text>
										{{
											details.other.num
										}}
									</text>
								</view>
							</template>

							<template #content>
								<view class="item_contariner" @click="()=>handleStockUpZero(details.other, 3)">
									<view>
										<text class="mr10">在库数：</text>
										<text>{{details.other.num}}</text>
									</view>

									<!-- <view class="mt20 flex-c-c">
																				<view>
											备货数：
										</view>

										<view class="flex1">
											<InputNum v-model="details.other.scanNum" :maxNum="details.other.num"></InputNum>
										</view>

										<view class="button">备货</view>
									</view> -->

								</view>
							</template>
						</PullDownBox>
					</view>
				</view>
			</scroll-view>
		</template>
	</BasicContainer>
	<tiplist ref="tiplists"></tiplist>
	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->
	<BluetoothList ref="bluetoothList"></BluetoothList>

	<!-- 零担备货 -->
	<PopUp ref="StockUpZero">
		<view class="pd10">
			<!-- 库位 -->
			<template v-if="details.type === 1">
				<view class="item_contariner">
					<view class="flex-c-sb">
						<view class="">
							<view class="mr10">库位：</view>
							<view>{{details.stockUpInfo.allocationName}}</view>
						</view>

						<view style="width: 35%;">
							<view class="mr10">在库数：</view>
							<view>{{details.stockUpInfo.num}}</view>
						</view>
					</view>
				</view>
			</template>

			<!-- 托盘 -->
			<template v-if="details.type === 2">
				<view class="item_contariner">
					<view class="flex-c-sb ">
						<view class="">
							<view class="mr10">托盘名称：</view>
							<view>{{details.stockUpInfo.trayName}}</view>
						</view>

						<view style="width: 35%;">
							<view class="mr10">在库数：</view>
							<view>{{details.stockUpInfo.num}}</view>
						</view>
					</view>
				</view>
			</template>

			<!-- 其它 -->
			<template v-if="details.type === 3">
				<view class="item_contariner">
					<view>
						<text class="mr10">在库数：</text>
						<text>{{details.stockUpInfo.num}}</text>
					</view>
				</view>
			</template>


			<view class="mt20 flex-c-c">
				<view>
					备货数：
				</view>

				<view class="flex1">
					<InputNum v-model="details.stockUpInfo.scanNum" :maxNum="details.stockUpInfo.maxNum"></InputNum>
				</view>
			</view>
		</view>
	</PopUp>
</template>

<script lang="ts" setup>
	import {
		onLoad,
		onShow,
	} from '@dcloudio/uni-app'
	import {
		postZeroStockUpData,
		postZeroStockUp
	} from '@/api/user.js'
	import { reactive, ref, onMounted, nextTick } from "vue";
	import useBluetoothStore from '@/store/useBluetoothStore.js';
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import utils from '@/utils/utils.js';
	import { storeToRefs } from 'pinia';
	const { scanState } = storeToRefs(useSystemSettingsStore())
	const bluetoothList = ref(null)
	const bluetoothStore = useBluetoothStore()
	const { bluetoothInfo } = storeToRefs(bluetoothStore)
	// 获取组件实例
	const tiplists = ref(null)
	const basicContainer = ref(null)
	/** 切换库位 */
	const StockUpZero = ref(null)
	// 基础组件配置项
	const option = {
		title: '备货列表',
		haveData: true,
		async pullDownRefreshInitPage() {
			await initpage()
		}
	}
	// 页面变量定义
	let details = reactive({
		pageInfo: {} as any,
		scancode: '',
		scrollHeight: '',
		/** 其它 */
		other: {},
		/** 托盘 */
		trayList: [],
		trayTotal: 0,
		/** 库位 */
		allocationList: [],
		allocationTotal: 0,
		/** 页面数据 */
		data: {} as any,
		/** 备货所在类型, 1 -- 库位, 2 -- 托盘, 3 -- 其它 */
		type: 1 as 1 | 2 | 3,
		/** 备货数据 */
		stockUpInfo: {},
		/** 备货库位ID */
		stockupAllocationId: '',
		/** 备货库位名称 */
		stockupAllocationName: '',
	})

	const PullDownRef1 = ref()
	const PullDownRef2 = ref()
	const PullDownRef3 = ref()

	onLoad((op) => {
		details.pageInfo = JSON.parse(op.info)
		console.log('details.pageInfo :>> ', details.pageInfo);
		// #ifdef APP
		utils.ttsspke('请选择零担进行备货')
		// #endif
	})
	onShow(async () => {
		// #ifdef APP
		uni.$off('scancodedate')
		uni.$on('scancodedate', function (code) {
			if (code) {
				details.scancode = code
				scandata()
			}
		})
		// #endif
		// 页面显示延时调用组件刷新函数

		await nextTick()

		basicContainer.value.startPullDownRefresh()

	})

	onMounted(async () => {
		await nextTick()
		details.scrollHeight = await utils.getViewDistanceFormTop('.scvew')

	})

	async function initpage() {
		try {
			const submitData = {
				typeService: details.pageInfo.typeService,
				stockupId: details.pageInfo.stockupId,
				allocationId: details.pageInfo.allocationId,
				orderCode: details.pageInfo.orderCode,
				stockArticleId: details.pageInfo.stockArticleId,
				reservationId: details.pageInfo.reservationId,
			}

			const res = await postZeroStockUpData(submitData)

			const { code, data } = res

			if (code !== 200) return
			details.data = data || {}

			console.log('details.data :>> ', details.data);

			details.other = details.data.other || []
			details.allocationList = details.data.allocationList || []
			details.trayList = details.data.trayList || []

			details.allocationTotal = 0
			for (var i = 0; i < details.allocationList.length; i++) {
				details.allocationTotal += Number(details.allocationList[i].num)
			}

			details.trayTotal = 0
			for (var i = 0; i < details.trayList.length; i++) {
				details.trayTotal += Number(details.trayList[i].num)
			}

			await nextTick()
			console.log('PullDownRef1.value :>> ', PullDownRef1.value);
			console.log('PullDownRef2 :>> ', PullDownRef2);
			console.log('PullDownRef3 :>> ', PullDownRef3);
			// 展开下拉框
			PullDownRef1.value.handleShowPullDown(true)
			PullDownRef2.value.handleShowPullDown(true)
			PullDownRef3.value.handleShowPullDown(true)

		} catch (err) {
			console.log('err :>> ', err);
			//TODO handle the exception
		} finally {
			return null
		}
	}

	/** 扫描接口
	 * */
	async function scandata() {

	}

	const handlePrintZeroOrder = async (item, _inputValue) => {
		// #ifdef APP
		let _isReturn = false
		for (let i = 0; i < _inputValue; i++) {
			if (_isReturn) return
			console.log('i :>> ', i);
			let text = '! 0 200 200 333 1\r\n'
			text += 'SETBOLD 2\r\n'
			text += `T 56 0 0 0 ${item.orderCode}\r\n`
			text += 'LINE 0 50 420 50 3\r\n'
			text += `T 55 0 0 60 客户\r\n`
			text += 'LINE 40 50 40 110 3\r\n'
			text += `T 55 0 50 60 ${details.user.consignee || ''}\r\n`
			text += 'LINE 40 80 420 80 3\r\n'
			text += `T 55 0 50 90 ${details.user.goodsAreaName || ''}\r\n`
			text += 'LINE 0 110 420 110 3\r\n'
			text += `T 55 0 0 120 物料\r\n`
			text += 'LINE 40 110 40 140 3\r\n'
			text += `T 55 0 50 120 ${item?.materialName || ''}\r\n`
			text += 'LINE 0 140 420 140 3\r\n'
			text += 'B QR 150 150 M 2 U 4\r\n'
			text += `MA,${item.orderCode}\r\n`
			text += 'ENDQR\r\n'
			text += `T 55 0 140 260 ${item.orderCode}\r\n`
			text += 'FORM\r\n'
			text += 'PRINT\r\n'
			utils.initbl()
			await utils.getbl(bluetoothInfo.value, text).catch(() => {
				bluetoothList.value.setdetails({ isshow: true, success() { handlePrintZeroOrder(item, _inputValue) } })
				_isReturn = true
			})
		}

		if (_isReturn) return
		// #endif
	}

	/** 处理并显示弹窗
	 *	 type : 1 -- 库位, 2 -- 托盘, 3 -- 其它
	 */
	const handleStockUpZero = (value : any, type : 1 | 2 | 3) => {
		details.stockUpInfo = { ...value }

		const _max = (details.data.planNum || 0) - (details.data.scanNum || 0)

		console.log('details.stockUpInfo :>> ', details.stockUpInfo);

		details.stockUpInfo.maxNum = _max > details.stockUpInfo.num ? details.stockUpInfo.num : _max
		details.stockUpInfo.scanNum = 0

		details.type = type

		console.log('details.pageInfo :>> ', details.pageInfo);

		StockUpZero.value.setDetails({
			title: '零担备货',
			showPopUp: true,
			async success() {
				const { scanNum, maxNum } = details.stockUpInfo as any

				if (scanNum > maxNum) return utils.handleToast('不能大于已备数量')

				const submitData : any = {
					num: scanNum,
					orderId: details.data.orderId,
					orderCode: details.pageInfo.orderCode,
					stockupId: details.pageInfo.stockupId,
					typeService: details.pageInfo.typeService,
					stockArticleId: details.pageInfo.stockArticleId,
					reservationId: details.pageInfo.reservationId,
					stockupAllocationId: details.pageInfo.stockupAllocationId,
					stockupAllocationName: details.pageInfo.stockupAllocationName,
				}

				console.log('submitData :>> ', submitData);

				// 库位
				if (type === 1) submitData.allocationId = value.allocationid
				else if (type === 2) submitData.trayId = value.trayId

				const res = await postZeroStockUp(submitData)

				const { code, data } = res

				if (code !== 200) return
				StockUpZero.value.details.showPopUp = false
				basicContainer.value.startPullDownRefresh()
			}
		})
	}
</script>

<style lang="scss" scoped>
	@import url(@/utils/style/common.scss);

	// 背景图
	.bgimg {
		position: absolute;
		width: 100% !important;
		top: -180upx;
		width: 0;
		z-index: 1;
	}

	// 头部
	.header {
		z-index: 10;
		position: relative;
		padding: 20upx;
		background-color: #fff;
		margin: 20upx;
		// height: 80px;
		border-radius: 10upx;
		font-weight: bold;

		.value {
			color: #3c86ef;

			&.red {
				color: #f00;
			}

			&.green {
				color: #7ba931;
			}

		}
	}

	// 下拉
	.pullDown_container {
		padding: 20upx;
	}

	:deep(.PullDownBox) {
		background: var(--subjectColor);
		border-radius: 10upx;

		.Pulldown_content {
			background: #fff;
		}
	}

	:deep(.Pulldown-title-container) {
		color: #fff;

		.u-icon__icon {
			color: #fff !important;
		}
	}

	:deep(.inputNum) {
		background: #f4f8fb;
		border: none;
		padding: 15upx 25upx;
		border-radius: 10upx;
	}

	.item_contariner {
		box-shadow: 0 0 15upx #acc;
		padding: 20upx 15upx;
		border-radius: 5upx;
	}

	// 按钮
	.button {
		padding: 15upx 80upx;
		background: var(--subjectColor);
		color: #fff;
		border-radius: 10upx;
	}
</style>