<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">
							<view class="custom-select" :class="{ 'readonly': isDetail }" @tap="isDetail ? null : openSelectModal('category')">
								<text class="select-text">{{ formData.reimbursementCategoryName || '请选择分类' }}</text>
								<text v-if="!isDetail" class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 单价 -->
					<view class="form-group">
						<text class="form-label">单价</text>
						<view class="input-wrapper">
							<u-input v-model="formData.unitPrice" placeholder="请输入单价" type="digit" 
								:readonly="isDetail"
								@input="calculateAmount" class="select-input" />
						</view>
					</view>

					<!-- 数量 -->
					<view class="form-group">
						<text class="form-label">数量</text>
						<view class="input-wrapper">
							<u-input v-model="formData.quantity" placeholder="请输入数量" type="number" 
								:readonly="isDetail"
								@input="calculateAmount" class="select-input" />
						</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">
							<textarea v-model="formData.memo" placeholder="请输入备注说明" :maxlength="500" 
								:disabled="isDetail"
								:count="true" class="textarea-input" />
						</view>
					</view>

					<!-- 附件 -->
					<view class="form-group">
						<text class="form-label">附件</text>
						<view class="input-wrapper">
							<view class="file-upload-area" :class="{ 'readonly': isDetail }" @tap.stop="handleChooseFile">
								<view v-if="!isDetail" class="file-upload-text">
									<text class="file-upload-icon">📁</text>
									<text>点击选择文件（最多9个）</text>
								</view>
								<view class="file-list">
									<view v-for="(file, index) in formData.attachment" :key="file.id || index" class="file-item">
										<view class="file-info">
											<text class="file-icon">🖼️</text>
											<text class="file-name">{{ file.name || file.url || '文件' }}</text>
										</view>
										<view class="file-actions">
											<button v-if="file.url && !isDetail" type="error" size="mini" @click.stop="removeFile(index)">
												删除
											</button>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 购买时间 -->
					<view class="form-group">
						<text class="form-label">购买时间</text>
						<view class="input-wrapper">
							<picker mode="date" :value="formData.purchaseTimeStr" :disabled="isDetail" @change="onPurchaseTimeChange">
								<view class="custom-select" :class="{ 'readonly': isDetail }">
									<text class="select-text">{{ formData.purchaseTimeStr || '请选择购买时间' }}</text>
									<text v-if="!isDetail" 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.createUserName" 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.createUserStoreName" placeholder="自动填充" readonly 
								class="select-input" />
						</view>
					</view> -->

					<!-- 提交按钮 -->
					<view class="btn-group" v-if="!isDetail">
						<button type="submit" class="btn btn-primary" 
							:style="{opacity: isSubmitting ? 0.5 : 1}" 
							@tap="isSubmitting ? null : handleFormSubmit()">
							{{ isSubmitting ? '提交中...' : (formData.id ? '更新' : '提交') }}
						</button>
					</view>
					<!-- 查看模式返回按钮 -->
					<view class="btn-group" v-else>
						<button type="button" class="btn btn-back" @tap="goBack">
							返回
						</button>
					</view>
				</form>
			</view>
		</view>

		<!-- 选择弹窗 -->
		<SearchSelectModal 
			:show="showModal" 
			:title="modalTitle" 
			:options="currentOptions" 
			:loading="modalLoading"
			:has-more="hasMoreData" 
			:search-param="searchParam" 
			@confirm="handleModalConfirm" 
			@close="closeModal"
			@load-more="handleLoadMore" 
			@refresh="handleRefresh" 
			@search="handleSearch" />
	</view>
</template>

