<template>
	<view class="form-container">
		<view class="form-card">
			<view class="form-content">
				<form @submit="handleFormSubmit">
					<!-- 申请人 -->
					<!-- <view class="form-group">
						<text class="form-label">申请人</text>
						<view class="input-wrapper">
							<u-input v-model="formData.applicationUserName" placeholder="自动填充" readonly 
								class="select-input" />
						</view>
					</view> -->

					<!-- 申请门店 -->
					<!-- <view class="form-group">
						<text class="form-label">申请门店</text>
						<view class="input-wrapper">
							<u-input v-model="formData.applicationStoreName" placeholder="自动填充" readonly 
								class="select-input" />
						</view>
					</view> -->

					<!-- 申请时间 -->
					<view class="form-group">
						<text class="form-label">申请时间</text>
						<view class="input-wrapper">
							<picker mode="date" :value="formData.applicationTimeStr" @change="onApplicationTimeChange">
								<view class="custom-select">
									<text class="select-text">{{ formData.applicationTimeStr || '请选择申请时间' }}</text>
									<text class="select-arrow">▼</text>
								</view>
							</picker>
						</view>
					</view>

					<!-- 总金额 -->
					<view class="form-group">
						<text class="form-label">总金额</text>
						<view class="input-wrapper">
							<u-input v-model="formData.amount" placeholder="自动计算" type="digit" readonly 
								class="select-input" />
						</view>
					</view>

					<!-- 购买物品清单 -->
					<view class="form-group">
						<text class="form-label">购买物品清单</text>
						<view class="input-wrapper">
							<view class="purchase-select-btn" @tap="openPurchaseDialog">
								<text class="btn-text">选择购买物品</text>
							</view>
							<text v-if="selectedPurchaseRecords.length > 0" class="selected-count">
								已选择 {{ selectedPurchaseRecords.length }} 条记录
							</text>
						</view>
					</view>

					<!-- 已选择的购买物品清单 -->
					<view class="form-group" v-if="selectedPurchaseRecords.length > 0">
						<view class="purchase-list">
							<view v-for="(item, index) in selectedPurchaseRecords" :key="item.id || index" class="purchase-item">
								<view class="purchase-item-header">
									<text class="purchase-category">{{ item.reimbursementCategoryName || '无' }}</text>
									<view class="purchase-item-actions">
										<text v-if="item.isInitial" class="initial-mark">初始记录</text>
										<view v-if="!item.isInitial" class="purchase-remove" @tap="removePurchaseRecord(index)">
											<text class="remove-icon">✕</text>
										</view>
									</view>
								</view>
								<view class="purchase-item-details">
									<text class="purchase-detail">单价: ¥{{ item.unitPrice || 0 }}</text>
									<text class="purchase-detail">数量: {{ item.quantity || 0 }}</text>
									<text class="purchase-detail amount">金额: ¥{{ item.amount || 0 }}</text>
								</view>
								<view class="purchase-item-time">
									<text class="purchase-time">购买时间: {{ formatTime(item.purchaseTime) }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 审批节点配置（仅新建时显示） -->
					<view class="form-group" v-if="!formData.id">
						<view class="nodes-header">
							<text class="form-label">审批节点配置（1-5个节点）</text>
							<view class="add-node-btn" @tap="addNode" v-if="formData.nodes.length < 5">
								<text class="add-node-text">+ 添加节点</text>
							</view>
						</view>
						<view class="nodes-list">
							<view v-for="(node, index) in formData.nodes" :key="index" class="node-item">
								<view class="node-header">
									<text class="node-order">节点 {{ node.nodeOrder }}</text>
									<view v-if="formData.nodes.length > 1" class="remove-node-btn" @tap="removeNode(index)">
										<text class="remove-node-text">删除</text>
									</view>
								</view>
								<view class="node-form">
									<view class="node-form-item">
										<text class="node-label">节点名称</text>
										<u-input v-model="node.nodeName" placeholder="请输入节点名称" class="node-input" />
									</view>
									<view class="node-form-item">
										<text class="node-label">审批类型</text>
										<picker mode="selector" :range="['会签', '或签']" :value="node.approvalType === '会签' ? 0 : (node.approvalType === '或签' ? 1 : -1)" @change="(e) => { node.approvalType = ['会签', '或签'][e.detail.value] }">
											<view class="custom-select">
												<text class="select-text">{{ node.approvalType || '请选择审批类型' }}</text>
												<text class="select-arrow">▼</text>
											</view>
										</picker>
									</view>
									<view class="node-form-item">
										<text class="node-label">审批人</text>
										<view class="approver-select-wrapper">
											<view class="approver-select-btn" @tap="openUserDialog(index)">
												<text class="approver-btn-text">{{ getApproverDisplayText(node) }}</text>
											</view>
											<view v-if="node.approverNames && node.approverNames.length > 0" class="approver-tags">
												<view v-for="(name, nameIndex) in node.approverNames" :key="nameIndex" class="approver-tag">
													{{ name }}
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 提交按钮 -->
					<view class="btn-group">
						<button type="submit" class="btn btn-primary" 
							:style="{opacity: isSubmitting ? 0.5 : 1}" 
							@tap="isSubmitting ? null : handleFormSubmit()">
							{{ isSubmitting ? '提交中...' : (formData.id ? '更新' : '提交') }}
						</button>
					</view>
				</form>
			</view>
		</view>

		<!-- 选择购买物品弹窗 -->
		<view v-if="showPurchaseDialog" class="modal-overlay" @tap="closePurchaseDialog">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">选择购买物品</text>
					<view class="modal-close" @tap="closePurchaseDialog">
						<text class="close-icon">✕</text>
					</view>
				</view>
				<view class="modal-body">
					<!-- 搜索框 -->
					<view class="search-box">
						<u-input v-model="searchKeyword" placeholder="搜索分类名称" @input="handleSearch" 
							class="search-input" />
					</view>
					<!-- 购买记录列表 -->
					<scroll-view scroll-y class="purchase-dialog-list" @scrolltolower="loadMorePurchaseRecords">
						<view v-if="purchaseListLoading && filteredPurchaseList.length === 0" class="loading-text">加载中...</view>
						<view v-else-if="!purchaseListLoading && filteredPurchaseList.length === 0" class="empty-text">暂无可用记录</view>
						<view v-else>
							<view 
								v-for="(item, index) in filteredPurchaseList" 
								:key="item.id || index" 
								class="purchase-dialog-item"
								:class="{ 'selected': isPurchaseSelected(item.id) }"
								@tap="togglePurchaseSelection(item)">
								<view class="purchase-dialog-header">
									<text class="purchase-dialog-category">{{ item.reimbursementCategoryName || '无' }}</text>
									<view v-if="isPurchaseSelected(item.id)" class="selected-mark">✓</view>
								</view>
								<view class="purchase-dialog-details">
									<text class="purchase-dialog-detail">单价: ¥{{ item.unitPrice || 0 }}</text>
									<text class="purchase-dialog-detail">数量: {{ item.quantity || 0 }}</text>
									<text class="purchase-dialog-detail amount">金额: ¥{{ item.amount || 0 }}</text>
								</view>
								<view class="purchase-dialog-time">
									<text>{{ formatTime(item.purchaseTime) }}</text>
								</view>
							</view>
							<view v-if="purchaseListLoading && filteredPurchaseList.length > 0" class="loading-more">加载更多...</view>
						</view>
					</scroll-view>
				</view>
				<view class="modal-footer">
					<button class="modal-btn cancel-btn" @tap="closePurchaseDialog">取消</button>
					<button class="modal-btn confirm-btn" @tap="confirmPurchaseSelection">确定</button>
				</view>
			</view>
		</view>

		<!-- 选择审批人弹窗 -->
		<view v-if="showUserDialog" class="modal-overlay" @tap="closeUserDialog">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">选择审批人</text>
					<view class="modal-close" @tap="closeUserDialog">
						<text class="close-icon">✕</text>
					</view>
				</view>
				<view class="modal-body">
					<!-- 搜索框 -->
					<view class="search-box">
						<u-input v-model="userSearchKeyword" placeholder="搜索用户姓名或账号" @input="handleUserSearch" 
							class="search-input" />
					</view>
					<!-- 用户列表 -->
					<scroll-view scroll-y class="user-dialog-list" @scrolltolower="loadMoreUsers">
						<view v-if="userListLoading && userList.length === 0" class="loading-text">加载中...</view>
						<view v-else-if="!userListLoading && userList.length === 0" class="empty-text">暂无用户</view>
						<view v-else>
							<view 
								v-for="(item, index) in filteredUserList" 
								:key="item.id || index" 
								class="user-dialog-item"
								:class="{ 'selected': isUserSelected(item.id) }"
								@tap="toggleUserSelection(item)">
								<view class="user-dialog-header">
									<text class="user-dialog-name">{{ item.fullName || item.realName || item.userName || item.id || '无' }}</text>
									<view v-if="isUserSelected(item.id)" class="selected-mark">✓</view>
								</view>
								<view class="user-dialog-details">
									<text class="user-dialog-detail">账号: {{ item.account || '无' }}</text>
									<text class="user-dialog-detail">ID: {{ item.id || '无' }}</text>
								</view>
							</view>
							<view v-if="userListLoading && filteredUserList.length > 0" class="loading-more">加载更多...</view>
							<view v-else-if="!userListLoading && filteredUserList.length >= userTotal && userTotal > 0" class="no-more">没有更多了</view>
							<view v-if="userTotal > 0" class="pagination-info">
								<text>共 {{ userTotal }} 人，已加载 {{ filteredUserList.length }} 人</text>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="modal-footer">
					<button class="modal-btn cancel-btn" @tap="closeUserDialog">取消</button>
					<button class="modal-btn confirm-btn" @tap="confirmUserSelection">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/apis/index.js'
	import purchaseApi from '@/apis/modules/purchase.js'
	import oauthApi from '@/apis/modules/oauth.js'

	export default {
		data() {
			return {
				isSubmitting: false,
				formData: {
					id: undefined,
					applicationUserId: undefined,
					applicationUserName: undefined,
					applicationStoreId: undefined,
					applicationStoreName: undefined,
					applicationTime: undefined,
					applicationTimeStr: undefined,
					amount: undefined,
					approveStatus: '未审批',
					selectedPurchaseRecordIds: [],
					nodes: [] // 审批节点配置
				},
				selectedPurchaseRecords: [],
				initialPurchaseRecordIds: [], // 存储初始的购买记录ID列表（编辑时使用）
				// 购买物品选择弹窗相关
				showPurchaseDialog: false,
				purchaseList: [],
				filteredPurchaseList: [],
				purchaseListLoading: false,
				purchaseQuery: {
					currentPage: 1,
					pageSize: 20,
					reimbursementCategoryName: ''
				},
				purchaseTotal: 0,
				tempSelectedPurchaseIds: [],
				searchKeyword: '',
				userInfo: null,
				newuserInfo: null,
				// 用户选择弹窗相关
				showUserDialog: false,
				currentNodeIndex: -1, // 当前正在编辑的节点索引
				userList: [],
				filteredUserList: [],
				userListLoading: false,
				userQuery: {
					currentPage: 1,
					pageSize: 20,
					keyword: ''
				},
				userTotal: 0,
				tempSelectedUserIds: [], // 临时选中的用户ID列表
				searchTimer: null // 搜索防抖定时器
			}
		},

		onLoad(options) {
			this.initializePage(options)
		},

		methods: {
			// 初始化页面
			async initializePage(options) {
				try {
					// 获取用户信息
					this.userInfo = uni.getStorageSync('userInfo')
					this.newuserInfo = uni.getStorageSync('newuserInfo')
					
					if (!this.userInfo || Object.keys(this.userInfo).length === 0) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}, 1500)
						return
					}

					// 设置默认值
					this.setDefaultValues()

					// 如果有ID，加载编辑数据
					if (options.id) {
						await this.loadEditData(options.id)
					}
				} catch (error) {
					console.error('页面初始化失败:', error)
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					})
				}
			},

			// 设置默认值
			setDefaultValues() {
				// 申请人：当前登录用户
				if (this.userInfo && this.userInfo.userId) {
					this.formData.applicationUserId = this.userInfo.userId
					this.formData.applicationUserName = this.userInfo.realName || this.userInfo.userName || '当前用户'
				}

				// 申请门店：当前登录用户的门店
				if (this.newuserInfo && this.newuserInfo.mdid) {
					this.formData.applicationStoreId = this.newuserInfo.mdid
					this.formData.applicationStoreName = this.newuserInfo.mdmc || '当前门店'
				} else if (this.userInfo && this.userInfo.mdid) {
					this.formData.applicationStoreId = this.userInfo.mdid
					this.formData.applicationStoreName = this.userInfo.mdmc || '当前门店'
				}

				// 申请时间：默认今日
				const today = new Date()
				today.setHours(0, 0, 0, 0)
				this.formData.applicationTime = today.getTime()
				this.formData.applicationTimeStr = today.toISOString().split('T')[0]
				
				// 初始化审批节点（仅新建时）
				if (!this.formData.id) {
					this.initNodes()
				}
			},
			
			// 初始化审批节点（新建时默认1个节点）
			initNodes() {
				this.formData.nodes = [
					{
						nodeOrder: 1,
						nodeName: '',
						approvalType: '',
						approverIds: '',
						approverNames: []
					}
				]
			},
			
			// 添加节点
			addNode() {
				if (this.formData.nodes.length >= 5) {
					uni.showToast({
						title: '最多只能添加5个节点',
						icon: 'none'
					})
					return
				}
				const nextOrder = this.formData.nodes.length + 1
				this.formData.nodes.push({
					nodeOrder: nextOrder,
					nodeName: '',
					approvalType: '',
					approverIds: '',
					approverNames: []
				})
			},
			
			// 删除节点
			removeNode(index) {
				if (this.formData.nodes.length <= 1) {
					uni.showToast({
						title: '至少需要1个节点',
						icon: 'none'
					})
					return
				}
				this.formData.nodes.splice(index, 1)
				// 重新排序
				this.formData.nodes.forEach((node, idx) => {
					node.nodeOrder = idx + 1
				})
			},
			
			// 打开用户选择弹窗
			openUserDialog(nodeIndex) {
				this.currentNodeIndex = nodeIndex
				this.showUserDialog = true
				const node = this.formData.nodes[nodeIndex]
				// 初始化已选中的用户ID
				if (node.approverIds) {
					const idsArray = typeof node.approverIds === 'string' 
						? node.approverIds.split(',').filter(id => id && id.trim())
						: (Array.isArray(node.approverIds) ? node.approverIds : [])
					this.tempSelectedUserIds = [...idsArray]
				} else {
					this.tempSelectedUserIds = []
				}
				this.userSearchKeyword = ''
				this.userQuery.currentPage = 1
				this.userList = []
				this.filteredUserList = []
				this.loadUsers()
			},
			
			// 关闭用户选择弹窗
			closeUserDialog() {
				this.showUserDialog = false
				this.currentNodeIndex = -1
				this.userSearchKeyword = ''
				this.tempSelectedUserIds = []
				// 清除搜索定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
					this.searchTimer = null
				}
			},
			
			// 加载用户列表
			async loadUsers() {
				try {
					this.userListLoading = true
					
					const params = {
						currentPage: this.userQuery.currentPage,
						pageSize: this.userQuery.pageSize
					}
					
					// 如果有搜索关键词，添加keyword参数
					if (this.userSearchKeyword && this.userSearchKeyword.trim()) {
						params.keyword = this.userSearchKeyword.trim()
					}
					
					const res = await oauthApi.getUserList(params)
					
					if (res.code === 200 && res.data) {
						const newList = res.data.list || []
						
						if (this.userQuery.currentPage === 1) {
							// 第一页，替换数据
							this.userList = newList
							this.filteredUserList = newList
						} else {
							// 后续页，追加数据
							this.userList = [...this.userList, ...newList]
							this.filteredUserList = [...this.filteredUserList, ...newList]
						}
						
						// 获取总数，优先使用pagination.Total，如果没有则使用当前列表长度
						const total = res.data.pagination && res.data.pagination.Total
						if (total !== undefined && total !== null) {
							this.userTotal = total
						} else {
							// 如果没有总数信息，根据当前页和返回数据判断
							if (newList.length < this.userQuery.pageSize) {
								// 返回的数据少于每页数量，说明是最后一页
								this.userTotal = this.filteredUserList.length + newList.length
							} else {
								// 可能还有更多数据，暂时设置为当前数量+1（表示可能还有）
								this.userTotal = this.filteredUserList.length + newList.length + 1
							}
						}
					} else {
						if (this.userQuery.currentPage === 1) {
							this.userList = []
							this.filteredUserList = []
						}
						this.userTotal = 0
					}
				} catch (error) {
					console.error('加载用户列表失败:', error)
					uni.showToast({
						title: '加载用户列表失败',
						icon: 'none'
					})
					if (this.userQuery.currentPage === 1) {
						this.userList = []
						this.filteredUserList = []
					}
					this.userTotal = 0
				} finally {
					this.userListLoading = false
				}
			},
			
			// 调用getUserInfoList API
			async loadUserInfoList(userIds) {
				const request = require('@/service/request.js').default
				const config = require('@/common/config.js').default
				try {
					return await request.post(`${config.getApiBaseUrl()}/api/permission/Users/getUserList`, {
						userId: userIds
					})
				} catch (error) {
					console.error('获取用户信息失败:', error)
					return { code: 500, data: { list: [] } }
				}
			},
			
			// 通过用户ID搜索用户
			async searchUserById() {
				if (!this.userSearchKeyword.trim()) {
					uni.showToast({
						title: '请输入用户ID',
						icon: 'none'
					})
					return
				}
				
				try {
					this.userListLoading = true
					const userIds = this.userSearchKeyword.split(',').map(id => id.trim()).filter(id => id)
					
					if (userIds.length === 0) {
						uni.showToast({
							title: '请输入有效的用户ID',
							icon: 'none'
						})
						return
					}
					
					const res = await this.loadUserInfoList(userIds)
					if (res.code === 200 && res.data && res.data.list) {
						// 合并到现有列表，去重
						const existingIds = new Set(this.userList.map(u => u.id))
						const newUsers = res.data.list.filter(u => !existingIds.has(u.id))
						this.userList = [...this.userList, ...newUsers]
						this.filteredUserList = this.userList
						this.userTotal = this.userList.length
						
						// 如果搜索的用户不在列表中，提示
						if (newUsers.length === 0 && res.data.list.length > 0) {
							uni.showToast({
								title: '用户已在列表中',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '未找到用户',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('搜索用户失败:', error)
					uni.showToast({
						title: '搜索用户失败',
						icon: 'none'
					})
				} finally {
					this.userListLoading = false
				}
			},
			
			// 加载更多用户
			loadMoreUsers() {
				if (this.userListLoading) return
				if (this.filteredUserList.length >= this.userTotal && this.userTotal > 0) {
					return
				}
				
				this.userQuery.currentPage++
				this.loadUsers()
			},
			
			// 搜索用户
			handleUserSearch() {
				// 防抖处理，延迟500ms后执行搜索
				clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					this.userQuery.currentPage = 1
					this.userList = []
					this.filteredUserList = []
					this.loadUsers()
				}, 500)
			},
			
			// 切换用户选择状态
			toggleUserSelection(user) {
				const index = this.tempSelectedUserIds.indexOf(user.id)
				if (index > -1) {
					this.tempSelectedUserIds.splice(index, 1)
				} else {
					this.tempSelectedUserIds.push(user.id)
				}
			},
			
			// 判断用户是否已选中
			isUserSelected(userId) {
				return this.tempSelectedUserIds.indexOf(userId) > -1
			},
			
			// 确认选择用户
			async confirmUserSelection() {
				if (this.currentNodeIndex < 0) return
				
				const node = this.formData.nodes[this.currentNodeIndex]
				
				// 保存选中的用户ID（逗号分隔的字符串）
				node.approverIds = this.tempSelectedUserIds.join(',')
				
				// 获取用户名列表
				if (this.tempSelectedUserIds.length > 0) {
					// 从已加载的用户列表中获取用户名
					const selectedUsers = this.userList.filter(user => 
						this.tempSelectedUserIds.indexOf(user.id) > -1
					)
					
					// 如果有些用户不在当前列表中，需要单独获取
					const missingIds = this.tempSelectedUserIds.filter(id => 
						!selectedUsers.find(u => u.id === id)
					)
					
					if (missingIds.length > 0) {
						try {
							const res = await this.loadUserInfoList(missingIds)
							if (res.code === 200 && res.data && res.data.list) {
								selectedUsers.push(...res.data.list)
							}
						} catch (error) {
							console.error('获取用户信息失败:', error)
						}
					}
					
					node.approverNames = selectedUsers.map(user => 
						user.fullName || user.realName || user.userName || user.id
					)
				} else {
					node.approverNames = []
				}
				
				this.closeUserDialog()
			},
			
			// 获取审批人显示文本
			getApproverDisplayText(node) {
				if (node.approverNames && node.approverNames.length > 0) {
					return `已选择 ${node.approverNames.length} 人`
				}
				return '请选择审批人'
			},

			// 申请时间变化
			onApplicationTimeChange(e) {
				this.formData.applicationTimeStr = e.detail.value
				const date = new Date(e.detail.value)
				date.setHours(0, 0, 0, 0)
				this.formData.applicationTime = date.getTime()
			},

			// 打开购买物品选择弹窗
			openPurchaseDialog() {
				this.showPurchaseDialog = true
				this.tempSelectedPurchaseIds = this.selectedPurchaseRecords.map(item => item.id)
				this.searchKeyword = ''
				this.purchaseQuery.currentPage = 1
				this.loadPurchaseRecords()
			},

			// 关闭购买物品选择弹窗
			closePurchaseDialog() {
				this.showPurchaseDialog = false
				this.searchKeyword = ''
			},

			// 加载购买记录（使用分页接口）
			async loadPurchaseRecords() {
				try {
					this.purchaseListLoading = true

					const params = {
						currentPage: this.purchaseQuery.currentPage,
						pageSize: this.purchaseQuery.pageSize,
						approveStatus: '未审批', // 只选择未审批的购买记录
						// createUserStoreId: this.formData.applicationStoreId || '暂无',
						createUser:this.newuserInfo&&this.newuserInfo.id?this.newuserInfo.id:'暂无',
					}
					
					if (this.searchKeyword) {
						params.reimbursementCategoryName = this.searchKeyword
					}

					const res = await purchaseApi.getPurchaseList(params)
					if (res.code === 200 && res.data) {
						const newList = res.data.list || []
						if (this.purchaseQuery.currentPage === 1) {
							// 第一页，替换数据
							this.purchaseList = newList
							this.filteredPurchaseList = newList
						} else {
							// 后续页，追加数据
							this.purchaseList = [...this.purchaseList, ...newList]
							this.filteredPurchaseList = [...this.filteredPurchaseList, ...newList]
						}
						this.purchaseTotal = (res.data.pagination && res.data.pagination.Total) || 0
					} else {
						if (this.purchaseQuery.currentPage === 1) {
							this.purchaseList = []
							this.filteredPurchaseList = []
						}
						this.purchaseTotal = 0
					}
				} catch (error) {
					console.error('加载购买记录失败:', error)
					uni.showToast({
						title: '加载购买记录失败',
						icon: 'none'
					})
					if (this.purchaseQuery.currentPage === 1) {
						this.purchaseList = []
						this.filteredPurchaseList = []
					}
					this.purchaseTotal = 0
				} finally {
					this.purchaseListLoading = false
				}
			},

			// 加载更多购买记录
			loadMorePurchaseRecords() {
				if (this.purchaseListLoading) return
				if (this.filteredPurchaseList.length >= this.purchaseTotal) return
				
				this.purchaseQuery.currentPage++
				this.loadPurchaseRecords()
			},

			// 搜索购买记录
			handleSearch() {
				this.purchaseQuery.currentPage = 1
				this.purchaseList = []
				this.filteredPurchaseList = []
				this.loadPurchaseRecords()
			},

			// 切换购买记录选择状态
			togglePurchaseSelection(item) {
				const index = this.tempSelectedPurchaseIds.indexOf(item.id)
				if (index > -1) {
					this.tempSelectedPurchaseIds.splice(index, 1)
				} else {
					this.tempSelectedPurchaseIds.push(item.id)
				}
			},

			// 判断购买记录是否已选中
			isPurchaseSelected(id) {
				return this.tempSelectedPurchaseIds.indexOf(id) > -1
			},

			// 确认选择购买物品
			confirmPurchaseSelection() {
				// 根据选中的ID找到对应的记录
				const selectedRecords = this.purchaseList.filter(item => 
					this.tempSelectedPurchaseIds.indexOf(item.id) > -1
				)

				// 去重：移除已存在的记录
				const existingIds = new Set(this.selectedPurchaseRecords.map(item => item.id))
				const newRecords = selectedRecords.filter(item => !existingIds.has(item.id)).map(record => {
					// 标记新增的记录
					record.isInitial = false
					return record
				})

				// 追加新选中的记录
				this.selectedPurchaseRecords = [...this.selectedPurchaseRecords, ...newRecords]

				// 更新ID列表
				this.formData.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id)

				// 自动计算总金额
				this.calculateTotalAmount()

				this.closePurchaseDialog()
			},

			// 移除已选中的购买记录
			removePurchaseRecord(index) {
				const record = this.selectedPurchaseRecords[index]
				// 检查是否是初始记录，初始记录不允许移除（编辑时）
				if (record && record.isInitial) {
					uni.showToast({
						title: '初始购买记录不能移除',
						icon: 'none'
					})
					return
				}
				this.selectedPurchaseRecords.splice(index, 1)
				this.formData.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id)
				this.calculateTotalAmount()
			},

			// 计算总金额
			calculateTotalAmount() {
				const totalAmount = this.selectedPurchaseRecords.reduce((sum, item) => {
					return sum + (parseFloat(item.amount) || 0)
				}, 0)
				this.formData.amount = totalAmount.toFixed(2)
			},

			// 加载编辑数据
			async loadEditData(id) {
				try {
					uni.showLoading({
						title: '加载中...'
					})

					const res = await api.getReimbursementDetail(id)
					
					if (res.code === 200 && res.data) {
						const data = res.data
						const formData = data.form || data
						const purchaseRecords = data.purchaseRecords || []
						
						this.formData = {
							id: formData.id,
							applicationUserId: formData.applicationUserId,
							applicationUserName: formData.applicationUserName,
							applicationStoreId: formData.applicationStoreId,
							applicationStoreName: formData.applicationStoreName,
							applicationTime: formData.applicationTime,
							applicationTimeStr: formData.applicationTime ? new Date(formData.applicationTime).toISOString().split('T')[0] : undefined,
							amount: formData.amount,
							approveStatus: formData.approveStatus || formData.approvalStatus || '待审批',
							selectedPurchaseRecordIds: [],
							nodes: [] // 编辑时不需要节点配置
						}

						// 保存初始的购买记录ID列表
						this.initialPurchaseRecordIds = purchaseRecords.map(record => record.id)
						
						// 填充购买记录列表，标记初始记录
						this.selectedPurchaseRecords = purchaseRecords.map(record => {
							// 处理附件字段
							if (record.attachment) {
								try {
									record.attachment = typeof record.attachment === 'string' 
										? JSON.parse(record.attachment) 
										: record.attachment
								} catch (e) {
									record.attachment = []
								}
							} else {
								record.attachment = []
							}
							// 标记为初始记录
							record.isInitial = true
							return record
						})
						
						this.formData.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id)
						
						// 计算总金额
						this.calculateTotalAmount()
					} else {
						throw new Error(res.message || '加载数据失败')
					}
				} catch (error) {
					console.error('加载编辑数据失败:', error)
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},


			// 表单提交
			async handleFormSubmit() {
				// 验证必填项
				if (!this.formData.selectedPurchaseRecordIds || this.formData.selectedPurchaseRecordIds.length === 0) {
					uni.showToast({
						title: '请至少选择一条购买记录',
						icon: 'none'
					})
					return
				}

				// 新建时验证节点配置
				if (!this.formData.id) {
					if (!this.formData.nodes || this.formData.nodes.length < 1 || this.formData.nodes.length > 5) {
						uni.showToast({
							title: '审批节点数量必须在1-5个之间',
							icon: 'none'
						})
						return
					}
					
					// 验证每个节点
					for (let i = 0; i < this.formData.nodes.length; i++) {
						const node = this.formData.nodes[i]
						if (!node.nodeName) {
							uni.showToast({
								title: `请填写节点${node.nodeOrder}的名称`,
								icon: 'none'
							})
							return
						}
						if (!node.approvalType) {
							uni.showToast({
								title: `请选择节点${node.nodeOrder}的审批类型`,
								icon: 'none'
							})
							return
						}
						// 验证审批人
						let approverIdsArray = []
						if (node.approverIds) {
							if (Array.isArray(node.approverIds)) {
								approverIdsArray = node.approverIds.filter(id => id)
							} else if (typeof node.approverIds === 'string') {
								approverIdsArray = node.approverIds.split(',').filter(id => id && id.trim())
							}
						}
						if (approverIdsArray.length === 0) {
							uni.showToast({
								title: `请为节点${node.nodeOrder}选择至少一个审批人`,
								icon: 'none'
							})
							return
						}
					}
				}

				if (this.isSubmitting) return

				try {
					this.isSubmitting = true
					uni.showLoading({
						title: '提交中...'
					})

					let submitData = {}
					
					if (this.formData.id) {
						// 更新：只传递有值的字段
						submitData = {
							id: this.formData.id
						}
						if (this.formData.applicationUserId) {
							submitData.applicationUserId = this.formData.applicationUserId
						}
						if (this.formData.applicationUserName) {
							submitData.applicationUserName = this.formData.applicationUserName
						}
						if (this.formData.applicationStoreId) {
							submitData.applicationStoreId = this.formData.applicationStoreId
						}
						if (this.formData.applicationTime) {
							submitData.applicationTime = this.formData.applicationTime
						}
						if (this.formData.amount) {
							submitData.amount = this.formData.amount
						}
						if (this.formData.selectedPurchaseRecordIds && this.formData.selectedPurchaseRecordIds.length > 0) {
							submitData.selectedPurchaseRecordIds = this.formData.selectedPurchaseRecordIds
						}
						
						const res = await api.updateReimbursement(this.formData.id, submitData)
						
						if (res.code === 200) {
							uni.showToast({
								title: '修改成功',
								icon: 'success'
							})
							
							// 修改成功后，自动重新提交审批
							try {
								const submitRes = await api.submitApproval(this.formData.id)
								if (submitRes.code === 200) {
									uni.showToast({
										title: '已重新提交审批',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: '修改成功，但重新提交审批失败',
										icon: 'none'
									})
								}
							} catch (error) {
								console.error('重新提交审批失败:', error)
								uni.showToast({
									title: '修改成功，但重新提交审批失败，请手动提交',
									icon: 'none'
								})
							}
							
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} else {
							throw new Error(res.message || '修改失败')
						}
					} else {
						// 创建
						submitData = {
							applicationUserId: this.formData.applicationUserId,
							applicationUserName: this.formData.applicationUserName,
							applicationStoreId: this.formData.applicationStoreId,
							applicationTime: this.formData.applicationTime,
							amount: this.formData.amount,
							selectedPurchaseRecordIds: this.formData.selectedPurchaseRecordIds,
							nodes: this.formData.nodes.map(node => {
								// 转换审批人ID为数组
								let approverIds = []
								if (node.approverIds) {
									if (Array.isArray(node.approverIds)) {
										approverIds = node.approverIds.filter(id => id)
									} else if (typeof node.approverIds === 'string') {
										approverIds = node.approverIds.split(',').filter(id => id && id.trim())
									}
								}
								
								return {
									nodeOrder: node.nodeOrder,
									nodeName: node.nodeName,
									approvalType: node.approvalType,
									approverIds: approverIds,
									approverNames: node.approverNames && node.approverNames.length > 0 
										? node.approverNames 
										: approverIds
								}
							})
						}
						
						const res = await api.createReimbursement(submitData)
						
						if (res.code === 200) {
							uni.showToast({
								title: '创建成功',
								icon: 'success'
							})
							
							// 创建成功后，自动提交审批
							let applicationId = null
							if (res.data) {
								if (typeof res.data === 'object' && res.data.id) {
									applicationId = res.data.id
								} else if (typeof res.data === 'string') {
									applicationId = res.data
								} else {
									applicationId = String(res.data)
								}
							}
							
							if (applicationId) {
								try {
									const submitRes = await api.submitApproval(applicationId)
									if (submitRes.code === 200) {
										uni.showToast({
											title: '已自动提交审批',
											icon: 'success'
										})
									} else {
										uni.showToast({
											title: '创建成功，但提交审批失败',
											icon: 'none'
										})
									}
								} catch (error) {
									console.error('提交审批失败:', error)
									uni.showToast({
										title: '创建成功，但提交审批失败，请手动提交',
										icon: 'none'
									})
								}
							} else {
								uni.showToast({
									title: '创建成功，但无法获取申请ID，请手动提交审批',
									icon: 'none'
								})
							}
							
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} else {
							throw new Error(res.message || '创建失败')
						}
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({
						title: error.message || '提交失败，请重试',
						icon: 'none'
					})
				} finally {
					this.isSubmitting = false
					uni.hideLoading()
				}
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '无'
				const date = new Date(timestamp)
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 40rpx;
		box-sizing: border-box;
	}

	.form-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		overflow: hidden;
	}

	.form-content {
		padding: 40rpx;
	}

	.form-group {
		margin-bottom: 32rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
		margin-bottom: 16rpx;
	}

	.input-wrapper {
		width: 100%;
	}

	.select-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
	}

	.custom-select {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
		min-height: 80rpx;
		box-sizing: border-box;
	}

	.select-text {
		font-size: 28rpx;
		color: #2e7d32;
		flex: 1;
	}

	.select-arrow {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.purchase-select-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
		padding: 24rpx;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		border-radius: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(67, 233, 123, 0.3);
	}

	.btn-icon {
		font-size: 32rpx;
		color: #fff;
	}

	.btn-text {
		font-size: 28rpx;
		color: #fff;
		font-weight: 600;
	}

	.selected-count {
		display: block;
		margin-top: 16rpx;
		font-size: 24rpx;
		color: #6a9c6a;
		text-align: center;
	}

	.purchase-list {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.purchase-item {
		background: #f9fff9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		padding: 24rpx;
	}

	.purchase-item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
	}

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

	.initial-mark {
		font-size: 22rpx;
		color: #909399;
		padding: 4rpx 12rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
	}

	.purchase-category {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.purchase-remove {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #ffebee;
		border-radius: 50%;
	}

	.remove-icon {
		font-size: 24rpx;
		color: #c62828;
		font-weight: 600;
	}

	.purchase-item-details {
		display: flex;
		gap: 24rpx;
		margin-bottom: 12rpx;
	}

	.purchase-detail {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.purchase-detail.amount {
		color: #f57c00;
		font-weight: 600;
	}

	.purchase-item-time {
		font-size: 22rpx;
		color: #909399;
	}

	.purchase-time {
		font-size: 22rpx;
		color: #909399;
	}

	.btn-group {
		margin-top: 48rpx;
	}

	.btn {
		width: 100%;
		padding: 32rpx;
		border-radius: 48rpx;
		font-size: 32rpx;
		font-weight: 600;
		letter-spacing: 2rpx;
		border: none;
	}

	.btn-primary {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 8rpx 24rpx rgba(67, 233, 123, 0.3);
		padding: 0;
	}

	.btn-primary:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 12rpx rgba(67, 233, 123, 0.4);
	}

	/* 弹窗样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.modal-content {
		width: 90%;
		max-height: 80vh;
		background: #fff;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
	}

	.modal-title {
		font-size: 32rpx;
		color: #fff;
		font-weight: 600;
	}

	.modal-close {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(255, 255, 255, 0.3);
		border-radius: 50%;
	}

	.close-icon {
		font-size: 28rpx;
		color: #fff;
		font-weight: 600;
	}

	.modal-body {
		flex: 1;
		padding: 32rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.search-box {
		margin-bottom: 24rpx;
	}

	.search-input {
		background: #f5f5f5;
		border-radius: 16rpx;
	}

	.purchase-dialog-list {
		flex: 1;
		max-height: 600rpx;
	}

	.loading-text,
	.empty-text {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #909399;
		font-size: 28rpx;
	}

	.purchase-dialog-item {
		background: #f9fff9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;
		transition: all 0.2s ease;
	}

	.purchase-dialog-item.selected {
		background: #e8f5e9;
		border-color: #43e97b;
	}

	.purchase-dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.purchase-dialog-category {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.selected-mark {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #43e97b;
		border-radius: 50%;
		color: #fff;
		font-size: 24rpx;
		font-weight: 600;
	}

	.purchase-dialog-details {
		display: flex;
		gap: 24rpx;
		margin-bottom: 12rpx;
	}

	.purchase-dialog-detail {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.purchase-dialog-detail.amount {
		color: #f57c00;
		font-weight: 600;
	}

	.purchase-dialog-time {
		font-size: 22rpx;
		color: #909399;
	}

	.modal-footer {
		display: flex;
		gap: 24rpx;
		padding: 32rpx;
		border-top: 2rpx solid #f0f0f0;
	}

	.modal-btn {
		flex: 1;
		padding:15rpx 24rpx;
		border-radius: 24rpx;
		font-size: 28rpx;
		font-weight: 600;
		border: none;
	}

	.cancel-btn {
		background: #f5f5f5;
		color: #909399;
	}

	.confirm-btn {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
	}

	/* 审批节点配置样式 */
	.nodes-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.add-node-btn {
		padding: 12rpx 24rpx;
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		border-radius: 16rpx;
	}

	.add-node-text {
		font-size: 24rpx;
		color: #fff;
		font-weight: 600;
	}

	.nodes-list {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.node-item {
		background: #f9fff9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		padding: 24rpx;
	}

	.node-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #e0e0e0;
	}

	.node-order {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.remove-node-btn {
		padding: 8rpx 16rpx;
		background: #ffebee;
		border-radius: 8rpx;
	}

	.remove-node-text {
		font-size: 24rpx;
		color: #c62828;
		font-weight: 500;
	}

	.node-form {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.node-form-item {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.node-label {
		font-size: 26rpx;
		color: #2e7d32;
		font-weight: 500;
	}

	.node-input {
		background: #fff;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		padding: 20rpx 24rpx;
	}

	.node-tip {
		font-size: 22rpx;
		color: #909399;
		margin-top: -8rpx;
	}

	.loading-more {
		text-align: center;
		padding: 32rpx;
		color: #909399;
		font-size: 24rpx;
	}

	.no-more {
		text-align: center;
		padding: 32rpx;
		color: #909399;
		font-size: 24rpx;
	}

	.pagination-info {
		text-align: center;
		padding: 24rpx;
		color: #6a9c6a;
		font-size: 22rpx;
		background: #f9fff9;
		border-top: 2rpx solid #e0e0e0;
	}

	/* 审批人选择相关样式 */
	.approver-select-wrapper {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.approver-select-btn {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
		min-height: 80rpx;
		box-sizing: border-box;
	}

	.approver-btn-text {
		font-size: 28rpx;
		color: #2e7d32;
		flex: 1;
	}

	.approver-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
	}

	.approver-tag {
		display: inline-block;
		padding: 8rpx 16rpx;
		background: #e8f5e9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		font-size: 24rpx;
		color: #2e7d32;
	}

	/* 用户选择弹窗样式 */
	.user-dialog-list {
		flex: 1;
		max-height: 600rpx;
	}

	.user-dialog-item {
		background: #f9fff9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 16rpx;
		transition: all 0.2s ease;
	}

	.user-dialog-item.selected {
		background: #e8f5e9;
		border-color: #43e97b;
	}

	.user-dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.user-dialog-name {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 600;
	}

	.user-dialog-details {
		display: flex;
		gap: 24rpx;
	}

	.user-dialog-detail {
		font-size: 24rpx;
		color: #6a9c6a;
	}
</style>

