<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" @input="handleSearch" />
			        <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-header-left">
				    	<view class="section-indicator"></view>
				    	<text class="section-title">物料列表</text>
				    </view>
				    <view class="add-material-btn" @click="showAddMaterialModal = true">
				        <text class="add-material-text">新物料</text>
				    </view>
				</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" :class="{'status-0': getAuditStatus(item) == 0, 'status-2': getAuditStatus(item) == 3}">{{ getItemName(item) }}</text>
									<text class="item-measure">{{ getMeasureName(item) }}</text>
								</view>
								<view class="item-sub-row">
									<text class="item-sub-title">{{ getItemTypeName(item) }}</text>
									<text class="item-stock">库存: {{ getStockNum(item) }}</text>
								</view>
							</view>
							<view class="item-actions">
								<view v-if="getAuditStatus(item) == 0 && !item.isSelected! && canDeleteMaterial(item)" class="delete-btn" @click.stop="handleDeleteMaterial(item)">
									<text class="delete-icon">×</text>
								</view>
								<view v-if="item.isSelected" class="added-btn">
									<text class="added-icon">已选</text>
								</view>
								<view v-else-if="isItemDisabled(item)" class="add-btn disabled">
									<text class="add-icon">+</text>
								</view>
								<view v-else class="add-btn" @click.stop="addToSelected(item)">
									<text class="add-icon">+</text>
								</view>
							</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-header-left">
				    	<view class="section-indicator"></view>
				    	<text class="section-title">已选列表</text>
				    </view>
				</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"
					>
						<view class="selected-item-row1">
							<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 class="selected-item-row2">
							<input 
								class="selected-item-remark" 
								type="text" 
								v-model="selItem.remark" 
								placeholder="备注" 
								:maxlength="200"
							/>
						</view>
					</view>
				</view>
			</view>
			
			<view class="section">
				<view class="section-header">
				    <view class="section-header-left">
				    	<view class="section-indicator"></view>
				    	<text class="section-title">备注/用途</text>
				    </view>
				</view>
				<view class="remark-section">
					<textarea 
						class="remark-input" 
						v-model="remark" 
						placeholder="请输入备注/用途" 
						:maxlength="500"
					></textarea>
					<text class="remark-count">{{ remark.length }}/500</text>
				</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 v-if="showAddMaterialModal" class="picker-modal">
		    <view class="modal-mask" @click="showAddMaterialModal = false"></view>
		    <view class="modal-content">
		        <view class="modal-header">
		            <text class="modal-title">{{ materialModalTitle }}</text>
		            <text class="modal-close" @click="showAddMaterialModal = false">取消</text>
		        </view>
				<view v-if="addMaterialError.length > 0" class="error-tip">
					<text class="error-tip-text">{{ addMaterialError }}</text>
					<text class="error-tip-close" @click="addMaterialError = ''">×</text>
				</view>
				<view class="form-item-input">
				    <text class="label-picker">物料名称</text>
				    <view class="view-input-picker">
				        <input class="input-picker" type="text" placeholder="请输入物料名称" v-model="newMaterial.itemName" />
				    </view>
				</view>
				<view class="form-item-input">
				    <text class="label-picker">规格型号</text>
				    <view class="view-input-picker">
				        <input class="input-picker" type="text" placeholder="请输入规格型号" v-model="newMaterial.specification" />
				    </view>
				</view>
				<view class="form-item-input">
				    <text class="label-picker">单位</text>
				    <view class="view-input-picker measure-input-row">
				        <input class="input-picker" type="text" placeholder="请输入或选择单位" v-model="newMaterial.measureName" />
				        <view class="pick-btn" @click="showMeasurePicker = true">
				        	<text class="pick-btn-text">选择</text>
				        </view>
				    </view>
				</view>
				<view class="form-item-input">
				    <text class="label-picker">产品链接</text>
				    <view class="view-input-picker">
				        <input class="input-picker" type="url" placeholder="请输入产品链接" v-model="newMaterial.productUrl" />
				    </view>
				</view>
				<view class="form-item-input">
				    <text class="label-picker">图片（最多3张）</text>
				    <view class="upload-wrapper">
				        <UploadImage
				            :maxCount="3"
				            :modelValue="newMaterial.imageUrls"
				            businessType="material"
				            @update:modelValue="handleImageUpdate"
				            @delete="handleImageDelete"
				            @preview="handleImagePreview"
				        />
				    </view>
				</view>
				<view class="form-item-btn">
					<button class="btn-primary" @click="handleAddMaterial">
						保存
					</button>
				</view>
		    </view>
		</view>
		
		<!-- 单位选择弹窗 -->
		<view v-if="showMeasurePicker" class="picker-modal">
		    <view class="modal-mask" @click="showMeasurePicker = false"></view>
		    <view class="modal-content">
		        <view class="modal-header">
		            <text class="modal-title">选择单位</text>
		            <text class="modal-close" @click="showMeasurePicker = false">取消</text>
		        </view>
				<scroll-view class="measure-list" :scroll-y="true">
					<view 
						v-for="(item, index) in measureList" 
						:key="index" 
						class="measure-item"
						@click="selectMeasure(item)"
					>
						<text class="measure-name">{{ item['measureName'] }}</text>
					</view>
					<view v-if="measureList.length === 0" class="empty-tip">
						<text class="empty-tip-text">暂无单位数据</text>
					</view>
				</scroll-view>
		    </view>
		</view>
		
		<!-- 删除确认弹窗 -->
		<view v-if="showDeleteConfirm" class="delete-confirm-modal">
		    <view class="delete-confirm-mask" @click="showDeleteConfirm = false"></view>
		    <view class="delete-confirm-content">
		        <text class="delete-confirm-title">确认删除</text>
		        <text class="delete-confirm-text">确定要删除这张图片吗？</text>
		        <view class="delete-confirm-btns">
		            <view class="delete-confirm-cancel" @click="showDeleteConfirm = false">
		                <text class="delete-confirm-cancel-text">取消</text>
		            </view>
		            <view class="delete-confirm-ok" @click="confirmDeleteImage">
		        <text class="delete-confirm-ok-text">确定</text>
		            </view>
		        </view>
		    </view>
		</view>
		
		<!-- 图片预览弹窗 -->
		<view v-if="showImagePreview" class="image-preview-modal" @click="showImagePreview = false">
		    <swiper class="preview-swiper" :current="previewIndex" @change="handlePreviewChange">
		        <swiper-item v-for="(url, idx) in previewUrls" :key="idx">
		            <image class="preview-image" :src="url" mode="aspectFit" @click.stop></image>
		        </swiper-item>
		    </swiper>
		    <view class="preview-close" @click="showImagePreview = false">
		        <text class="preview-close-text">×</text>
		    </view>
		    <view class="preview-indicator">
		        <text class="preview-indicator-text">{{ previewIndex + 1 }} / {{ previewUrls.length }}</text>
		    </view>
		</view>
	</view>
