<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="easyinputStore" v-model="storeName" :input-border="false"
							:clearable="false" type="text" placeholder="请扫描库位信息"
							@confirm="confirmStore" />
						<text class="font-icons" @click="handleScanStore">&#xe6b7;</text>
					</view>
				</view>

				<!-- 物料扫描输入框 -->
				<view class="scan">
					<view class="scan-card">
						<uni-easyinput ref="easyinput" v-model="scanBatchNumber" :input-border="false"
							:clearable="false" type="text" placeholder="请扫描物料二维码"
							@confirm="handleKeydown" />
						<text class="font-icons" @click="handleScanMaterial">
							&#xe6b7;
						</text>
					</view>
				</view>
			
				<!-- 是否按货位盘点单选按钮 -->
				<view class="check-by-location-radio">
					<text class="radio-label">是否按货位盘点：</text>
					<radio-group @change="handleCheckByLocationChange" class="radio-group">
						<label class="radio-item">
							<radio value="1" :checked="checkByLocationFlag === '1'" color="#00a0e9" />
							<text>是</text>
						</label>
						<label class="radio-item">
							<radio value="0" :checked="checkByLocationFlag === '0'" color="#00a0e9" />
							<text>否</text>
						</label>
					</radio-group>
				</view>
			
				<!-- 仓库和货位信息展示 -->
				<view class="info-row">
					<text class="info-label">仓库:</text>
					<text class="info-value">{{ erpStockName }}</text>
					<text class="info-label">货位:</text>
					<text class="info-value">{{ wmsStoreName }}</text>
				</view>
		
				<!-- 自定义表格：表头固定 + 支持横向滑动 -->
				<view class="custom-table-wrapper">
					<!-- 表头区域（固定纵向，跟随横向滚动） -->
					<scroll-view 
						class="table-header-scroll" 
						scroll-x 
						:scroll-left="tableScrollLeft" 
						@scroll="handleHeaderScroll"
					>
						<view class="table-row header-row">
							<view class="table-cell" style="width: 120px;">备注</view>
							<view class="table-cell" style="width: 100px;">物料编码</view>
							<view class="table-cell" style="width: 100px;">物料名称</view>
							<view class="table-cell" style="width: 100px;">仓库</view>
							<view class="table-cell" style="width: 100px;">库位</view>
							<view class="table-cell" style="width: 120px;">条码号</view>
							<view class="table-cell" style="width: 80px;">数量</view>
							<view class="table-cell" style="width: 80px;">操作</view>
						</view>
					</scroll-view>
					
					<!-- 内容区域（纵向滚动 + 横向滚动） -->
					<scroll-view 
						class="table-body-scroll" 
						scroll-y 
						scroll-x 
						:scroll-left="tableScrollLeft"
						@scroll="handleBodyScroll"
					>
						<view 
							class="table-row body-row" 
							v-for="(item, key) in beforeTableData" 
							:key="key"
						>
							<view class="table-cell" style="width: 120px;">
								<uni-easyinput 
									v-model="item.note" 
									:input-border="false"
									placeholder="请输入"
									@blur="handleNoteBlur(item)"
								/>
							</view>
							<view class="table-cell" style="width: 100px;">{{ item.materialNo }}</view>
							<view class="table-cell" style="width: 100px;">{{ item.materialName }}</view>
							<view class="table-cell" style="width: 100px;">{{ item.wmsStockCode }}</view>
							<view class="table-cell" style="width: 100px;">{{ item.wmsStoreCode }}</view>
							<view class="table-cell" style="width: 120px;">{{ item.batchNumber }}</view>
							<view class="table-cell" style="width: 80px;">{{ item.batchQty }}</view>
							<view class="table-cell" style="width: 80px;">
								<text class="delete-btn" @click="deleteTableItem(key)">删除</text>
							</view>
						</view>
						<!-- 空数据提示 -->
						<view v-if="beforeTableData.length === 0" class="empty-text">暂无更多数据</view>
					</scroll-view>
				</view>

				<view class="btn-area">
					<view class="finish-btn" :class="{ disabled: finishDisabled }" @click="handleFinish">
						<text class="btn-text">结束盘点</text>
					</view>
				</view>

				<uni-popup ref="errorTip" type="dialog">
					<uni-popup-dialog type="error" cancel-text="关闭" confirm-text="确认" title="提示"
						:content="errorTipMessage" @confirm="handleCloseErrorTipsModal"
						@close="handleCloseErrorTipsModal" />
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script>
import {
	onShow
} from '@dcloudio/uni-app'
import {
	ref,
	defineComponent,
	onBeforeMount,
	nextTick
} from 'vue'

