<template>
	<view class="form-container">
		<view class="form-card">
			<view class="form-content">
				<!-- 审批信息 -->
				<view class="approval-section">
					<view class="section-title">审批信息</view>
					
					<!-- 审批人 -->
					<view class="form-group">
						<text class="form-label">审批人</text>
						<view class="input-wrapper">
							<view class="custom-select" @tap="openSelectModal('approver', -1)">
								<text class="select-text">{{ approverName || '请选择审批人（主管）' }}</text>
								<text class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 申请门店 -->
					<view class="form-group">
						<text class="form-label">申请门店</text>
						<view class="input-wrapper">
							<view class="custom-select" @tap="openSelectModal('applicationStore', -1)">
								<text class="select-text">{{ applicationStoreName || '请选择申请门店' }}</text>
								<text class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 备注 -->
					<view class="form-group">
						<text class="form-label">备注</text>
						<view class="input-wrapper">
							<textarea v-model="remarks" placeholder="请输入备注（可选）" 
								:maxlength="500" class="textarea-input" />
						</view>
					</view>
				</view>

				<!-- 分隔线 -->
				<view class="divider"></view>

				<!-- 使用记录列表 -->
				<view v-for="(item, index) in usageItems" :key="index" class="usage-item-card">
					<view class="item-header">
						<text class="item-title">使用记录 {{ index + 1 }}</text>
						<view v-if="usageItems.length > 1" class="delete-btn" @click="removeItem(index)">
							<text class="delete-icon">🗑️</text>
						</view>
					</view>

					<!-- 产品 -->
					<view class="form-group">
						<text class="form-label">产品</text>
						<view class="input-wrapper">
							<view class="custom-select" @tap="openSelectModal('product', index)">
								<text class="select-text">{{ item.productName || '请选择产品' }}</text>
								<text class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 门店 -->
					<view class="form-group">
						<text class="form-label">门店</text>
						<view class="input-wrapper">
							<view class="custom-select" @tap="openSelectModal('store', index)">
								<text class="select-text">{{ item.storeName || '请选择门店' }}</text>
								<text class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 使用数量 -->
					<view class="form-group">
						<text class="form-label">使用数量</text>
						<view class="input-wrapper">
							<u-input v-model="item.usageQuantity" placeholder="请输入使用数量" type="number" 
								class="select-input" />
						</view>
					</view>

					<!-- 使用时间 -->
					<view class="form-group">
						<text class="form-label">使用时间</text>
						<view class="input-wrapper">
							<view class="custom-select" @tap="openDateTimePicker(index)">
								<text class="select-text">{{ item.usageTimeStr || '请选择使用时间' }}</text>
								<text class="select-arrow">▼</text>
							</view>
						</view>
					</view>

					<!-- 分隔线 -->
					<view v-if="index < usageItems.length - 1" class="divider"></view>
				</view>

				<!-- 添加记录按钮 -->
				<view class="add-item-btn" @click="addItem">
					<text class="add-text">添加一条记录</text>
				</view>

				<!-- 提交按钮 -->
				<view class="btn-group">
					<button type="submit" class="btn btn-primary" 
						:style="{opacity: isSubmitting ? 0.5 : 1}" 
						@tap="isSubmitting ? null : handleFormSubmit()">
						{{ isSubmitting ? '提交中...' : '提交' }}
					</button>
				</view>
			</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" />

		<!-- 日期时间选择器 -->
		<u-datetime-picker 
			v-if="showDateTimePicker" 
			:show="showDateTimePicker" 
			:value="currentDateTimeValue" 
			mode="datetime" 
			@confirm="onDateTimeConfirm" 
			@close="closeDateTimePicker" 
			@cancel="closeDateTimePicker" 
			:show-toolbar="true"
			:close-on-click-overlay="true" 
			confirm-color="#43e97b" 
			title="选择使用时间" 
			class="datetime-picker" />
	</view>
</template>

