<template>
	<uni-navbar-lite :showRight=false title="物料申请"></uni-navbar-lite>
	<view class="page-container">
		<scroll-view class="page-content">
		<view class="section">
			<view class="search-bar">
			    <view class="search-box">
			        <image class="search-icon" src="/static/images/workbench/list/1.png" mode="aspectFit"></image>
			        <input class="search-input" type="text" placeholder="请输入关键字查询" v-model="keyword" @confirm="handleSearch" confirm-type="search" />
			        <view v-if="keyword.length > 0" class="clear-btn" @tap="clearKeyword">
			        	<text class="clear-btn-text">×</text>
			        </view>
			        <view class="search-btn" @tap="handleSearch">
			        	<text class="search-btn-text">搜索</text>
			        </view>
			    </view>
			</view>
			
			<view class="status-tabs">
				<scroll-view class="scroll-view_H" direction="horizontal" :show-scrollbar="false">
					<view 
						v-for="(cat, idx) in categories" 
						:key="idx" 
						class="status-tab" 
						:class="{ 'active': currentStatus === cat.id }" 
						@click="switchStatus(cat.id)"
					>
						<text class="status-tab-text" :class="{ 'active-text': currentStatus === cat.id }">{{ cat.name }}</text>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="section">
				<view class="section-header">
				    <view class="section-indicator"></view>
				    <text class="section-title">物料列表</text>
				</view>
				<view class="material-list">
					<view 
						v-for="(item, index) in dataList" 
						:key="item.itemId + '_' + page" 
						class="list-item"
						@click="handleItemClick(item, index)"
					>
						<view class="item-header">
						    <view class="item-info">
								<view class="item-name-row">
									<text class="item-name">{{ getItemName(item) }}</text>
									<text class="item-measure">{{ getMeasureName(item) }}</text>
								</view>
								<text class="item-sub-title">{{ getItemTypeName(item) }}</text>
						    </view>
						    <view v-if="item.isSelected" class="added-btn">
						        <text class="added-icon">已选</text>
						    </view>
						    <view v-else class="add-btn" @click.stop="addToSelected(item)">
						        <text class="add-icon">+</text>
						    </view>
						</view>
					</view>
				</view>
				<!-- 手动分页 -->
				<view class="pagination">
					<view class="page-btn" :class="{disabled: page <= 1}" @click="prevPage">
						<text class="page-btn-text"><</text>
					</view>
					<text class="page-info">第{{ page }}页 / 共{{ totalPages }}页</text>
					<view class="page-btn" :class="{disabled: page >= totalPages}" @click="nextPage">
						<text class="page-btn-text">></text>
					</view>
				</view>
			</view>
			<view class="section">
				<view class="section-header">
				    <view class="section-indicator"></view>
				    <text class="section-title">已选列表</text>
				</view>
				<view class="selected-list">
					<view v-if="selectedItems.length === 0" class="empty-tip">
						<text class="empty-tip-text">请选择物料</text>
					</view>
					<view 
						v-else
						v-for="(selItem, selIndex) in selectedItems" 
						:key="selIndex" 
						class="selected-item"
					>
						<text class="selected-item-name">{{ selItem.itemName }}</text>
						<text class="selected-item-measure">{{ selItem.measureName }}</text>
						<view class="quantity-control">
							<view class="qty-btn" @click="decreaseQty(selIndex)">
								<text class="qty-btn-text">-</text>
							</view>
							<input 
								class="quantity-input" 
								type="digit" 
								v-model="selItem.qty" 
								placeholder="数量" 
							/>
							<view class="qty-btn" @click="increaseQty(selIndex)">
								<text class="qty-btn-text">+</text>
							</view>
						</view>
						<view class="delete-btn" @click="removeSelected(selIndex)">
							<text class="delete-icon">×</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<view class="btn-row">
				<button class="save-btn" @click="saveApplication">保存</button>
				<button class="confirm-btn" @click="confirmApplication">确认申请</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="uts">
	import { ref, computed, onBeforeUnmount, onMounted } from 'vue'
	import { getItemTypeListByParentId, getItemList, savePurchaseApply, confirmPurchaseApply } from '../../api/apply/index'
	
	type CategoryItem = { id: string; name: string; code: string }
	type Item = { itemId: string; itemName: string; itemTypeName: string; measureName: string; isSelected?: boolean }
	type SelectedItem = { itemId: string; itemName: string; itemTypeName: string; measureName: string; qty: string }
	
	const keyword = ref<string>("")
	
	const dataList = ref<Item[]>([])
	const selectedItems = ref<SelectedItem[]>([])
	const page = ref<number>(1)
	const pageSize: number = 10
	const total = ref<number>(0)
	const totalPages = computed((): number => {
		if (total.value <= 0) return 1
		return Math.ceil(total.value / pageSize)
	})
	const hasMore = ref<boolean>(true)
	const loading = ref<boolean>(false)
	const refreshing = ref<boolean>(false)
	
	const categories = ref<CategoryItem[]>([])
	
	const dealLoad = ref<boolean>(false) 
	let currentStatus = ref<string>('')
	const isSearching = ref<boolean>(false)
	
	// 获取当前选中的分类code
	const getCurrentCategoryCode = (): string => {
		const currentCat = categories.value.find((c: CategoryItem) => c.id === currentStatus.value)
		return currentCat != null ? currentCat.code : ''
	}
	
	// 加载物料列表
	const loadItems = (): void => {
		loading.value = true
		const itemTypeCode = getCurrentCategoryCode()
		getItemList(itemTypeCode, page.value, pageSize, keyword.value).then((res: any) => {
			const data = res as UTSJSONObject
			const rows = data['rows']
			const totalNum = data['total']
			if (totalNum != null) {
				total.value = totalNum as number
			}
			if (rows != null) {
				const listData = rows as UTSJSONObject[]
				if (listData.length > 0) {
					const arr: Item[] = []
					const selectedIds = selectedItems.value.map((s: SelectedItem) => s.itemId)
					listData.forEach((item: UTSJSONObject) => {
						const itemId = item['itemId'] != null ? item['itemId'].toString() : ''
						const it: Item = {
							itemId: itemId,
							itemName: item['itemName'] != null ? item['itemName'].toString() : '',
							itemTypeName: item['itemTypeName'] != null ? item['itemTypeName'].toString() : '',
							measureName: item['measureName'] != null ? item['measureName'].toString() : '',
							isSelected: selectedIds.includes(itemId)
						}
						arr.push(it)
					})
					dataList.value = arr
					loading.value = false
					return
				}
			}
			dataList.value = []
			loading.value = false
		}).catch(() => {
			dataList.value = []
			loading.value = false
		})
	}
	
	// 上一页
	const prevPage = (): void => {
		if (page.value > 1) {
			page.value--
			loadItems()
		}
	}
	
	// 下一页
	const nextPage = (): void => {
		if (page.value < totalPages.value) {
			page.value++
			loadItems()
		}
	}
	
	const loadCategories = (): void => {
		getItemTypeListByParentId(200).then((res: any) => {
			const data = res as UTSJSONObject
			const list = data['data']
			if (list != null) {
				const listData = list as UTSJSONObject[]
				if (listData.length > 0) {
					const arr: CategoryItem[] = []
					listData.forEach((item: UTSJSONObject) => {
						const idVal = item['itemTypeId']
						const nameVal = item['itemTypeName']
						const codeVal = item['itemTypeCode']
						const cat: CategoryItem = {
							id: idVal != null ? idVal.toString() : '',
							name: nameVal != null ? nameVal.toString() : '',
							code: codeVal != null ? codeVal.toString() : ''
						}
						arr.push(cat)
					})
					const allItem: CategoryItem = {id: '', name: '全部', code: ''}
					arr.unshift(allItem)
					categories.value = arr
					// 加载第一个分类的物料
					if (arr.length > 0) {
						currentStatus.value = arr[0].id
						loadItems()
					}
					return
				}
			}
			const defaultArr: CategoryItem[] = []
			const defaultItem: CategoryItem = {id: '', name: '全部', code: ''}
			defaultArr.push(defaultItem)
			categories.value = defaultArr
		}).catch(() => {
			const defaultArr: CategoryItem[] = []
			const defaultItem: CategoryItem = {id: '', name: '全部', code: ''}
			defaultArr.push(defaultItem)
			categories.value = defaultArr
		})
	}
	
	// 添加到已选列表
	const addToSelected = (item: any | null): void => {
		if (item == null) return
		const mdItem = item as Item
		// 检查是否已存在
		const exists = selectedItems.value.find((s: SelectedItem) => s.itemId === mdItem.itemId)
		if (exists != null) {
			uni.showToast({ title: '该物料已在选择列表中', icon: 'none' })
			return
		}
		const selItem: SelectedItem = {
			itemId: mdItem.itemId,
			itemName: mdItem.itemName,
			itemTypeName: mdItem.itemTypeName,
			measureName: mdItem.measureName,
			qty: '1'
		}
		selectedItems.value.push(selItem)
		// 更新 dataList 中的选中状态
		const idx = dataList.value.findIndex((d: Item) => d.itemId === mdItem.itemId)
		if (idx >= 0) {
			dataList.value[idx].isSelected = true
		}
	}
	
	// 删除已选物料
	const removeSelected = (index: number): void => {
		const removedItem = selectedItems.value[index]
		selectedItems.value.splice(index, 1)
		// 重新加载当前页数据以更新选中状态
		loadItems()
	}
	
	// 增加数量
	const increaseQty = (index: number): void => {
		const currentQty = parseInt(selectedItems.value[index].qty)
		selectedItems.value[index].qty = (currentQty + 1).toString()
	}
	
	// 减少数量
	const decreaseQty = (index: number): void => {
		const currentQty = parseInt(selectedItems.value[index].qty)
		if (currentQty > 1) {
			selectedItems.value[index].qty = (currentQty - 1).toString()
		}
	}
	
	const handleItemClick = (item: any | null, index: number): void => {
	    if (item == null) return
		const mdItem = item as Item
	    uni.navigateTo({
	        url: `/pages/item/itemDetail?id=${mdItem.itemId}`
	    })
	}
	const getItemName = (item: any | null): string => {
	    if (item == null) return ''
	    const mdItem = item as Item
	    return mdItem.itemName
	}
	const getItemTypeName = (item: any | null): string => {
	    if (item == null) return ''
	    const mdItem = item as Item
	    return mdItem.itemTypeName
	}
	const getMeasureName = (item: any | null): string => {
	    if (item == null) return ''
	    const mdItem = item as Item
	    return mdItem.measureName
	}
	
	// 检查物料是否已被选择
	const isItemSelected = (item: any | null): boolean => {
	    if (item == null) return false
	    const mdItem = item as Item
	    return selectedItems.value.find((s: SelectedItem) => s.itemId === mdItem.itemId) != null
	}

	const handleSearch = (): void => {
	    page.value = 1
	    loadItems()
	}
	
	const clearKeyword = (): void => {
	    keyword.value = ''
	    page.value = 1
	    loadItems()
	}
	
	const switchStatus = (status: string): void => {
	    if (loading.value) {
	        return;
	    }
	    if (isSearching.value) {
	        return
	    }
	    isSearching.value = true
		currentStatus.value = status
	    page.value = 1
	    loadItems()
	    setTimeout(() => {
	        isSearching.value = false
	    }, 100)
	}

	// 构建申请单数据
	const buildApplyData = (status: string): UTSJSONObject => {
		const applyLines: UTSJSONObject[] = []
		selectedItems.value.forEach((item: SelectedItem) => {
			const lineObj = new UTSJSONObject()
			lineObj['itemId'] = parseInt(item.itemId)
			lineObj['itemCode'] = ''
			lineObj['itemName'] = item.itemName
			lineObj['specification'] = ''
			lineObj['unitOfMeasure'] = ''
			lineObj['quantityApply'] = parseInt(item.qty)
			applyLines.push(lineObj)
		})
		const result = new UTSJSONObject()
		result['applyCode'] = ''
		result['applyName'] = '物料申请'
		result['status'] = status
		result['wmPurchaseApplyLineList'] = applyLines
		return result
	}
	// 来源页面
	const fromIndexPage = ref<boolean>(false)

	// 保存申请
	const saveApplication = (): void => {
		if (selectedItems.value.length === 0) {
			uni.showToast({ title: '请选择物料', icon: 'none' })
			return
		}
		// 构建申请单数据
		const applyData = buildApplyData('PREPARE')
		savePurchaseApply(applyData).then((res: any) => {
		    uni.showToast({ title: '保存成功', icon: 'success' })
		    // 清空已选列表
		    selectedItems.value = []
		    loadItems()
		    // 如果从index.uvue跳转过来，返回index.uvue
		    if (fromIndexPage.value) {
			    setTimeout(() => {
				    uni.navigateBack()
			    }, 1000)
		    }
		}).catch((e) => {
		    console.log(e)
			const error = e as UTSError
			const errMsg = error?.message
			uni.showToast({ title: errMsg.toString(), icon: 'none' })
		})
	}

	// 确认申请
	const confirmApplication = (): void => {
		if (selectedItems.value.length === 0) {
			uni.showToast({ title: '请选择物料', icon: 'none' })
			return
		}
		// 验证所有数量都大于0
		for (let i = 0; i < selectedItems.value.length; i++) {
			const qty = parseFloat(selectedItems.value[i].qty)
			if (qty <= 0) {
				uni.showToast({ title: '所有物料数量必须大于0', icon: 'none' })
				return
			}
		}
		// 构建申请单数据
		const applyData = buildApplyData('CONFIRMED')
		savePurchaseApply(applyData).then((res: any) => {
			uni.showToast({ title: '确认申请成功', icon: 'success' })
			// 清空已选列表
			selectedItems.value = []
			loadItems()
			// 如果从index.uvue跳转过来，返回index.uvue
			if (fromIndexPage.value) {
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}
		}).catch((e) => {
			const error = e as UTSError
			const errMsg = error?.message
			uni.showToast({ title: errMsg.toString(), icon: 'none' })
		})
	}
	onMounted(() => {
		loadCategories()
	// 获取页面参数，判断是否从index.uvue跳转过来
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options
		if (options != null && options.from == 'index') {
			fromIndexPage.value = true
		}
	})
