<template>
	<gui-page :custom-header="true" :header-class="['gui-theme-background-color']">
		<template #gHeader>
			<view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
				<!-- 使用组件实现返回按钮及返回首页按钮 -->
				<text style="font-size:44rpx;" class="gui-header-leader-btns gui-color-white font-icons"
					@tap="goBack">&#xe6c5;</text>
				<!-- 导航文本此处也可以是其他自定义内容 -->
				<text
					class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text">入库签收</text>
				<!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
				<!-- 实际宽度请根据自己情况设置 -->
				<view style="width:40px;" />
				<!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
			</view>
		</template>
		<template #gBody>
			<view class="list-content">
				<view class="scan">
					<view class="scan-card">
						<uni-easyinput ref="easyinput" v-model="scanNumber" :input-border="false" :clearable="false"
							type="text" focus @focus="handleInputFocus" placeholder="扫描完成品标签"
							@confirm="handleKeydown" />
						<text class="font-icons" @click="handleMapass">&#xe6b7;</text>
					</view>
				</view>
				<view class="scan">
					<view class="scan-card">
						<uni-easyinput ref="easyinput" v-model="employeeNum" :input-border="false" :clearable="false"
							type="text" focus @focus="handleInputFocus" placeholder="扫描/输入员工号签收"
							@confirm="handleInputPerson" />
						<text class="font-icons" @click="handleScanPerson">&#xe6b7;</text>
					</view>
				</view>
				<view class="scan">
					<view class="scan-card">
						<uni-easyinput ref="easyinput" v-model="storeNum" :input-border="false" :clearable="false"
							type="text" focus @focus="handleInputFocus" placeholder="请扫描库位信息" @confirm="handleInputStore" />
						<view style="display: flex; flex-direction: row;">
							<text class="font-icons" @click="selectModal.open('center')">&#xe6a8;</text>
							<text class="font-icons" @click="handleScanStore">&#xe6b7;</text>
						</view>
					</view>
				</view>
				<view class="store-list">
					<uni-row>
						<uni-col :span='3'>仓库：</uni-col>
						<uni-col :span='9'>{{ stockName }}</uni-col>
						<uni-col :span='3'>区域：</uni-col>
						<uni-col :span='9'>{{ areaName }}</uni-col>
					</uni-row>
					<uni-row>
						<uni-col :span='3'>货位：</uni-col>
						<uni-col :span='9'>{{ locationName }}</uni-col>
					</uni-row>
				</view>
				<view class="table-title">
					<span>入库需求清单</span>
				</view>
				<view class="custom-table">
					<view v-if="submitList?.length > 0" class="list-panel">
						<div v-for="(item, key) in submitList" :key="key" class="panel"
							@click="handleCheckedCard(item)">
							<div class="panel-row">
								<span>{{ item.workOrderNo }}</span>
							</div>
							<div class="panel-row">
								<span>产品</span>
								<span>{{ item.productCode }}({{ item.productName }})</span>
							</div>
							<div class="panel-row">
								<span>数量</span>
								<span>{{ item.inQty }}</span>
							</div>
							<div class="tag-icon" v-if="item.checked">
								<div>✓️️</div>
							</div>
						</div>
					</view>
					<view v-else>
						<view class="bg-image">
							<image src="@/static/empty.png" mode="heightFix" />
							<text>这里什么都没有...</text>
						</view>
					</view>
				</view>
				<view v-if="submitList?.length > 0" class="card-list-item"
					style="margin: 12px 0;display: grid;grid-template-columns: 1fr;grid-template-rows: 1fr;"
					@click="handleBtnLight">
					<view class="sign-btn">
						<text
							:style="['font-size: 14px;font-weight: bold;', isLightText?'color: rgba(0, 160, 233, 1)':'']">PDA签收</text>
						<view style="width: 0px;">
							<uni-easyinput ref="signInput" v-model="signText" @focus="handleInputFocus"
								:input-border="false" :clearable="false" type="text" @confirm="handleComplete" />
						</view>
					</view>
				</view>
				<view v-if="submitList?.length === 0" class="card-list-item"
					style="margin: 12px 0;display: grid;grid-template-columns: 1fr;grid-template-rows: 1fr;">
					<view class="sign-btn">
						<text style="font-size: 14px;font-weight: bold;color: gray;">PDA签收</text>
						<view style="width: 0px;">
							<uni-easyinput ref="signInput" @focus="handleInputFocus" :input-border="false"
								:clearable="false" type="text" />
						</view>
					</view>
				</view>
			</view>
			<uni-popup ref="selectModal" type="dialog">
				<uni-popup-dialog type="warn" cancel-text="取消" confirm-text="确认" title="手动分配货位" content="提示"
					@confirm="selectModal.close()" @close="selectModal.close()">
					<!-- eslint-disable-next-line -->
					<template #default="custom">
						<view class="select-group">
							<view class="select-item">
								<text class="store-text">仓库</text>
								<view class="custom-select">
									<uni-data-select v-model="stockCode" :localdata="warehouseList"
										@change="handleSelectWareHouse" />
								</view>
							</view>
							<view class="select-item">
								<text class="store-text">区域</text>
								<view class="custom-select">
									<uni-data-select v-model="areaCode" :localdata="regionList"
										@change="handleSelectRegion" />
								</view>
							</view>
							<view class="select-item">
								<text class="store-text">货位</text>
								<view class="custom-select">
									<uni-data-select v-model="locationCode" :localdata="locationList"
										@change="handleSelectLocation" />
								</view>
							</view>
						</view>
					</template>
				</uni-popup-dialog>
			</uni-popup>
			<uni-popup ref="errorTip" type="dialog">
				<uni-popup-dialog type="error" cancel-text="关闭" confirm-text="确认" title="提示" :content="errorTipMessage"
					@confirm="handleCloseErrorTipsModal" @close="handleCloseErrorTipsModal" />
			</uni-popup>
		</template>
	</gui-page>
