<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 style="font-size:44rpx;" class="gui-header-leader-btns gui-color-white font-icons"
					@tap="goHome">&#xe6c5;</text>
				<!-- 导航文本此处也可以是其他自定义内容 -->
				<text class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text"
					style="font-size: 1rem;">扫码入库列表</text>
				<!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
				<!-- 实际宽度请根据自己情况设置 -->
				<view style="width:40px;" />
				<!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
			</view>
		</template>
		<template #gBody>
			<view class="list-content">
				<!-- 搜索栏 -->
				<view class="search-bar">
					<view class="search-item">
						<text class="search-label">业务类型</text>
						<view class="search-select">
							<picker @change="onBusinessTypeChange" :range="businessTypeList" range-key="text" :value="businessTypeIndex">
								<view class="picker-text">{{ businessTypeList[businessTypeIndex]?.text || '请选择业务类型' }}</view>
							</picker>
						</view>
					</view>
					<view class="search-item">
						<text class="search-label">申请单号</text>
						<view class="search-input-wrapper">
							<!-- <input type="text" v-model="requestNo" placeholder="请输入申请单号" class="search-input" focus /> -->
							<input type="text" v-model="requestNo" placeholder="请输入申请单号" class="search-input" />
							<text class="scan-icon font-icons" @tap="scanCode">
								&#xe6b7;
							</text>
						</view>
					</view>
					<view class="search-btn" @tap="handleSearch">
						<text class="font-icons">搜索&#xe60c;</text>
					</view>
				</view>
				<view style="margin-top: 110px;">
					<view v-if="cardList?.length > 0" class="list-panel">
						<div v-for="(item, key) in cardList" :key="key" class="panel"
							@click="handleToScanMaterials(item)">
								<div class="panel-row">
									<span>{{ item.requestNo }}</span>
									<span class="font-icons">前往扫描&#xe66b;</span>
								</div>
								<div class="panel-row">
									<span>业务类型</span>
									<span>{{ computedState(item.businessType,'businessType') }}</span>
								</div>
								<div class="panel-row">
									<span>业务状态</span>
									<span>{{ computedState(item.status,'status') }}</span>
								</div>
						</div>
					</view>
					<view v-else>
						<view class="bg-image">
							<image src="@/static/empty.png" mode="heightFix" />
							<text>这里什么都没有...</text>
						</view>
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script>
	import {
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		ref,
		defineComponent,
		computed,
		onMounted
	} from 'vue'
	export default defineComponent({
		setup() {
			const queryParams = ref({
		pageSize: 10,
		pageNo: 1,
		keyWord: '',
		businessType: ''
	})
	const cardList = ref([])
	const businessTypeList = ref([])
	const statusMap = ref({})
	const businessTypeIndex = ref(0)
	const selectedBusinessType = ref('')
	const requestNo = ref('')

			const search = function(pageNo) {
				uni.$reqGet('getScanInList', {
					...queryParams.value,
					businessType: selectedBusinessType.value,
					requestNo: requestNo.value,
					pageNo
				})
				.then(({
					data,
					msg
				}) => {
					cardList.value = data?.list ?? []
					// 如果是通过申请单号搜索且有结果，直接跳转到scannedMaterials页面
					if (requestNo.value && cardList.value.length === 1) {
						handleToScanMaterials(cardList.value[0])
					}
				})
			}

			onMounted(() => {
		search(1)
		// 获取业务类型字典数据
		uni.$reqGet('getDictDataPage', {
			dictType: 'in_business_type',
			pageNo: 1,
			pageSize: 100
		}).then(({ data }) => {
			businessTypeList.value = [{ text: '请选择业务类型', value: '' }]
			const dataList = data?.list || [];
			for (var i = 0; i < dataList.length; i++) {
				businessTypeList.value.push({
					text: dataList[i].label,
					value: dataList[i].value,
				})
			}
		})
		uni.$reqGet('getDictDataPage', {
  dictType: 'in_out_status',// 后端给的字典编码
  pageNo: 1,
  pageSize: 100
}).then(({ data }) => {
  data?.list.forEach(item => {
    statusMap.value[item.value] = item.label// 例如 0→待出库  1→已出库
  })
})
	})
	const goHome = function() {
      uni.$goHome()
    }
			const goBack = function() {
				uni.removeStorageSync('masterId')
				// 返回到扫码类型选择页面
				uni.$goBack('/pages/workbranch/warehouse/scanInOut/scanInOutType')
			}

			const handleToScanMaterials = function(params) {
			    // 存储数据，使用abc页面需要的键名
			    uni.setStorageSync('masterId', JSON.stringify({
			        id: params?.id,
			        businessType: params?.businessType
			    }))
			    
			    // 根据 businessType 判断跳转页面：3=退料，其他=普通入库
			    const isReturnMaterial = String(params?.businessType).trim() == '3'
			    const targetUrl = isReturnMaterial
			        ? '/pages/workbranch/warehouse/scanInOut/In/businessType3/returnMaterial'
			        : '/pages/workbranch/warehouse/scanInOut/In/scannedMaterials'
			    
			    // 跳转到对应页面
			    uni.navigateTo({
			        url: targetUrl
			    })
			}
			
			// 同步搜索条件到queryParams
		const syncQueryParams = () => {
			queryParams.value.businessType = selectedBusinessType.value;
			queryParams.value.requestNo = requestNo.value;
		};

		// 业务类型选择变化
		const onBusinessTypeChange = function(e) {
			businessTypeIndex.value = e.detail.value
			selectedBusinessType.value = businessTypeList.value[e.detail.value]?.value || ''
		}
		
		// 搜索
		const handleSearch = function() {
			queryParams.value.pageNo = 1
			syncQueryParams(); // 保证条件写进去
			search(1)
		}
		
		// 扫码获取申请单号
		const scanCode = function() {
			uni.scanCode({
				success: function(res) {
					// 将扫码结果填入申请单号输入框
					requestNo.value = res.result
					// 自动执行搜索
					handleSearch()
				},
				fail: function(err) {
					console.log('扫码失败', err)
					uni.showToast({
						title: '扫码失败',
						icon: 'none'
					})
				}
			})
		}

		// uniapp移动端触底事件
	onReachBottom(() => {
		queryParams.value.pageNo += 1
		syncQueryParams(); // 关键：把条件重新合并
		uni.$reqGet('getScanInList', queryParams.value)
			.then(({data,msg}) => {
				Array.prototype.push.call(cardList.value, ...data?.list ?? [])
			})
	})

		// 计算业务类型的中文标签
		const computedState = function (value, type = 'businessType') {
		  if (value === '' || value == null) return '未知'
		  // 业务类型
		  if (type === 'businessType') {
		    const hit = businessTypeList.value.find(i => String(i.value).trim() === String(value).trim())
		    return hit ? hit.text : '未知'
		  }
		  // 单据状态
		  if (type === 'status') {
		    return statusMap.value[value] || '未知'
		  }
		  return '未知'
		}

		return {
						goHome,
						goBack,
						cardList,
						handleToScanMaterials,
						businessTypeList,
						computedState,
						businessTypeIndex,
						onBusinessTypeChange,
						handleSearch,
						requestNo,
						scanCode
					}
		}
	})