</template>

<script setup lang="uts">
import { ref, computed, onBeforeUnmount, onMounted } from 'vue'
import { getItemTypeListByParentId, getItemList, savePurchaseApply, confirmPurchaseApply, addMaterial, getMeasureList, deleteMaterial, updateMaterial } from '../../api/apply/index'
import { getUserInfo } from '../../utils/storage'
import UploadImage from '../../components/upload-image/upload-image.uvue'
import type { UploadResponse } from '../../types/workbench'

let searchTimer: number | null = null
	
	type CategoryItem = { id: string; name: string; code: string }
	type Item = { 
		itemId: string; 
		itemName: string; 
		itemCode: string;
		itemTypeName: string; 
		measureName: string; 
		specification: string;
		imageUrls: string;
		productUrl: string;
		auditStatus: number;
		stockNum: number;
		createBy: string;
		isSelected?: boolean; 
	}
	type SelectedItem = { itemId: string; itemName: string; itemTypeName: string; measureName: string; qty: string; remark: string }
	
	const keyword = ref<string>("")

	const dataList = ref<Item[]>([])
	const selectedItems = ref<SelectedItem[]>([])
	const remark = ref<string>("")
	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)

// 当前登录用户
const currentUserName = ref<string>('')

// 新增物料相关
const showAddMaterialModal = ref<boolean>(false)
const addMaterialError = ref<string>('')
const showMeasurePicker = ref<boolean>(false)
const measureList = ref<UTSJSONObject[]>([])
const showDeleteConfirm = ref<boolean>(false)
const deleteImageIndex = ref<number>(0)
const showImagePreview = ref<boolean>(false)
const previewUrls = ref<string[]>([])
const previewIndex = ref<number>(0)
// 编辑物料相关
const editingMaterialItem = ref<Item | null>(null)