</template>

<script>
	import {
		defineComponent,
		onMounted,
		reactive,
		ref,
		computed,
		toRefs,
		onBeforeMount
	} from 'vue'
	import {
		storeToRefs
	} from 'pinia';
	import {
		useSetWareHouseStore
	} from '@/stores/useSetWareHouseStore.js';
	export default defineComponent({
		setup() {
			const selectModal = ref('')
			const modalForm = ref('')
			const easyinput = ref()
			const errorState = ref(0)
			const errorTip = ref('')
			const errorTipMessage = ref('')
			const submitList = ref([])
			const scanNumber = ref('')
			const signInput = ref()
			const signText = ref('')
			// 员工号
			const employeeNum = ref('')
			const isLightText = ref('')
			const checkedList = ref([])
			// 货位
			const storeNum = ref('')
			const storeValues = reactive({
				stockCode: '',
				stockName: '',
				areaCode: '',
				areaName: '',
				locationCode: '',
				locationName: ''
			})
			const regionList = ref([])
			const warehouseList = ref([])
			const locationList = ref([])
			const store = useSetWareHouseStore();
			const computedStock = computed(() => {
				return item => warehouseList.value.find(opt => opt.id === item)?.text
			})
			const computedStore = computed(() => {
				return item => {
					return locationList.value.find(opt => opt.id === item)?.text
				}
			})
			const computedStoreArea = computed(() => {
				return item => regionList.value.find(opt => opt.id === item)?.text
			})

			onBeforeMount(() => {
				warehouseList.value = store.$state.warehouseList
			})

			// 仓库选择事件
			const handleSelectWareHouse = function(e) {
				const stock = warehouseList.value.find(item => item.value === e)
				storeValues.areaCode = ''
				storeValues.areaName = ''
				storeValues.stockName = stock?.text
				locationList.value = []
				store.handleGetRegionList(e).then(ret => {
					regionList.value = ret
				})
			}

			// 区域选择事件
			const handleSelectRegion = function(e) {
				const area = regionList.value.find(item => item.value === e)
				storeValues.locationCode = ''
				storeValues.locationName = ''
				storeValues.areaName = area?.text
				store.handleGetLocationList(e).then(ret => {
					locationList.value = ret
				})
			}

			// 货位选择事件
			const handleSelectLocation = function(e) {
				const location = locationList.value.find(item => item.value === e)
				storeValues.locationName = location?.text
			}

			// 输入员工工号签收
			const handleInputPerson = function() {
				const {
					stockCode,
					areaCode,
					locationCode
				} = storeValues
				uni.$reqPost('signIncomingProduceDetail', {
						detail: checkedList.value.length === 0 ? submitList.value : checkedList.value,
						encodedEmployeeId: employeeNum.value,
						stockCode,
						areaCode,
						locationCode
					})
					.then(({
						code,
						data,
						msg
					}) => {
						easyinput.value.onBlur()
						easyinput.value.onFocus()
						isLightText.value = false
						signText.value = ''
						if (code === 0) {
							if (data?.status * 1 === -1) {
								// #ifdef APP-PLUS
								plus.device.beep(2)
								// #endif
								errorTipMessage.value = "请先提交入库申请！"
								errorTip.value.open()
								errorState.value = 0
							} else {
								submitList.value.length = 0
								uni.showToast({
									title: '签收成功',
									icon: 'none',
									duration: 2000
								})
							}
						} else {
							// #ifdef APP-PLUS
							plus.device.beep(2)
							// #endif
							errorTipMessage.value = msg
							errorTip.value.open()
							errorState.value = -1
						}
					})
			}

			const handleInputStore = function() {
				console.log(storeNum.value);
				// uni.$reqGet('getStockLocaltionByCode', {
				// 		code: storeNum.value
				// 	})
				// 	.then(({
				// 		code,
				// 		data,
				// 		msg
				// 	}) => {
				// 		if (code === 0) {
				// 			console.log(data);
				// 			// submitParams.value.storeName = data?.name // 库位名称
				// 			// submitParams.value.erpStockId = data?.erpStockId // 入库仓库
				// 			// submitParams.value.wmsStoreAreaId = data
				// 			// 	?.wmsStoreAreaId // 入库区域
				// 			// submitParams.value.wmsStoreId = data?.wmsStoreId // 入库货位
				// 		} else {
				// 			uni.showToast({
				// 				title: msg,
				// 				icon: 'none',
				// 				duration: 2000
				// 			})
				// 		}
				// 	})
			}
			
			const handleScanStore = function() {
				return
				// #ifdef APP-PLUS
				const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_code === 1000) {
							uni.$reqGet('getStockLocaltionByCode', {
									code: ret.resp_result
								})
								.then(({
									code,
									data,
									msg
								}) => {
									if (code === 0) {
										console.log(data);
										// submitParams.value.storeName = data?.name // 库位名称
										// submitParams.value.erpStockId = data?.erpStockId // 入库仓库
										// submitParams.value.wmsStoreAreaId = data
										// 	?.wmsStoreAreaId // 入库区域
										// submitParams.value.wmsStoreId = data?.wmsStoreId // 入库货位
									} else {
										uni.showToast({
											title: msg,
											icon: 'none',
											duration: 2000
										})
									}
								})
						}
						// 返回值中，resp_code 表示返回结果值，10：用户取消，11：其他错误，1000：成功
						// 返回值中，resp_message 表示返回结果信息
						// 返回值中，resp_result 表示扫码结果，只有成功才会有返回
					})
				// #endif
			}


			// 扫描员工工号签收
			const handleScanPerson = function() {
				// #ifdef APP-PLUS
				const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_code === 1000) {
							const {
								stockCode,
								areaCode,
								locationCode
							} = storeValues
							uni.$reqPost('signIncomingProduceDetail', {
									detail: checkedList.value.length === 0 ? submitList.value :
										checkedList.value,
									encodedEmployeeId: ret.resp_result,
									stockCode,
									areaCode,
									locationCode
								})
								.then(({
									code,
									data,
									msg
								}) => {
									easyinput.value.onBlur()
									easyinput.value.onFocus()
									isLightText.value = false
									signText.value = ''
									if (code === 0) {
										if (data?.status * 1 === -1) {
											// #ifdef APP-PLUS
											plus.device.beep(2)
											// #endif
											errorTipMessage.value = "请先提交入库申请！"
											errorTip.value.open()
											errorState.value = 0
										} else {
											submitList.value.length = 0
											uni.showToast({
												title: '签收成功',
												icon: 'none',
												duration: 2000
											})
										}
									} else {
										// #ifdef APP-PLUS
										plus.device.beep(2)
										// #endif
										errorTipMessage.value = msg
										errorTip.value.open()
										errorState.value = -1
									}
								})
						}
					})
				// #endif
			}

			const handleMapass = function() {
				// #ifdef APP-PLUS
				const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_code === 1000) {
							uni.$reqGet('scanProductInDetailTemp', {
									id: ret.resp_result
								})
								.then(({
									code,
									data,
									msg
								}) => {
									if (code === 0) {
										if (data.status !== -1) {
											uni.$reqGet('getIncomingProduceDetailPage', {
													pageNo: 1,
													pageSize: 100,
													warehousingOrderNo: data.warehousingOrderNo
												})
												.then(({
													code,
													data,
													msg
												}) => {
													if (code === 0) {
														submitList.value = data?.list ?? []
														submitList.value.forEach(item => item
															.checked = false)
													} else {
														// #ifdef APP-PLUS
														plus.device.beep(2)
														// #endif
														errorTipMessage.value = msg
														errorTip.value.open()
														errorState.value = 0
													}
												})
										}
									} else {
										// #ifdef APP-PLUS
										plus.device.beep(2)
										// #endif
										errorTipMessage.value = msg
										errorTip.value.open()
										errorState.value = 0
									}
								})
						}
					})
				// #endif
			}

			// 扫描完成品标签输入框回车事件
			const handleKeydown = function(e) {
				uni.$reqGet('scanProductInDetailTemp', {
						id: e
					})
					.then(({
						code,
						data,
						msg
					}) => {
						scanNumber.value = ''
						easyinput.value.onBlur()
						easyinput.value.onFocus()
						if (code === 0) {
							if (data.status !== -1) {
								uni.$reqGet('getIncomingProduceDetailPage', {
										pageNo: 1,
										pageSize: 100,
										warehousingOrderNo: data.warehousingOrderNo
									})
									.then(({
										code,
										data,
										msg
									}) => {
										if (code === 0) {
											submitList.value = data?.list ?? []
											submitList.value.forEach(item => item.checked = false)
										} else {
											// #ifdef APP-PLUS
											plus.device.beep(2)
											// #endif
											errorTipMessage.value = msg
											errorTip.value.open()
											errorState.value = 0
										}
									})
							}
						} else {
							// #ifdef APP-PLUS
							plus.device.beep(2)
							// #endif
							errorTipMessage.value = msg
							errorTip.value.open()
							errorState.value = 0
						}
					})
			}

			const goBack = function() {
				uni.$goBack('/pages/workbranch/warehouse/warehousing/warehousingType')
			}

			// 设置高亮
			const handleBtnLight = function() {
				// #ifdef APP-PLUS
				signInput.value.onBlur()
				isLightText.value = true
				signInput.value.onFocus()
				// #endif
			}

			const handleComplete = function(e) {
				// #ifdef APP-PLUS
				// 扫描员工工号
				const {
					stockCode,
					areaCode,
					locationCode
				} = storeValues
				uni.$reqPost('signIncomingProduceDetail', {
						detail: checkedList.value.length === 0 ? submitList.value : checkedList.value,
						encodedEmployeeId: e,
						stockCode,
						areaCode,
						locationCode
					})
					.then(({
						code,
						data,
						msg
					}) => {
						easyinput.value.onBlur()
						easyinput.value.onFocus()
						isLightText.value = false
						signText.value = ''
						if (code === 0) {
							if (data?.status * 1 === -1) {
								// #ifdef APP-PLUS
								plus.device.beep(2)
								// #endif
								errorTipMessage.value = "请先提交入库申请！"
								errorTip.value.open()
								errorState.value = 0
							} else {
								submitList.value.length = 0
								uni.showToast({
									title: '签收成功',
									icon: 'none',
									duration: 2000
								})
							}
						} else {
							// #ifdef APP-PLUS
							plus.device.beep(2)
							// #endif
							errorTipMessage.value = msg
							errorTip.value.open()
							errorState.value = -1
						}
					})
				// #endif
			}

			const setInputFocus = function() {
				scanNumber.value = ''
				easyinput.value.onBlur()
				easyinput.value.onFocus()
			}

			// 关闭错误信息弹窗
			const handleCloseErrorTipsModal = async function() {
				errorTip.value.close()
				if (errorState.value === 0) {
					await setInputFocus()
				}
			}

			// 卡片面板选择事件
			const handleCheckedCard = function(ret) {
				const fdIndex = submitList.value.findIndex(item => item.id === ret.id);
				const findChecked = checkedList.value.findIndex(item => item.id === ret.id);
				if (fdIndex !== -1) submitList.value[fdIndex].checked = !submitList.value[fdIndex]
					.checked;

				if (findChecked === -1) {
					checkedList.value.push(ret);
				} else {
					checkedList.value.splice(findChecked, 1);
				}
			}

			// 禁用软键盘
			const handleInputFocus = function() {
				// // #ifdef APP-PLUS
				// setTimeout(() => {
				// 	uni.hideKeyboard()
				// }, 100)
				// // #endif
			}

			return {
				selectModal,
				goBack,
				errorTip,
				errorTipMessage,
				...toRefs(storeValues),
				handleSelectRegion,
				handleSelectWareHouse,
				handleSelectLocation,
				handleScanStore,
				handleInputStore,
				easyinput,
				modalForm,
				storeNum,
				employeeNum,
				scanNumber,
				signInput,
				signText,
				regionList,
				warehouseList,
				locationList,
				computedStock,
				computedStore,
				computedStoreArea,
				isLightText,
				handleMapass,
				handleKeydown,
				submitList,
				handleBtnLight,
				handleComplete,
				handleScanPerson,
				handleInputPerson,
				handleCheckedCard,
				handleInputFocus,
				handleCloseErrorTipsModal
			}
		}
	})