export default defineComponent({
	setup(options) {
		const errorTip = ref('')
		const errorTipMessage = ref('')
		const easyinput = ref('')
		const easyinputStore = ref('')
		const errorState = ref(0)
		const parentRow = uni.getStorageSync('masterId') ?? {}
		const masterId = ref('')
		const scanBatchNumber = ref('')
		const tableData = ref([])
		const beforeTableData = ref([])
		const currentScanMaterial = ref([])
		const localScannedList = ref([])
		const finishDisabled = ref(false)
		const receiveList = ref([])
    
		const storeName = ref('')
		const erpStockName = ref('')
		const wmsStoreName = ref('')
		const countStockCode = ref('')      // 盘点仓库编码
		const countStoreAreaCode = ref('')  // 盘点区域编码
		const countStoreCode = ref('')      // 盘点货位编码

		/* -------------------- 是否按货位盘点字段 -------------------- */
		const checkByLocationFlag = ref(null)

		/* -------------------- 表格横向滚动同步 -------------------- */
		const tableScrollLeft = ref(0)

		const initMasterId = () => {
			const parsedData = JSON.parse(parentRow)
			masterId.value = parsedData?.id
		}
	
		onBeforeMount(() => {
			initMasterId()
			if (masterId.value) {
			        search()
			}
		})
	
		onShow(() => {
			initMasterId()
			// if (masterId.value) {
			// 	search()
			// }
		})

		const search = function() {
		    uni.$reqGet('inventoryGetStockCountSubdetailList', { id: masterId.value })
		        .then(({ code, data, msg }) => {
		            if (code === 0) {
		                receiveList.value = data || []
		                tableData.value = data || []
		                // 清空本地扫描列表并重新构建
		                localScannedList.value = []
		                tableData.value.forEach(item => {
		                    // 后端返回的字段是 batchQty，但可能为 null，需要处理
		                    localScannedList.value.push({
		                        ...item,
		                        batchQty: item.batchQty || 1,  // 如果为 null 默认给 1
		                        note: item.note || ''
		                    })
		                })
		                
		                flushBeforeTableData()
		            } else {
		                uni.showToast({ title: msg, icon: 'none', duration: 2000 })
		            }
		        })
		}

		const goBack = function() {
			if (uni.getStorageSync('masterId')) {
				uni.removeStorageSync('masterId')
			}
			if (uni.getStorageSync('ids')) {
				uni.removeStorageSync('ids')
			}
			uni.$goBack('/pages/workbranch/warehouse/Inventory/inventoryPage')
		}

		const isProcessing = ref(false)
		
		const handleScanMaterial = async function () {
		    if (isProcessing.value) {
		            uni.showToast({ title: '处理中，请稍候...', icon: 'none', duration: 1500 })
		            return
		        } 
		    if (!storeName.value) {
		        errorTipMessage.value = '请先扫描库位信息'
		        errorTip.value.open()
		        return
		    }
		
		    const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
		    const ret = await new Promise(resolve =>
		        mpaasScanModule.mpaasScan(
		            { scanType: ['qrCode', 'barCode'], hideAlbum: false },
		            resolve
		        )
		    )
		    if (ret.resp_code !== 1000) return
		
		    const qrCode = ret.resp_result
		    isProcessing.value = true  
		
		    try {
		        // 1. 查询物料信息
		        const { code, data, msg } = await uni.$reqPost('inventoryGetQrCode', {
		            countStoreCode: countStoreCode.value || storeName.value,
		            countStoreAreaCode: countStoreAreaCode.value,
		            countStockCode: countStockCode.value,
		            batchNumber: qrCode,
		            erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value,
		        })
		
		        if (code !== 0) {
		            throw new Error(msg || '查询物料失败')
		        }
		
		        scanBatchNumber.value = qrCode
		
		        // 2. 组装保存参数
		        const scanData = {
		            ...data,
		            countStoreCode: countStoreCode.value || storeName.value,
		            countStoreAreaCode: countStoreAreaCode.value,
		            countStockCode: countStockCode.value,
		        }
		        const saveParams = {
		            ...scanData,
		            erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value
		        }
		
		        // 3. 保存数据
		        const { code: saveCode, data: saveData, msg: saveMsg } = await uni.$reqPost('inventorySaveQrCode', saveParams)
		        
		        if (saveCode !== 0) {
		            throw new Error(saveMsg || '保存失败')
		        }
		
		        // 4. 本地更新数据（✅ 去掉 search()，减少一次请求）
		        localScannedList.value.push({
		            ...scanData,
		            batchQty: scanData.receiptQty || 1,
		            note: '',
		            id: saveData?.id || scanData.id
		        })
		        flushBeforeTableData()
				search()
		        uni.showToast({
		            title: '保存成功',
		            icon: 'success',
		            duration: 1500
		        })
		
		        scanBatchNumber.value = ''
		        setInputFocus()
		        
		    } catch (err) {
		        errorTipMessage.value = err.message || '操作失败'
		        errorTip.value.open()
		        errorState.value = 0
		    } finally {
		        isProcessing.value = false  // ✅ 释放锁
		    }
		}

		const handleKeydown = async function(e) {
		    if (isProcessing.value) {
				uni.showToast({ title: '处理中，请稍候...', icon: 'none', duration: 1500 })
				return
			}
			 
		    if (!storeName.value) {
		        errorTipMessage.value = '请先扫描库位信息'
		        errorTip.value.open()
		        errorState.value = 0
		        return
		    }
		
		    isProcessing.value = true
		
		    try {
		        const { code, data, msg } = await uni.$reqPost('inventoryGetQrCode', {
		            countStoreCode: countStoreCode.value || storeName.value,
		            countStoreAreaCode: countStoreAreaCode.value,
		            countStockCode: countStockCode.value,
		            batchNumber: e,
		            erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value,
		        })
		
		        if (code !== 0) {
		            throw new Error(msg || '查询物料失败')
		        }
		
		        scanBatchNumber.value = e
		
		        const scanData = {
		            ...data,
		            countStoreCode: countStoreCode.value || storeName.value,
		            countStoreAreaCode: countStoreAreaCode.value,
		            countStockCode: countStockCode.value,
		        }
		        const saveParams = {
		            ...scanData,
		            erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value
		        }
		
		        const { code: saveCode, data: saveData, msg: saveMsg } = await uni.$reqPost('inventorySaveQrCode', saveParams)
		        
		        if (saveCode !== 0) {
		            throw new Error(saveMsg || '保存失败')
		        }
		
		        localScannedList.value.push({
		            ...scanData,
		            batchQty: scanData.receiptQty || 1,
		            note: '',
		            id: saveData?.id || scanData.id
		        })
		        flushBeforeTableData()
				search()
		        uni.showToast({
		            title: '保存成功',
		            icon: 'success',
		            duration: 1500
		        })
		
		        scanBatchNumber.value = ''
		        setInputFocus()
		        
		    } catch (err) {
		        errorTipMessage.value = err.message || '操作失败'
		        errorTip.value.open()
		        errorState.value = 0
		    } finally {
		        isProcessing.value = false  // ✅ 释放锁
		    }
		}

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

		const flushBeforeTableData = function() {
			const map = new Map()
			localScannedList.value.forEach(it => {
				const key = `${it.materialNo}__${it.batchNumber}`
				if (map.has(key)) {
					map.get(key).batchQty += it.batchQty
					if (it.note) {
						map.get(key).note = it.note
					}
				} else {
					map.set(key, { ...it })
				}
			})
			beforeTableData.value = Array.from(map.values()).map((v, i) => ({
				...v,
				uniqueId: `${v.materialNo}_${v.batchNumber}_${i}`,
				slideX: 0
			}))
		}

		// 删除 - 调用 inventoryDelete 接口
		const deleteTableItem = async (idx) => {
			const target = beforeTableData.value[idx]
			
			uni.showModal({
				title: '提示',
				content: '确认删除该物料？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const { code, msg } = await uni.$reqPost('inventoryDelete', { 
								id: target.id,
								erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value
							})
							if (code !== 0) {
								errorTipMessage.value = msg || '删除失败'
								errorTip.value.open()
								return
							}
							
							// 删除成功，更新本地数据
							const key = `${target.materialNo}__${target.batchNumber}`
							const listIdx = localScannedList.value.findIndex(
								v => `${v.materialNo}__${v.batchNumber}` === key
							)
							if (listIdx > -1) localScannedList.value.splice(listIdx, 1)

							flushBeforeTableData()

							const row = tableData.value.find(r => r.materialNo === target.materialNo)
							if (row) row.completedQty -= target.batchQty
							search()
						} catch (err) {
							errorTipMessage.value = err.errMsg || '网络异常，删除失败'
							errorTip.value.open()
						}
					}
				}
			})
		}

		// 备注修改 - 调用 inventoryUpdateQrCode 接口
		const handleNoteBlur = async (item) => {
			// 先同步到本地缓存
			const key = `${item.materialNo}__${item.batchNumber}`
			localScannedList.value.forEach(it => {
				if (`${it.materialNo}__${it.batchNumber}` === key) {
					it.note = item.note
				}
			})
			
			// 调用接口更新备注
			if (item.id) {
				try {
					await uni.$reqPost('inventoryUpdateQrCode', {
						id: item.id,
						note: item.note,
						erpStockCountId: receiveList.value?.[0]?.erpStockCountId || masterId.value
					})
					search()
				} catch (err) {
					console.error('备注更新失败', err)
				}
			}
		}

		const handleCloseErrorTipsModal = async function() {
			errorTip.value.close()
			if (errorState.value === 0) {
				await setInputFocus()
			}
		}

		const handleScanStore = function() {
			const mpaasScanModule = uni.requireNativePlugin('Mpaas-Scan-Module')
			mpaasScanModule.mpaasScan({
				'scanType': ['qrCode', 'barCode'],
				'hideAlbum': false
			}, (ret) => {
				if (ret.resp_code === 1000) {
					confirmStore(ret.resp_result)
				}
			})
		}

		const confirmStore = function(e) {
			storeName.value = e
			uni.$reqGet('getStockLocaltionByCode', { code: e })
			.then(({ code, data, msg }) => {
				if (code === 0) {
					if (!data || !data.erpStockName || !data.wmsStoreName) {
						errorTipMessage.value = '请扫描正确的库位'
						errorTip.value.open()
						errorState.value = 0
						storeName.value = ''
						return
					}
					erpStockName.value = data.erpStockName
					wmsStoreName.value = data.wmsStoreName
					// 保存盘点编码
					countStockCode.value = data.stockCode || ''        // 盘点仓库编码 = 仓库编码
					countStoreCode.value = data.locationCode || e       // 盘点货位编码 = 货位编码
					countStoreAreaCode.value = data.stockCode || ''   // 盘点区域编码 = 仓库编码（同仓库）
					nextTick(() => {
						easyinput.value.onFocus()
					})
				} else {
					errorTipMessage.value = '请扫描正确的库位'
					errorTip.value.open()
					errorState.value = 0
					storeName.value = ''
				}
			})
		}

		const mergeBeforeIntoTable = () => {
			const mergedTableData = JSON.parse(JSON.stringify(tableData.value))
			const map = {}
			mergedTableData.forEach(row => {
				if (!row.inRequestSubdetailList) row.inRequestSubdetailList = []
				map[row.materialNo] = row
			})

			beforeTableData.value.forEach(item => {
				const target = map[item.materialNo]
				if (target) {
					target.inRequestSubdetailList.push({ ...item, leftQty: null })
				}
			})
			return mergedTableData
		}

		// 结束盘点 - 调用 inventoryFinishStockCount 接口
		const handleFinish = async function() {
		    if (finishDisabled.value) return
		    
		    if (checkByLocationFlag.value === null) {
		        uni.showToast({
		            title: '请选择是否按货位盘点',
		            icon: 'none',
		            duration: 2000
		        })
		        return
		    }
		    
		    finishDisabled.value = true
		    try {
		        await uni.$reqPost('inventoryFinishStockCount', {
		            id: receiveList.value?.[0]?.erpStockCountId || masterId.value,
		            storeFlag: checkByLocationFlag.value
		        })
		        .then(({ code, data, msg }) => {
		            if (code === 0) {
		                uni.showModal({
		                    title: '提示',
		                    content: '盘点结束',
		                    showCancel: false,
		                   	success: () => {
		                        goBack()
		                    }
		                })
		            } else {
		                errorTipMessage.value = msg
		                errorTip.value.open()
		                errorState.value = 0
		            }
		        })
		    } finally {
		        finishDisabled.value = false
		    }
		}

		// 同步表头和内容的横向滚动
		const handleHeaderScroll = function(e) {
			tableScrollLeft.value = e.detail.scrollLeft
		}

		const handleBodyScroll = function(e) {
			tableScrollLeft.value = e.detail.scrollLeft
		}

		// 处理是否按货位盘点单选按钮变化
		const handleCheckByLocationChange = function(e) {
			checkByLocationFlag.value = e.detail.value
		}

		return {
			goBack,
			beforeTableData,
			easyinput,
			easyinputStore,
			errorTip,
			errorTipMessage,
			handleKeydown,
			scanBatchNumber,
			handleScanMaterial,
			handleCloseErrorTipsModal,
			handleFinish,
			finishDisabled,
			storeName,
			erpStockName,
			wmsStoreName,
			handleScanStore,
			confirmStore,
			deleteTableItem,
			handleNoteBlur,
			checkByLocationFlag,
			handleCheckByLocationChange,
			tableScrollLeft,
			handleHeaderScroll,
			handleBodyScroll
		}
	}
})
</script>

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

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

	.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;
			}
		}
	}

	/* ========== 自定义表格样式（支持横向+纵向滚动）========== */
	.custom-table-wrapper {
		height: calc(100vh - 280px);
		min-height: 230px;
		margin: 5px 0;
		display: flex;
		flex-direction: column;
		border: 1px solid #e0e0e0;
		border-radius: 4px;
		overflow: hidden;
	}

	/* 表头横向滚动容器 */
	.custom-table-wrapper {
		height: calc(100vh - 280px);
		min-height: 230px;
		margin: 5px 0;
		display: flex;
		flex-direction: column;
		border: 1px solid #e0e0e0;
		border-radius: 4px;
		overflow: hidden;
	}

	/* 内容区域：纵向+横向滚动 */
	.table-body-scroll {
		height: calc(100% - 40px); /* 明确内容区域高度 */
		scrollbar-width: none;
		-ms-overflow-style: none;
		&::-webkit-scrollbar {
			display: none;
		}
	}

	.table-row {
		display: flex;
		align-items: center;
		min-height: 40px;
		/* 确保行宽超出容器，触发横向滚动 */
		width: max-content;
	}

	.header-row {
		font-weight: bold;
		color: #333;
		background-color: #f5f7fa;
	}

	.body-row {
		border-bottom: 1px solid #f0f0f0;
		&:nth-child(even) {
			background-color: #f5f7fa;
		}
		&:nth-child(odd) {
			background-color: #ffffff;
		}
	}

	.table-cell {
		padding: 8px 4px;
		text-align: center;
		box-sizing: border-box;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		word-break: break-all;
	}

	.empty-text {
		text-align: center;
		padding: 20px;
		color: #999;
		font-size: 14px;
		width: 100vw; /* 确保空提示有宽度 */
	}

	/* ========== 其他样式 ========== */

	.info-row {
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background-color: #f0f2f5;
		border-radius: 8rpx;
		margin: 10rpx 20rpx;
	}

	.info-label {
		color: #666;
		font-size: 28rpx;
		margin-right: 8rpx;
	}

	.info-value {
		color: #333;
		font-size: 28rpx;
		margin-right: 20rpx;
		font-weight: 500;
	}

	.delete-btn {
		color: #e54d42;
		font-size: 12px;
		padding: 2px 4px;
	}

	.btn-area {
		margin: 12px 24rpx;
	}

	.finish-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 44px;
		background-color: #00a0e9;
		border-radius: 6px;
	}

	.finish-btn.disabled {
		opacity: 0.5;
		pointer-events: none;
	}

	.btn-text {
		color: #fff;
		font-size: 16px;
		font-weight: bold;
	}

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

	/* 是否按货位盘点单选按钮样式 */
	.check-by-location-radio {
		display: flex;
		align-items: center;
		padding: 10rpx 24rpx;
		background-color: #fff;
		margin: 0 24rpx 10rpx 24rpx;
		border-radius: 6px;
		
		.radio-label {
			font-size: 28rpx;
			color: #333;
			margin-right: 20rpx;
			white-space: nowrap;
		}
		
		.radio-group {
			display: flex;
			flex-direction: row;
		}
		
		.radio-item {
			display: flex;
			align-items: center;
			margin-right: 30rpx;
			
			radio {
				transform: scale(0.8);
			}
			
			text {
				font-size: 28rpx;
				color: #333;
				margin-left: 8rpx;
			}
		}
	}
</style>