</script>

<style lang="scss">
	.page-container {
		flex: 1;
		background-color: #f5f8fe;
		padding-top: env(safe-area-inset-top);
		background-color: #e8f0f9;
		padding: 0rpx 20rpx 0rpx 20rpx;
	}
	.page-content {
		flex: 1;
		padding: 0rpx;
		padding-bottom: 150rpx;
		box-sizing: border-box;
	}
	.section {
		margin-top: 10rpx;
	    padding: 0 10rpx 10rpx;
	
	    background: #ffffff;
	    border-radius: 16rpx;
	
	    &-header {
	        flex-direction: row;
	        align-items: center;
	        padding: 30rpx 10rpx 20rpx;
	    }
	
	    &-indicator {
	        width: 6rpx;
	        height: 32rpx;
	        background-color: #007aff;
	        border-radius: 3rpx;
	        margin-right: 12rpx;
	    }
	
	    &-title {
	        font-size: 36rpx;
	        color: #333333;
	        font-weight: bold;
	    }
	}
	.search-bar {
	    padding: 10rpx 3rpx;
	}
	.search-box {
	    flex-direction: row;
	    align-items: center;
	    height: 72rpx;
	    padding: 0 24rpx;
	    background-color: #f5f5f5;
	    border-radius: 16rpx;
	
	    .search-icon {
	        width: 32rpx;
	        height: 32rpx;
	        margin-right: 12rpx;
	    }
	
	    .search-input {
	        flex: 1;
	        font-size: 28rpx;
	        color: #333333;
	    }
	
	    .search-btn {
	        padding: 10rpx 20rpx;
	        background-color: #007aff;
	        border-radius: 8rpx;
	        margin-left: 10rpx;
	    }

	    .search-btn-text {
	        color: #ffffff;
	        font-size: 24rpx;
	    }

	    .clear-btn {
	        width: 36rpx;
	        height: 36rpx;
	        border-radius: 18rpx;
	        background-color: #cccccc;
	        align-items: center;
	        justify-content: center;
	        margin-left: 10rpx;
	    }

	    .clear-btn-text {
	        color: #ffffff;
	        font-size: 24rpx;
	        font-weight: bold;
	    }
	}
	.status-tabs {
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #eeeeee;
	}

	.scroll-view_H {
		width: 100%;
		flex-direction: row;
	}

	.status-tab {
		padding: 16rpx 24rpx;
		text-align: center;
		margin-right: 16rpx;
		border-radius: 8rpx;
		background-color: #f5f5f5;
		flex-shrink: 0;

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

		&.active {
			background-color: #007aff;
		}

		.status-tab-text {
			font-size: 26rpx;
			color: #666666;

			&.active-text {
				color: #ffffff;
				font-weight: bold;
			}
		}
	}
	.list-item {
	    margin: 3rpx;
		padding: 10rpx 10rpx 0rpx 10rpx;
	    border-bottom: 1px solid #f9f9f9;
	}
	.item-header {
	    flex-direction: row;
	    align-items: center;
	    justify-content: space-between;
	    margin-bottom: 10rpx;
	}
	.item-title {
	        flex: 1;
	    }
	.item-name {
		    font-size: 28rpx;
		    color: #333333;
		    font-weight: bold;
		}
	.item-name-row {
			flex-direction: row;
			align-items: center;
		}
	.item-measure {
			font-size: 24rpx;
			color: #999999;
			margin-left: 10rpx;
		}
	.item-sub-title {
			flex: 1;
			font-size: 23rpx;
			color: #797979;
			margin-left: 10rpx;
		}
	.item-measure {
			font-size: 23rpx;
			color: #999999;
			margin-left: 10rpx;
		}
	.add-btn {
	        width: 44rpx;
	        height: 44rpx;
	        border-radius: 22rpx;
	        background-color: #165DFF;
	        align-items: center;
	        justify-content: center;
	    }
	
	.add-icon {
	        color: #FFFFFF;
	        font-size: 28rpx;
	        font-weight: bold;
	    }
	    
	.added-btn {
	        padding: 8rpx 16rpx;
	        border-radius: 8rpx;
	        align-items: center;
	        justify-content: center;
	    }
	
	.added-icon {
	        color: #ff4d4f;
	        font-size: 24rpx;
	    }
	    
	.detail-link {
	        font-size: 21rpx;
	        color: #999999;
	    }
	
	.material-list {
		max-height: 720rpx;
		overflow-y: auto;
	}
	
	.pagination {
		flex-direction: row;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		gap: 30rpx;
	}
	
	.page-btn {
		padding: 10rpx 20rpx;
		margin: 5px;
		background-color: #165DFF;
		border-radius: 8rpx;
	}
	
	.page-btn.disabled {
		background-color: #cccccc;
	}
	
	.page-btn-text {
		color: #FFFFFF;
		font-size: 26rpx;
	}
	
	.page-info {
		font-size: 26rpx;
		color: #666666;
	}
	
	.selected-list {
		padding: 20rpx;
		background-color: #ffffff;
		min-height: 150rpx;
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.empty-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40rpx;
	}

	.empty-tip-text {
		color: #999999;
		font-size: 28rpx;
	}

	.selected-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 20rpx;
		border: 1rpx solid #e5e5e5;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
		white-space: nowrap;
	}

	.selected-item-name {
		font-size: 26rpx;
		color: #333333;
		margin-right: 20rpx;
		font-weight: 500;
		// white-space: nowrap;
		max-width: 180rpx;
		// overflow: hidden;
		// text-overflow: ellipsis;
		flex-shrink: 0;
	}

	.selected-item-measure {
		font-size: 24rpx;
		color: #999999;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.quantity-control {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-left: auto;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.qty-btn {
		width: 44rpx;
		height: 44rpx;
		background-color: #f5f5f5;
		border-radius: 6rpx;
		align-items: center;
		justify-content: center;
		border: 1rpx solid #e5e5e5;
	}

	.qty-btn-text {
		color: #333333;
		font-size: 28rpx;
		font-weight: bold;
	}

	.quantity-input {
		width: 160rpx;
		height: 44rpx;
		background-color: #f5f5f5;
		border-radius: 6rpx;
		font-size: 24rpx;
		padding: 0 10rpx;
		border: 1rpx solid #e5e5e5;
		text-align: center;
		margin: 0 10rpx;
	}

	.quantity-input:focus {
		outline: none;
		border-color: #007aff;
		background-color: #ffffff;
	}

	.delete-btn {
		width: 40rpx;
		height: 40rpx;
		border-radius: 20rpx;
		background-color: #ff4d4f;
		align-items: center;
		justify-content: center;
		display: flex;
		flex-shrink: 0; // 防止删除按钮被压缩
	}

	.delete-icon {
		color: #ffffff;
		font-size: 30rpx;
		font-weight: bold;
	}

	/* 底部按钮 */
	.bottom-buttons {
		padding: 20rpx;
		background-color: #ffffff;
		border-top: 1rpx solid #e5e5e5;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 100;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.btn-row {
		flex-direction: row;
		display: flex;
		gap: 20rpx;
	}

	.save-btn {
		width: 180rpx;
		height: 80rpx;
		background-color: #f5f5f5;
		color: #333333;
		font-size: 28rpx;
		font-weight: 500;
		border-radius: 20rpx;
		border: 1rpx solid #e5e5e5;
	}

	.confirm-btn {
		flex: 1;
		height: 80rpx;
		background-color: #007aff;
		color: #ffffff;
		font-size: 28rpx;
		font-weight: 600;
		border-radius: 20rpx;
		margin-left: 10rpx;
		border: none;
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
	}

</style>