</script>

<style lang="scss" scoped>
	.gui-header-leader-btns {
		color: black;
		font-size: 24px !important;
	}

	.list-content {
		margin-top: 80px;
		background-color: #edeeee;
	}

	.input-200 {
		width: 200px;
		padding-left: 10px;
	}

	.font-icons {
		width: 40px;
		font-size: 20px;
		text-align: right;
	}

	.scan {
		height: 45px;
		width: calc(100% - 48px);
		margin: 12px;
		padding: 0 12px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-radius: 6px;
		background-color: white;

		.scan-card {
			width: 100%;
			display: grid;
			grid-template-rows: 1fr;
			grid-template-columns: 7fr 2fr;
			align-items: center;

			input {
				height: 35px;
				line-height: 35px;
			}

			text {
				width: 100%;
				text-align: right;
			}
		}
	}

	.card-list-item {
		width: 750rpx;
		height: 40px;
		margin: 2rpx 0;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;

		uni-text {
			font-size: 14px;
			height: 50rpx;
			text-align: left;
			padding: 0 12px;
			display: flex;
			flex-direction: row;
			align-items: center;
		}

		.text-1 {
			flex: 1;
			height: 40px;
			justify-content: flex-start;
		}

		.text-2 {
			flex: 3;
			height: 40px;
			justify-content: flex-end;
			margin-right: 4px;
			padding: 2px 6px;
		}
	}

	.table-title {
		height: 40px;
		line-height: 40px;
		margin: 0 0 -3px 0;
		padding: 0 12px;
		font-size: 16px;
		font-weight: bold;
		background-color: white;
	}

	.custom-table {
		height: calc(100vh - (8vh + 365px));
		min-height: 230px;
		margin: 5px 0;
		overflow-y: scroll;
	}

	.sign-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 8px;
		border: 1px solid #999999;
		background-color: white;
		border-radius: 6px;
	}

	span,
	text {
		font-size: 12px;
	}

	.tag-icon {
		position: absolute;
		top: 0;
		right: 0;
		width: 32px;
		height: 32px;
		display: flex;
		justify-content: end;
		align-items: flex-start;
		background-color: #00a0e9;
		clip-path: polygon(0 0, 100% 0%, 100% 100%);
	}

	.tag-icon div {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 16px;
		font-weight: bold;
		font-size: 16px;
		color: white;
	}

	.store-list {
		min-height: 60px;
		height: 8vh;
		margin-bottom: 2px;
		display: flex;
		justify-content: space-around;
		flex-direction: column;
		padding: 0 8px;
		font-size: 12px;
		background-color: white;
	}
</style>