<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-remove" @tap="removePurchaseRecord(index)">
										<text class="remove-icon">✕</text>
									</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="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" class="loading-text">加载中...</view>
						<view v-else-if="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>
					</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>
</template>

<script>
	import api from '@/apis/index.js'
	import purchaseApi from '@/apis/modules/purchase.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: []
				},
				selectedPurchaseRecords: [],
				// 购买物品选择弹窗相关
				showPurchaseDialog: false,
				purchaseList: [],
				filteredPurchaseList: [],
				purchaseListLoading: false,
				tempSelectedPurchaseIds: [],
				searchKeyword: '',
				userInfo: null,
				newuserInfo: 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]
			},

			// 申请时间变化
			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.loadPurchaseRecords()
			},

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

			// 加载购买记录（未报销的）
			async loadPurchaseRecords() {
				try {
					this.purchaseListLoading = true

					const params = {
						createUser:this.newuserInfo&&this.newuserInfo.id?this.newuserInfo.id:'暂无',
						// createUserStoreId: this.formData.applicationStoreId || '暂无',
						approveStatus: '未审批'
					}

					const res = await api.getUnreimbursedPurchaseList(params)
					console.error(res)
					if (res.code === 200 && res.data) {
						// 过滤出未报销的记录（ApplicationId为空或未关联）
						// this.purchaseList = (res.data || []).filter(item => !item.applicationId)
						this.purchaseList = res.data || []
						this.filteredPurchaseList = this.purchaseList
					} else {
						this.purchaseList = []
						this.filteredPurchaseList = []
					}
					console.error(this.purchaseList)
				} catch (error) {
					console.error('加载购买记录失败:', error)
					uni.showToast({
						title: '加载购买记录失败',
						icon: 'none'
					})
					this.purchaseList = []
					this.filteredPurchaseList = []
				} finally {
					this.purchaseListLoading = false
				}
			},

			// 加载更多购买记录（如果需要分页）
			loadMorePurchaseRecords() {
				// 当前使用不分页接口，暂不需要
			},

			// 搜索购买记录
			handleSearch() {
				if (!this.searchKeyword.trim()) {
					this.filteredPurchaseList = this.purchaseList
					return
				}
				const keyword = this.searchKeyword.toLowerCase()
				this.filteredPurchaseList = this.purchaseList.filter(item => {
					const categoryName = (item.reimbursementCategoryName || '').toLowerCase()
					return categoryName.includes(keyword)
				})
			},

			// 切换购买记录选择状态
			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))

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

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

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

				this.closePurchaseDialog()
			},

			// 移除已选中的购买记录
			removePurchaseRecord(index) {
				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
						this.formData = {
							id: data.id,
							applicationUserId: data.applicationUserId,
							applicationUserName: data.applicationUserName,
							applicationStoreId: data.applicationStoreId,
							applicationStoreName: data.applicationStoreName,
							applicationTime: data.applicationTime,
							applicationTimeStr: data.applicationTime ? new Date(data.applicationTime).toISOString().split('T')[0] : undefined,
							amount: data.amount,
							approveStatus: data.approveStatus || '未审批',
							selectedPurchaseRecordIds: []
						}

						// 加载已关联的购买记录
						if (data.purchaseRecordsId) {
							await this.loadSelectedPurchaseRecords(data.purchaseRecordsId)
						}
					} else {
						throw new Error(res.message || '加载数据失败')
					}
				} catch (error) {
					console.error('加载编辑数据失败:', error)
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 加载已选中的购买记录（编辑时使用）
			async loadSelectedPurchaseRecords(purchaseRecordsId) {
				if (!purchaseRecordsId) {
					this.selectedPurchaseRecords = []
					this.formData.selectedPurchaseRecordIds = []
					return
				}

				// 处理逗号分隔的ID字符串
				const normalizedStr = purchaseRecordsId.toString().replace(/[\r\n]+/g, ',').replace(/\s+/g, '')
				const ids = normalizedStr.split(',').map(id => id.trim()).filter(id => id && id !== '')

				if (ids.length === 0) {
					this.selectedPurchaseRecords = []
					this.formData.selectedPurchaseRecordIds = []
					return
				}

				try {
					// 批量加载购买记录
					const promises = ids.map(id => {
						return purchaseApi.getPurchaseDetail(id)
							.then(res => res.code === 200 ? res.data : null)
							.catch(() => null)
					})

					const results = await Promise.all(promises)
					this.selectedPurchaseRecords = results.filter(item => item !== null)
					this.formData.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id)

					// 计算总金额
					this.calculateTotalAmount()
				} catch (error) {
					console.error('加载购买记录失败:', error)
					uni.showToast({
						title: '加载购买记录失败',
						icon: 'none'
					})
				}
			},

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

				if (this.isSubmitting) return

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

					// 设置关联购买编号（多个ID用逗号分隔）
					const submitData = {
						...this.formData,
						purchaseRecordsId: this.formData.selectedPurchaseRecordIds.join(',')
					}

					let res
					if (this.formData.id) {
						// 更新
						res = await api.updateReimbursement(this.formData.id, submitData)
					} else {
						// 创建
						res = await api.createReimbursement(submitData)
					}

					if (res.code === 200) {
						uni.showToast({
							title: res.message || '操作成功',
							icon: 'success'
						})
						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-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;
	}
</style>