<script>
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	import purchaseApi from '@/apis/modules/purchase.js'
	import lxApi from '@/apis/modules/lx.js'

	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				isSubmitting: false,
				formData: {
					id: undefined,
					reimbursementCategoryId: undefined,
					reimbursementCategoryName: undefined,
					unitPrice: undefined,
					quantity: undefined,
					amount: undefined,
					memo: undefined,
					attachment: [],
					purchaseTime: undefined,
					purchaseTimeStr: undefined,
					createTime: undefined,
					createUser: undefined,
					createUserName: undefined,
					createUserStoreId: undefined,
					createUserStoreName: undefined,
					approveStatus: '未审批'
				},
				// 选择弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',
				// 用户信息
				userInfo: null,
				newuserInfo: null,
				isDetail: false // 是否为查看模式
			}
		},

		onLoad(options) {
			this.isDetail = options.isDetail === 'true' || options.isDetail === true
			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.createUser = this.userInfo.userId
					this.formData.createUserName = this.userInfo.realName || this.userInfo.userName || '当前用户'
				}

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

				// 购买时间：默认今日
				const today = new Date()
				today.setHours(0, 0, 0, 0)
				this.formData.purchaseTime = today.getTime()
				this.formData.purchaseTimeStr = today.toISOString().split('T')[0]

				// 创建时间：当前时间
				this.formData.createTime = new Date().getTime()

				// 审批状态：默认"未审批"
				this.formData.approveStatus = '未审批'
			},

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

					const res = await purchaseApi.getPurchaseDetail(id)
					
					if (res.code === 200 && res.data) {
						const data = res.data
						this.formData = {
							id: data.id,
							reimbursementCategoryId: data.reimbursementCategoryId,
							reimbursementCategoryName: data.reimbursementCategoryName,
							unitPrice: data.unitPrice,
							quantity: data.quantity,
							amount: data.amount,
							memo: data.memo,
							attachment: data.attachment || [],
							purchaseTime: data.purchaseTime,
							purchaseTimeStr: data.purchaseTime ? new Date(data.purchaseTime).toISOString().split('T')[0] : undefined,
							createTime: data.createTime,
							createUser: data.createUser,
							createUserName: data.createUserName || '当前用户',
							createUserStoreId: data.createUserStoreId,
							createUserStoreName: data.createUserStoreName || '当前门店',
							approveStatus: data.approveStatus || '未审批'
						}

						// 如果有已选择的分类，加载对应的选项
						// if (this.formData.reimbursementCategoryId) {
						// 	await this.loadCategoryOption(this.formData.reimbursementCategoryId)
						// }
					} else {
						throw new Error(res.message || '加载数据失败')
					}
				} catch (error) {
					console.error('加载编辑数据失败:', error)
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 打开选择弹窗
			async openSelectModal(fieldId) {
				this.currentSelectField = fieldId
				this.showModal = true
				this.modalTitle = '加载中...'
				this.modalLoading = true
				this.currentPage = 1
				this.hasMoreData = true
				this.searchKeyword = ''
				this.currentOptions = []

				try {
					if (fieldId === 'category') {
						this.searchParam = 'level1Name'
						this.modalTitle = '选择分类'
					}

					await this.loadOptionsData(fieldId, 1)
				} catch (error) {
					console.error('获取选项数据失败:', error)
					this.modalTitle = '加载失败'
					this.currentOptions = []
					uni.showToast({
						title: '数据加载失败，请检查网络连接',
						icon: 'none'
					})
				} finally {
					this.modalLoading = false
				}
			},

			// 关闭弹窗
			closeModal() {
				this.showModal = false
				this.currentSelectField = ''
				this.currentOptions = []
				this.modalLoading = false
				this.hasMoreData = true
				this.currentPage = 1
				this.searchKeyword = ''
			},

			// 加载选项数据
			async loadOptionsData(fieldId, page = 1, searchKeyword = '') {
				let options = []

				try {
					if (fieldId === 'category') {
						// 加载报销分类列表
						const params = {}
						if (searchKeyword) {
							// 支持按一级名称、二级名称或二级编号搜索
							params.level1Name = searchKeyword
						}

						const res = await purchaseApi.getReimbursementCategoryList(params)
						
						if (res.code === 200 && res.data) {
							options = res.data.map(item => ({
								value: item.id,
								label: `${item.level1Name || ''} - ${item.typeName || ''}`,
								subtitle: `编号: ${item.level2Code || ''}`,
								level1Name: item.level1Name,
								typeName: item.typeName,
								level2Code: item.level2Code
							}))
						}
					}

					if (page === 1) {
						this.currentOptions = options
					} else {
						this.currentOptions = [...this.currentOptions, ...options]
					}

					this.hasMoreData = options.length === this.pageSize
				} catch (error) {
					console.error('加载选项数据失败:', error)
					this.currentOptions = []
				}
			},

			// 处理弹窗确认
			handleModalConfirm(item) {
				console.log(item)
				if (this.currentSelectField === 'category') {
					this.formData.reimbursementCategoryId = item.value
					this.formData.reimbursementCategoryName = item.typeName
				}
				this.closeModal()
			},

			// 处理加载更多
			async handleLoadMore() {
				if (!this.hasMoreData || this.modalLoading) return
				this.currentPage++
				await this.loadOptionsData(this.currentSelectField, this.currentPage, this.searchKeyword)
			},

			// 处理刷新
			async handleRefresh() {
				this.currentPage = 1
				this.hasMoreData = true
				await this.loadOptionsData(this.currentSelectField, 1, this.searchKeyword)
			},

			// 处理搜索
			async handleSearch(keyword) {
				this.searchKeyword = keyword
				this.currentPage = 1
				this.hasMoreData = true
				await this.loadOptionsData(this.currentSelectField, 1, keyword)
			},

			// 加载已选择的分类选项（用于编辑时显示）
			async loadCategoryOption(categoryId) {
				try {
					const res = await purchaseApi.getReimbursementCategoryList({
						id: categoryId
					})
					if (res.code === 200 && res.data && res.data.length > 0) {
						const item = res.data[0]
						this.formData.reimbursementCategoryName = `${item.level1Name || ''} - ${item.typeName || ''}`
					}
				} catch (error) {
					console.error('加载分类选项失败:', error)
				}
			},

			// 自动计算总金额
			calculateAmount() {
				const unitPrice = parseFloat(this.formData.unitPrice) || 0
				const quantity = parseFloat(this.formData.quantity) || 0
				this.formData.amount = (unitPrice * quantity).toFixed(2)
			},

			// 购买时间变化
			onPurchaseTimeChange(e) {
				this.formData.purchaseTimeStr = e.detail.value
				const date = new Date(e.detail.value)
				date.setHours(0, 0, 0, 0)
				this.formData.purchaseTime = date.getTime()
			},

			// 处理文件选择点击
			handleChooseFile() {
				if (this.isDetail) {
					return
				}
				this.chooseFile()
			},

			// 选择文件
			chooseFile() {
				const maxCount = 9 - (this.formData.attachment || []).length
				if (maxCount <= 0) {
					uni.showToast({
						title: '最多只能上传9个文件',
						icon: 'none'
					})
					return
				}
				
				uni.chooseImage({
					count: maxCount,
					type: 'file',
					success: (res) => {
						if (res.tempFiles && res.tempFiles.length > 0) {
							this.handleFileSelect(res.tempFiles)
						}
					},
					fail: (err) => {
						console.error('选择文件失败:', err)
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						})
					}
				})
			},

			// 处理文件选择
			async handleFileSelect(files) {
				for (let i = 0; i < files.length; i++) {
					const file = files[i]

					// 验证文件大小 (限制为5MB)
					if (file.size > 5 * 1024 * 1024) {
						uni.showToast({
							title: `文件大小超过5MB限制`,
							icon: 'none'
						})
						continue
					}

					// 上传文件
					await this.uploadSingleFile(file)
				}
			},

			// 上传单个文件
			async uploadSingleFile(file) {
				try {
					const result = await lxApi.uploadFile(file)

					if (result.code === 200 && result.data) {
						// 添加到附件列表
						if (!this.formData.attachment) {
							this.formData.attachment = []
						}
						this.formData.attachment.push({
							name: file.name || '文件',
							url: result.data.url || result.data.name,
							fileId: result.data.name
						})

						uni.showToast({
							title: '文件上传成功',
							icon: 'success'
						})
					} else {
						throw new Error(result.msg || '上传失败')
					}
				} catch (error) {
					console.error('文件上传失败:', error)
					uni.showToast({
						title: `文件上传失败`,
						icon: 'none'
					})
				}
			},

			// 删除文件
			removeFile(index) {
				this.formData.attachment.splice(index, 1)
			},

			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 表单提交
			async handleFormSubmit() {
				// 验证必填项
				if (!this.formData.reimbursementCategoryId) {
					uni.showToast({
						title: '请选择分类',
						icon: 'none'
					})
					return
				}

				if (!this.formData.unitPrice || parseFloat(this.formData.unitPrice) <= 0) {
					uni.showToast({
						title: '请输入有效的单价',
						icon: 'none'
					})
					return
				}

				if (!this.formData.quantity || parseFloat(this.formData.quantity) <= 0) {
					uni.showToast({
						title: '请输入有效的数量',
						icon: 'none'
					})
					return
				}

				this.isSubmitting = true

				try {
					uni.showLoading({
						title: '提交中...'
					})

					// 准备提交数据
					const submitData = {
						...this.formData
					}

					// 移除不需要的字段
					delete submitData.purchaseTimeStr
					delete submitData.createUserName
					delete submitData.createUserStoreName

					let res
					if (this.formData.id) {
						// 更新
						res = await purchaseApi.updatePurchase(this.formData.id, submitData)
					} else {
						// 创建
						res = await purchaseApi.createPurchase(submitData)
					}

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

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

	.input-wrapper {
		width: 100%;
	}

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

	.custom-select.readonly {
		background: #f5f5f5;
		border-color: #e0e0e0;
		opacity: 0.8;
	}

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

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

	.select-input {
		width: 100%;
		box-sizing: border-box;
	}

	.textarea-input {
		width: 100%;
		min-height: 200rpx;
		padding: 24rpx;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
		box-sizing: border-box;
	}

	.file-upload-area {
		background: #f9fff9;
		border: 3rpx dashed #c8e6c9;
		border-radius: 24rpx;
		padding: 32rpx;
	}

	.file-upload-area.readonly {
		background: #f5f5f5;
		border-color: #e0e0e0;
		opacity: 0.8;
	}

	.file-upload-text {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #6a9c6a;
		font-size: 28rpx;
		margin-bottom: 24rpx;
	}

	.file-upload-icon {
		font-size: 32rpx;
		margin-right: 12rpx;
	}

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

	.file-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		border: 2rpx solid #e0e0e0;
		border-radius: 16rpx;
		padding: 20rpx;
	}

	.file-info {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.file-icon {
		font-size: 32rpx;
		margin-right: 16rpx;
	}

	.file-name {
		font-size: 26rpx;
		color: #555;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.file-actions {
		display: flex;
		align-items: center;
	}

	.btn-group {
		margin-top: 60rpx;
		padding-bottom: 40rpx;
	}

	.btn {
		width: 100%;
		height: 88rpx;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 600;
		letter-spacing: 4rpx;
		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);
	}

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

	.btn-back {
		background: linear-gradient(135deg, #90a4ae 0%, #78909c 100%);
		color: #fff;
		box-shadow: 0 8rpx 24rpx rgba(144, 164, 174, 0.3);
	}

	.btn-back:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 12rpx rgba(144, 164, 174, 0.4);
	}
</style>