</script>

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

	.list-content {
		margin-top: 50px;
		min-height: calc(100vh - 80px);
		background-color: #edeeee;
	}
	
	.search-bar {
		position: fixed;
		top: 72px;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding: 12px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
		z-index: 9;
		box-sizing: border-box;
	}
	
	.search-item {
	    flex: 1 1 200px;        // 原来只有 flex:1
	    min-width: 200px;
	    display: flex;
	    align-items: center;
	    gap: 8px;
	    margin-bottom: 8px;
	}
	
	.search-input-wrapper {
		flex: 1;
	}
	
	.search-input {
					width: 90%;
					height: 36px;
					line-height: 36px;
					background-color: #f5f5f5;
					border-radius: 4px;
					padding: 0 12px;
					font-size: 12px;
					border: none;
				}
				
				.search-input-wrapper {
					flex: 1;
					position: relative;
				}
				
				.scan-icon {
					position: absolute;
					right: 10px;
					top: 50%;
					transform: translateY(-50%);
					font-size: 20px;
					color: #00a0e9;
					cursor: pointer;
				}
	
	.search-input:focus {
		outline: none;
		background-color: #fff;
		border: 1px solid #00a0e9;
	}
	
	.search-label {
		font-size: 12px;
		color: #666;
	}
	
	.search-select {
		flex: 1;
		position: relative;
	}
	
	.search-select picker {
	    display: flex;          // 关键：让内部文本撑开
	    align-items: center;
	    height: 36px;
	    line-height: 36px;
	    min-width: 120px;       // 防止被 flex 挤没
	    background-color: #f5f5f5;
	    border-radius: 4px;
	    padding: 0 28px 0 12px; // 右侧留图标位置
	}
	
	.picker-text {
		font-size: 12px;
		color: #333;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.picker-text::after {
	    position: absolute;
	    right: 8px;
	    top: 50%;
	    transform: translateY(-50%);
	}
	
	.search-btn {
		width: 80px;
		height: 36px;
		line-height: 36px;
		background-color: #00a0e9;
		color: #fff;
		border-radius: 4px;
		text-align: center;
		font-size: 12px;
	}
	
	.search-btn .font-icons {
		color: #fff;
		margin-right: 4px;
	}

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

	.list-panel {
		padding: 12px;
	}

	.panel {
		background-color: white;
		border-radius: 8px;
		padding: 12px;
		margin-bottom: 12px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.panel-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8px;

		&:last-child {
			margin-bottom: 0;
		}

		span:first-child {
			color: #666;
		}

		span:last-child {
			font-weight: bold;
		}

		.font-icons {
			color: #00a0e9;
			display: flex;
			align-items: center;
		}
	}

	.bg-image {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 0;

		image {
			width: 120px;
			height: 120px;
			margin-bottom: 16px;
		}

		text {
			color: #999;
			font-size: 14px;
		}
	}
</style>