<script>
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	import usageApi from '@/apis/modules/usage.js'
	import memberApi from '@/apis/modules/member.js'
	import request from '@/service/request.js'
	import config from '@/common/config.js'

	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				isSubmitting: false,
				usageItems: [
					{
						productId: '',
						productName: '',
						storeId: '',
						storeName: '',
						usageTime: '',
						usageTimeStr: '',
						usageQuantity: 1,
						relatedConsumeId: ''
					}
				],
				// 选择弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentSelectIndex: 0,
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',
				// 用户信息
				userInfo: null,
				newuserInfo: null,
				// 审批信息
				approverId: '',
				approverName: '',
				applicationStoreId: '',
				applicationStoreName: '',
				remarks: '',
				// 日期时间选择器相关
				showDateTimePicker: false,
				currentDateTimeIndex: -1,
				currentDateTimeValue: 0
			}
		},

		onLoad() {
			this.initializePage()
		},

		methods: {
			// 初始化页面
			async initializePage() {
				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()
				} catch (error) {
					console.error('页面初始化失败:', error)
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					})
				}
			},

			// 设置默认值
			setDefaultValues() {
				// 使用时间：默认当前时间
				const now = new Date()
				this.usageItems.forEach(item => {
					if (!item.usageTimeStr) {
						item.usageTime = now.getTime()
						item.usageTimeStr = this.utils.formatTime(now)
					}
				})
			},

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

				try {
					if (fieldId === 'product') {
						this.searchParam = 'productName'
						this.modalTitle = '选择产品'
					} else if (fieldId === 'store') {
						this.searchParam = 'fullName'
						this.modalTitle = '选择门店'
					} else if (fieldId === 'approver') {
						this.searchParam = 'realName'
						this.modalTitle = '选择审批人'
					} else if (fieldId === 'applicationStore') {
						this.searchParam = 'fullName'
						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.currentSelectIndex = 0
				this.currentOptions = []
				this.modalLoading = false
				this.hasMoreData = true
				this.currentPage = 1
				this.searchKeyword = ''
			},

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

				try {
					if (fieldId === 'product') {
						// 加载产品列表（只获取上架的产品）
						const params = {
							currentPage: page,
							pageSize: this.pageSize,
							onShelfStatus: 1
						}
						if (searchKeyword) {
							params.productName = searchKeyword
						}

						const res = await request.get(`${config.getApiBaseUrl()}/api/Extend/LqProduct/GetList`, params)
						
						if (res.code === 200 && res.data) {
							const list = res.data.list || []
							options = list.map(item => ({
								value: item.id,
								label: item.productName || '未知产品',
								productName: item.productName,
								id: item.id
							}))
						}
					} else if (fieldId === 'store') {
						// 加载门店列表
						options = await this.getStoreOptions(page, searchKeyword)
					} else if (fieldId === 'approver') {
						// 加载审批人列表（主管）
						options = await this.getApproverOptions(page, searchKeyword)
					} else if (fieldId === 'applicationStore') {
						// 加载申请门店列表
						options = await this.getStoreOptions(page, searchKeyword)
					}

					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 = []
				}
			},

			// 获取门店选项
			async getStoreOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize
					}
					if (searchKeyword) {
						params.dm = searchKeyword
					}
					
					const result = await memberApi.getStoreList(params)
					if (result.code === 200 && result.data) {
						// 处理分页数据
						let storeList = []
						if (Array.isArray(result.data)) {
							storeList = result.data
						} else if (result.data.list) {
							storeList = result.data.list
						}
						
						const options = storeList.map(item => ({
							value: item.id,
							label: item.dm || '未知门店',
							fullName: item.dm,
							id: item.id
						}))
						
						return options
					}
					return []
				} catch (error) {
					console.error('获取门店列表失败:', error)
					return []
				}
			},

			// 获取审批人选项
			async getApproverOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						page: page,
						pageSize: this.pageSize,
						gw: '主管'
					}
					if (searchKeyword) {
						params.realName = searchKeyword
					}
					
					const res = await request.get(`${config.getApiBaseUrl()}/api/Extend/user`, params)
					if (res.code === 200 && res.data && res.data.list) {
						const options = res.data.list.map(item => ({
							value: item.id,
							label: `${item.realName || item.name || item.userName}（主管）`,
							realName: item.realName || item.name || item.userName,
							id: item.id
						}))
						return options
					}
					return []
				} catch (error) {
					console.error('获取审批人列表失败:', error)
					return []
				}
			},

			// 处理弹窗确认
			handleModalConfirm(item) {
				const index = this.currentSelectIndex
				if (this.currentSelectField === 'product') {
					this.usageItems[index].productId = item.value
					this.usageItems[index].productName = item.label
				} else if (this.currentSelectField === 'store') {
					this.usageItems[index].storeId = item.value
					this.usageItems[index].storeName = item.label
				} else if (this.currentSelectField === 'approver') {
					this.approverId = item.value
					this.approverName = item.label
				} else if (this.currentSelectField === 'applicationStore') {
					this.applicationStoreId = item.value
					this.applicationStoreName = item.label
				}
				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)
			},

			// 打开日期时间选择器
			openDateTimePicker(index) {
				this.currentDateTimeIndex = index
				const item = this.usageItems[index]
				this.currentDateTimeValue = item.usageTime || new Date().getTime()
				this.showDateTimePicker = true
			},

			// 日期时间确认
			onDateTimeConfirm(e) {
				const timestamp = e.value
				const index = this.currentDateTimeIndex
				if (index >= 0 && index < this.usageItems.length) {
					const date = new Date(timestamp)
					this.usageItems[index].usageTime = timestamp
					this.usageItems[index].usageTimeStr = this.utils.formatTime(date)
				}
				this.closeDateTimePicker()
			},

			// 关闭日期时间选择器
			closeDateTimePicker() {
				this.showDateTimePicker = false
				this.currentDateTimeIndex = -1
				this.currentDateTimeValue = 0
			},

			// 添加记录
			addItem() {
				const now = new Date()
				this.usageItems.push({
					productId: '',
					productName: '',
					storeId: '',
					storeName: '',
					usageTime: now.getTime(),
					usageTimeStr: this.utils.formatTime(now),
					usageQuantity: 1,
					relatedConsumeId: ''
				})
			},

			// 删除记录
			removeItem(index) {
				if (this.usageItems.length <= 1) {
					uni.showToast({
						title: '至少保留一条记录',
						icon: 'none'
					})
					return
				}
				this.usageItems.splice(index, 1)
			},

			// 表单提交
			async handleFormSubmit() {
				// 验证审批信息
				if (!this.approverId) {
					uni.showToast({
						title: '请选择审批人',
						icon: 'none',
						duration: 3000
					})
					return
				}
				if (!this.applicationStoreId) {
					uni.showToast({
						title: '请选择申请门店',
						icon: 'none',
						duration: 3000
					})
					return
				}

				// 验证所有表单项
				let isValid = true
				let errorMessage = ''

				this.usageItems.forEach((item, index) => {
					if (!item.productId) {
						errorMessage = `第${index + 1}条记录：请选择产品`
						isValid = false
					}
					if (!item.storeId) {
						errorMessage = `第${index + 1}条记录：请选择门店`
						isValid = false
					}
					if (!item.usageQuantity || item.usageQuantity <= 0) {
						errorMessage = `第${index + 1}条记录：请输入使用数量`
						isValid = false
					}
					if (!item.usageTime) {
						errorMessage = `第${index + 1}条记录：请选择使用时间`
						isValid = false
					}
				})

				if (!isValid) {
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					})
					return
				}

				if (this.isSubmitting) return

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

					// 转换日期时间为ISO格式
					const usageItems = this.usageItems.map(item => {
						let usageTime = item.usageTime
						// 如果日期时间不是ISO格式，转换为ISO格式
						if (usageTime && typeof usageTime === 'number') {
							const date = new Date(usageTime)
							usageTime = date.toISOString()
						}
						return {
							productId: item.productId,
							storeId: item.storeId,
							usageTime: usageTime,
							usageQuantity: item.usageQuantity,
							relatedConsumeId: item.relatedConsumeId || ''
						}
					})

					const res = await usageApi.batchCreateUsage({
						approverId: this.approverId,
						applicationStoreId: this.applicationStoreId,
						remarks: this.remarks || '',
						usageItems: usageItems
					})

					if (res.code === 200) {
						uni.showToast({
							title: res.msg || res.message || '添加成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						throw new Error(res.message || res.msg || '操作失败')
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({
						title: error.message || error.msg || '提交失败，请重试',
						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;
	}

	.approval-section {
		margin-bottom: 40rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #2e7d32;
		margin-bottom: 32rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}

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

	.usage-item-card {
		margin-bottom: 40rpx;
	}

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

	.item-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #2e7d32;
	}

	.delete-btn {
		padding: 8rpx 16rpx;
		border-radius: 16rpx;
		background: #ffebee;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-icon {
		font-size: 28rpx;
	}

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

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

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

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

	.select-text:empty::before {
		content: attr(placeholder);
		color: #999;
	}

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

	.select-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 24rpx;
		padding: 24rpx 32rpx;
		font-size: 28rpx;
		color: #2e7d32;
	}

	.divider {
		height: 2rpx;
		background: #f0f0f0;
		margin: 40rpx 0;
	}

	.add-item-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 24rpx;
		background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
		border: 3rpx dashed #43a047;
		border-radius: 24rpx;
		margin-bottom: 40rpx;
	}

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

	.add-text {
		font-size: 28rpx;
		color: #2e7d32;
		font-weight: 500;
	}

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

	.btn {
		width: 100%;
		padding:6rpx 28rpx;
		border-radius: 32rpx;
		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);
	}

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