// 弹窗标题
const materialModalTitle = computed<string>(() => {
	return editingMaterialItem.value != null ? '修改物料' : '新增物料'
})

type NewMaterial = {
	itemName: string
	specification: string
	measureName: string
	imageUrls: UploadResponse[]
	productUrl: string
}
const newMaterial = ref<NewMaterial>({
    itemName: '',
    specification: '',
    measureName: '',
    imageUrls: [],
    productUrl: ''
})

// 加载单位列表
const loadMeasureList = (): void => {
	getMeasureList().then((res: any) => {
		const data = res as UTSJSONObject
		const list = data['data']
		if (list != null) {
			measureList.value = list as UTSJSONObject[]
		}
	}).catch(() => {
		measureList.value = []
	})
}

// 选择单位
const selectMeasure = (item: UTSJSONObject): void => {
	const measureName = item['measureName'] != null ? item['measureName'].toString() : ''
	newMaterial.value.measureName = measureName
	showMeasurePicker.value = 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() : ''
						let auditStatus = -1
						const auditStatusVal = item['auditStatus']
						if (auditStatusVal != null) {
							if (typeof auditStatusVal === 'number') {
								auditStatus = auditStatusVal as number
							} else {
								auditStatus = parseInt(auditStatusVal.toString())
							}
						}
						let stockNum = 0
						const stockNumVal = item['stockNum']
						if (stockNumVal != null) {
							if (typeof stockNumVal === 'number') {
								stockNum = stockNumVal as number
							} else {
								stockNum = parseFloat(stockNumVal.toString())
							}
						}
						const it: Item = {
							itemId: itemId,
							itemName: item['itemName'] != null ? item['itemName'].toString() : '',
							itemCode: item['itemCode'] != null ? item['itemCode'].toString() : '',
							itemTypeName: item['itemTypeName'] != null ? item['itemTypeName'].toString() : '',
							measureName: item['measureName'] != null ? item['measureName'].toString() : '',
							specification: item['specification'] != null ? item['specification'].toString() : '',
							imageUrls: item['imageUrls'] != null ? item['imageUrls'].toString() : '',
							productUrl: item['productUrl'] != null ? item['productUrl'].toString() : '',
							isSelected: selectedIds.includes(itemId),
							auditStatus: auditStatus,
							stockNum: stockNum,
							createBy: item['createBy'] != null ? item['createBy'].toString() : ''
						}
						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
		// 检查审核状态
		if (mdItem.auditStatus != null && mdItem.auditStatus === 2) {
			uni.showToast({ title: '该物料已禁用，无法添加', icon: 'none'})
			return
		}
		// 检查是否已存在
		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',
			remark: ''
		}
		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
	// 判断是否满足编辑条件
	if (getAuditStatus(mdItem) == 0 && !mdItem.isSelected && canDeleteMaterial(mdItem)) {
		// 满足编辑条件，弹出编辑窗口
		editingMaterialItem.value = mdItem
		let imageUrls: UploadResponse[] = []
		if (mdItem.imageUrls && mdItem.imageUrls.length > 0) {
			const fileNames = mdItem.imageUrls.split(',')
			imageUrls = fileNames.map((fileName: string) => {
				return {
					fileName: fileName,
					url: fileName
				} as UploadResponse
			})
		}
		let itemName = mdItem.itemName
		if (mdItem.specification && mdItem.itemName.endsWith('(' + mdItem.specification + ')')) {
			itemName = mdItem.itemName.substring(0, mdItem.itemName.length - ('(' + mdItem.specification + ')').length)
		}
		newMaterial.value = {
			itemName: itemName,
			specification: mdItem.specification || '',
			measureName: mdItem.measureName || '',
			imageUrls: imageUrls,
			productUrl: mdItem.productUrl || ''
		} as NewMaterial
		showAddMaterialModal.value = true
	} else {
		// 不满足编辑条件，跳转到详情页
	    uni.navigateTo({
	        url: `/pages/item/detail?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 getStockNum = (item: any | null): string => {
	    if (item == null) return '0'
	    const mdItem = item as Item
	    const stock = mdItem.stockNum != null ? mdItem.stockNum : 0
	    return stock.toString()
	}
	
	const getAuditStatus = (item: any | null): number => {
	    if (item == null) return -1
	    const mdItem = item as Item
	    return mdItem.auditStatus != null ? mdItem.auditStatus : -1
	}
	
	const isItemDisabled = (item: any | null): boolean => {
	    if (item == null) return false
	    const mdItem = item as Item
	    const status = mdItem.auditStatus != null ? mdItem.auditStatus : -1
	    return status == 3
	}
	
	// 判断物料是否可删除（创建人是当前用户）
	const canDeleteMaterial = (item: any | null): boolean => {
		if (item == null) return false
		const mdItem = item as Item
		const createBy = mdItem.createBy != null ? mdItem.createBy : ''
		return createBy === currentUserName.value
	}
	
	// 检查物料是否已被选择
	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 => {
		const timer = searchTimer
		if (timer != null) {
			clearTimeout(timer)
		}
		searchTimer = setTimeout(() => {
			page.value = 1
			loadItems()
		}, 300)
	}
	
	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)
			lineObj['remark'] = item.remark || ''
			applyLines.push(lineObj)
		})
		const result = new UTSJSONObject()
		result['applyCode'] = ''
		result['applyName'] = '物料申请'
		result['status'] = status
		result['remark'] = remark.value
		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')
		if (applyData['remark'].length === 0) {
			uni.showToast({ title: '请输入用途', icon: 'none'})
			return
		}
		savePurchaseApply(applyData).then((res: any) => {
		    uni.showToast({ title: '保存成功', icon: 'success'})
		    // 清空已选列表
		    selectedItems.value = []
		    loadItems()
		    // 如果从index.uvue跳转过来，返回index.uvue
		    if (fromIndexPage.value) {
			    setTimeout(() => {
				    uni.navigateBack()
			    }, 1000)
		    }else{
				uni.navigateTo({
				    url: `/pages/apply/index?from=new`
				})
			}
		}).catch((e) => {
			const error = e as UTSError
			const errMsg = error?.message
			uni.showModal({
				title: '提示',
				content: errMsg.toString(),
				showCancel: false,
				confirmText: '确定'
			})
		})
	}
	
	// 确认申请
	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')
		if (applyData['remark'].length === 0) {
			uni.showToast({ title: '请输入用途', icon: 'none'})
			return
		}
		savePurchaseApply(applyData).then((res: any) => {
			uni.showToast({ title: '确认申请成功', icon: 'success'})
			// 清空已选列表
			selectedItems.value = []
			loadItems()
			// 如果从index.uvue跳转过来，返回index.uvue
			if (fromIndexPage.value) {
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			}else{
				uni.navigateTo({
				    url: `/pages/apply/index?from=new`
				})
			}
		}).catch((e) => {
			const error = e as UTSError
			const errMsg = error?.message
			uni.showModal({
				title: '提示',
				content: errMsg.toString(),
				showCancel: false,
				confirmText: '确定'
			})
		})
	}
	


// 处理图片更新
const handleImageUpdate = (value: UploadResponse[]): void => {
    newMaterial.value.imageUrls = value
}

// 处理图片删除
const handleImageDelete = (index: number, currentList: UploadResponse[]): void => {
    deleteImageIndex.value = index
    showDeleteConfirm.value = true
}

const confirmDeleteImage = (): void => {
    newMaterial.value.imageUrls.splice(deleteImageIndex.value, 1)
    showDeleteConfirm.value = false
}

// 处理图片预览
const handleImagePreview = (index: number, urls: string[]): void => {
    previewUrls.value = urls
    previewIndex.value = index
    showImagePreview.value = true
}

const handlePreviewChange = (e: any): void => {
    previewIndex.value = e.detail.current
}

// 处理新增/编辑物料
const handleAddMaterial = async (): Promise<void> => {
	// 验证输入
	if (newMaterial.value.itemName.length == 0) {
		uni.showToast({ title: '请输入物料名称', icon: 'none'})
		return
	}
	if (newMaterial.value.measureName.length == 0) {
		uni.showToast({ title: '请输入单位', icon: 'none'})
		return
	}

	try {
		// 构建物料数据
			const materialData = new UTSJSONObject()
			materialData['itemShortName'] = newMaterial.value.itemName
			materialData['itemName'] = newMaterial.value.itemName + "("+newMaterial.value.specification+")"
			materialData['specification'] = newMaterial.value.specification
			materialData['measureName'] = newMaterial.value.measureName
			materialData['auditStatus'] = 0 // 审核状态为0
			// 从 UploadResponse 数组中提取 fileName 并拼接成逗号分隔的字符串
			const imageFileNames = newMaterial.value.imageUrls.map((item: UploadResponse) => item.fileName).join(',')
			materialData['imageUrls'] = imageFileNames
			materialData['productUrl'] = newMaterial.value.productUrl
		
		// 判断是新增还是编辑
		if (editingMaterialItem.value != null) {
			// 编辑模式
			await updateMaterial(editingMaterialItem.value.itemId, materialData)
			uni.showToast({ title: '物料修改成功', icon: 'success'})
		} else {
			// 新增模式
			await addMaterial(materialData)
			uni.showToast({ title: '物料新增成功', icon: 'success'})
		}
		
		// 关闭弹窗
		showAddMaterialModal.value = false
		
		// 清空表单
		editingMaterialItem.value = null
		newMaterial.value = {
			itemName: '',
			specification: '',
			measureName: '',
			imageUrls: [],
			productUrl: ''
		} as NewMaterial
		
		// 重新加载物料列表
		loadItems()
	} catch (e) {
		const error = e as UTSError
		const errMsg = error?.message
		// 显示错误提示
		addMaterialError.value = errMsg.toString()
	}
}

const handleDeleteMaterial = (item: Item): void => {
	uni.showModal({
		title: '确认删除',
		content: `确定要删除物料「${item.itemName}」吗？`,
		success: (res) => {
			if (res.confirm) {
				deleteMaterial(item.itemId).then(() => {
					uni.showToast({ 
						title: '删除成功', 
						icon: 'success', 
					})
					loadItems()
				}).catch((e) => {
					const error = e as UTSError
					const errMsg = error?.message
					uni.showModal({
							title: '删除失败',
							content: errMsg.toString(),
							showCancel: false,
							confirmText: '确定'
						})
				})
			}
		}
	})
}

onMounted(() => {
	loadCategories()
	loadMeasureList()
	// 获取当前登录用户信息
	const userInfo = getUserInfo()
	if (userInfo != null) {
		currentUserName.value = userInfo['userName'] != null ? userInfo['userName'].toString() : ''
	}
	// 获取页面参数，判断是否从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;
	
		.section-header {
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 10rpx 20rpx;
		}
		
		.section-header-left {
			flex-direction: row;
			align-items: center;
		}
				    
		.add-material-btn {
			padding: 8rpx 16rpx;
			background-color: #007aff;
			border-radius: 8rpx;
		}
		
		.add-material-text {
			color: #ffffff;
			font-size: 24rpx;
			font-weight: bold;
		}
	
	    &-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 {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10rpx;
}

	.item-actions {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.item-title {
	        flex: 1;
	    }
	.item-name {
		    font-size: 28rpx;
		    color: #333333;
		    font-weight: bold;
		
		&.status-0 {
			color: #ff4d4f;
		}
		
		&.status-2 {
			color: #999999;
		}
	}
	.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-sub-row {
			flex-direction: row;
			align-items: center;
		}
	.item-stock {
			font-size: 23rpx;
			color: #52c41a;
			margin-left: 20rpx;
		}
	.item-measure {
			font-size: 23rpx;
			color: #999999;
			margin-left: 10rpx;
		}
	.add-btn {
	        width: 44rpx;
	        height: 44rpx;
	        border-radius: 22rpx;
	        background-color: #165DFF;
			color: #FFFFFF;
	        align-items: center;
	        justify-content: center;
	    }
	
	.add-btn.disabled {
	        background-color: #cccccc;
	    }
	    
	.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 {
	}
	
	.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: column;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 16rpx 20rpx;
		border: 1rpx solid #e5e5e5;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 12rpx;
	}

	.selected-item-row1 {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.selected-item-row2 {
		margin-top: 10rpx;
	}

	.selected-item-name {
		font-size: 26rpx;
		color: #333333;
		margin-right: 20rpx;
		font-weight: 500;
		max-width: 180rpx;
		flex-shrink: 0;
	}

	.selected-item-remark-row {
		margin-top: 10rpx;
	}

	.selected-item-remark {
		width: 100%;
		height: 56rpx;
		padding: 0 16rpx;
		background-color: #f5f5f5;
		border-radius: 6rpx;
		font-size: 24rpx;
		color: #333333;
		border: 1rpx solid #e5e5e5;
	}

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

		/* 新增物料弹窗样式 */
		.picker-modal {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 1000;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.modal-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.modal-content {
			position: relative;
			width: 90%;
			// max-width: 500rpx;
			background-color: #ffffff;
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
		}

		.modal-header {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid #e5e5e5;
		}

		.modal-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333333;
		}

		.modal-close {
			font-size: 28rpx;
			color: #999999;
			padding: 8rpx 16rpx;
			border-radius: 8rpx;
			background-color: #f5f5f5;
		}

		.form-item-input {
			display: flex;
			flex-direction: column;
			margin-bottom: 24rpx;
		}

		.label-picker {
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 12rpx;
			font-weight: 500;
		}

		.view-input-picker {
			position: relative;
			width: 100%;
		}

		.input-picker {
			width: 100%;
			height: 80rpx;
			padding: 0 24rpx;
			background-color: #f5f5f5;
			border-radius: 12rpx;
			font-size: 28rpx;
			color: #333333;
			border: 1rpx solid #e5e5e5;
		}

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

		.form-item-btn {
			margin-top: 30rpx;
			display: flex;
			justify-content: center;
		}

		.error-tip {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			margin: 20rpx;
			padding: 16rpx 20rpx;
			background-color: #fff2f0;
			border: 1rpx solid #ffccc7;
			border-radius: 8rpx;
		}

		.error-tip-text {
			flex: 1;
			font-size: 26rpx;
			color: #ff4d4f;
		}

		.error-tip-close {
			margin-left: 16rpx;
			font-size: 32rpx;
			color: #999999;
			font-weight: bold;
		}

		.btn-primary {
			width: 100%;
			height: 80rpx;
			background-color: #007aff;
			color: #ffffff;
			font-size: 28rpx;
			font-weight: 600;
			border-radius: 12rpx;
			border: none;
			box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
		}
		.add-icon{
			color: #ffffff;
		}
		
		.measure-list {
			max-height: 500rpx;
			overflow-y: auto;
		}
		
		.measure-item {
			padding: 24rpx;
			border-bottom: 1rpx solid #f0f0f0;
		}
		
		.measure-name {
			font-size: 28rpx;
			color: #333333;
		}
		
		.measure-input-row {
			flex-direction: row;
			align-items: center;
		}
		
		.measure-input-row .input-picker {
			flex: 1;
			margin-right: 16rpx;
		}
		
		.pick-btn {
			padding: 16rpx 24rpx;
			background-color: #007aff;
			border-radius: 8rpx;
		}
		
		.pick-btn-text {
					color: #ffffff;
					font-size: 26rpx;
				}

				/* 备注输入框样式 */
				.remark-section {
					padding: 20rpx;
					background-color: #ffffff;
				}
				
				.remark-input {
					width: 100%;
					min-height: 200rpx;
					padding: 20rpx;
					background-color: #f5f5f5;
					border-radius: 12rpx;
					font-size: 28rpx;
					color: #333333;
					border: 1rpx solid #e5e5e5;
					resize: none;
					box-sizing: border-box;
				}
				
				.remark-input:focus {
					outline: none;
					border-color: #007aff;
					background-color: #ffffff;
				}
				
				.remark-count {
					display: block;
					text-align: right;
					margin-top: 10rpx;
					font-size: 24rpx;
					color: #999999;
				}

				/* 图片上传样式 */
				.image-upload-container {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					gap: 16rpx;
					margin-top: 12rpx;
				}

				.uploaded-image {
					position: relative;
					width: 160rpx;
					height: 160rpx;
					border-radius: 8rpx;
					overflow: hidden;
					border: 1rpx solid #e5e5e5;
				}

				.uploaded-image-item {
					width: 100%;
					height: 100%;
				}

				.image-delete-btn {
					position: absolute;
					top: 8rpx;
					right: 8rpx;
					width: 36rpx;
					height: 36rpx;
					border-radius: 18rpx;
					background-color: rgba(0, 0, 0, 0.6);
					display: flex;
					align-items: center;
					justify-content: center;
				}

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

				.upload-btn {
					width: 160rpx;
					height: 160rpx;
					border-radius: 8rpx;
					border: 2rpx dashed #e5e5e5;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					background-color: #fafafa;
				}

				.upload-btn-icon {
					font-size: 48rpx;
					color: #999999;
					margin-bottom: 8rpx;
				}

				.upload-btn-text {
					font-size: 24rpx;
					color: #999999;
				}
				
				/* 删除确认弹窗样式 */
				.delete-confirm-modal {
					position: fixed;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					z-index: 10000;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.delete-confirm-mask {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background-color: rgba(0, 0, 0, 0.5);
				}
				
				.delete-confirm-content {
					position: relative;
					width: 600rpx;
					background-color: #ffffff;
					border-radius: 16rpx;
					padding: 40rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
				}
				
				.delete-confirm-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 20rpx;
				}
				
				.delete-confirm-text {
					font-size: 28rpx;
					color: #666666;
					margin-bottom: 40rpx;
				}
				
				.delete-confirm-btns {
					display: flex;
					flex-direction: row;
					gap: 40rpx;
				}
				
				.delete-confirm-cancel {
					padding: 20rpx 60rpx;
					background-color: #f5f5f5;
					border-radius: 12rpx;
				}
				
				.delete-confirm-cancel-text {
					font-size: 28rpx;
					color: #666666;
				}
				
				.delete-confirm-ok {
					padding: 20rpx 60rpx;
					background-color: #ff4d4f;
					border-radius: 12rpx;
				}
				
				.delete-confirm-ok-text {
					font-size: 28rpx;
					color: #ffffff;
				}
				
				/* 图片预览弹窗样式 */
				.image-preview-modal {
					position: fixed;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background-color: #000000;
					z-index: 10000;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.preview-swiper {
					width: 100%;
					height: 80%;
				}
				
				.preview-image {
					width: 100%;
					height: 100%;
				}
				
				.preview-close {
					position: absolute;
					top: 80rpx;
					right: 30rpx;
					width: 60rpx;
					height: 60rpx;
					border-radius: 30rpx;
					background-color: rgba(255, 255, 255, 0.3);
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.preview-close-text {
					font-size: 40rpx;
					color: #ffffff;
				}
				
				.preview-indicator {
					position: absolute;
					bottom: 100rpx;
					left: 50%;
					transform: translateX(-50%);
					padding: 10rpx 30rpx;
					background-color: rgba(0, 0, 0, 0.5);
					border-radius: 20rpx;
				}
				
				.preview-indicator-text {
					font-size: 28rpx;
					color: #ffffff;
				}
 </style>
