<template>
	<view class="form-container">
		<view class="form-card">
			<view class="form-content">
				<!-- 批次号 -->
				<view class="form-group">
					<text class="form-label">批次号</text>
					<view class="input-wrapper">
						<view class="custom-select" @tap="openSelectModal('batch')">
							<text class="select-text">{{ formData.batchNumber || '请选择批次号' }}</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="sendRecordInfo.storeName" placeholder="无" 
							disabled class="select-input" />
					</view>
				</view>

				<!-- 产品类型（只读） -->
				<view class="form-group">
					<text class="form-label">产品类型</text>
					<view class="input-wrapper">
						<u-input v-model="sendRecordInfo.productType" placeholder="无" 
							disabled class="select-input" />
					</view>
				</view>

				<!-- 送出数量（只读） -->
				<view class="form-group">
					<text class="form-label">送出数量</text>
					<view class="input-wrapper">
						<u-input v-model="sendRecordInfo.quantity" placeholder="无" 
							disabled class="select-input" />
					</view>
				</view>

				<!-- 清洗商 -->
				<view class="form-group">
					<text class="form-label">清洗商</text>
					<view class="input-wrapper">
						<view class="custom-select" @tap="openSelectModal('supplier')">
							<text class="select-text">{{ formData.supplierName || '请选择清洗商' }}</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="formData.laundryPrice" placeholder="自动填充" 
							disabled 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" class="select-input" />
					</view>
				</view>

				<!-- 预计总费用 -->
				<view class="form-group">
					<text class="form-label">预计总费用</text>
					<view class="input-wrapper">
						<u-input v-model="totalPrice" placeholder="自动计算" 
							disabled class="select-input" />
					</view>
				</view>

				<!-- 备注 -->
				<view class="form-group">
					<text class="form-label">备注</text>
					<view class="input-wrapper">
						<u-input v-model="formData.remark" placeholder="请输入备注（可说明差异原因，如损坏、丢失等）" 
							type="textarea" :maxlength="500" class="select-input" />
					</view>
				</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" />
	</view>
</template>

<script>
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	import laundryFlowApi from '@/apis/modules/laundry-flow.js'

	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				isSubmitting: false,
				formData: {
					batchNumber: '',
					laundrySupplierId: '',
					supplierName: '',
					laundryPrice: '',
					quantity: 0,
					remark: ''
				},
				sendRecordInfo: {
					storeName: '',
					productType: '',
					quantity: 0
				},
				selectedSupplier: null,
				batchList: [],
				allSupplierList: [],
				// 选择弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: ''
			}
		},

		computed: {
			// 计算总费用
			totalPrice() {
				const quantity = parseFloat(this.formData.quantity) || 0
				const price = parseFloat(this.formData.laundryPrice) || 0
				return (quantity * price).toFixed(2)
			},
			// 过滤后的清洗商列表（根据产品类型）
			filteredSupplierList() {
				if (!this.sendRecordInfo.productType) {
					return this.allSupplierList
				}
				return this.allSupplierList.filter(supplier => supplier.productType === this.sendRecordInfo.productType)
			}
		},

		onLoad() {
			this.checkLoginStatus()
			this.initBatchList()
			this.initSupplierList()
		},

		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
			},

			// 初始化批次列表
			async initBatchList() {
				try {
					// 获取所有送出记录
					const sendRes = await laundryFlowApi.getLaundryFlowList({
						currentPage: 1,
						pageSize: 1000,
						flowType: 0,
						isEffective: 1
					})

					if (sendRes.code === 200 && sendRes.data && sendRes.data.list) {
						const sendRecords = sendRes.data.list

						// 获取所有送回记录
						const returnRes = await laundryFlowApi.getLaundryFlowList({
							currentPage: 1,
							pageSize: 1000,
							flowType: 1,
							isEffective: 1
						})

						let returnRecords = []
						if (returnRes.code === 200 && returnRes.data && returnRes.data.list) {
							returnRecords = returnRes.data.list
						}

						// 按批次号分组统计送回数量
						const returnMap = {}
						returnRecords.forEach(item => {
							if (!returnMap[item.batchNumber]) {
								returnMap[item.batchNumber] = 0
							}
							returnMap[item.batchNumber] += item.quantity
						})

						// 过滤出可以送回记录的批次（送出数量 > 已送回数量）
						this.batchList = sendRecords.filter(send => {
							const returnedQty = returnMap[send.batchNumber] || 0
							return send.quantity > returnedQty
						}).map(send => ({
							batchNumber: send.batchNumber,
							storeName: send.storeName,
							productType: send.productType,
							quantity: send.quantity,
							returnedQty: returnMap[send.batchNumber] || 0
						}))
					} else {
						this.batchList = []
					}
				} catch (error) {
					console.error('初始化批次列表失败:', error)
					this.batchList = []
				}
			},

			// 初始化清洗商列表
			async initSupplierList() {
				try {
					const res = await laundryFlowApi.getSupplierList({
						currentPage: 1,
						pageSize: 1000,
						isEffective: 1
					})

					if (res.code === 200 && res.data && res.data.list) {
						this.allSupplierList = res.data.list
					} else {
						this.allSupplierList = []
					}
				} catch (error) {
					console.error('初始化清洗商列表失败:', error)
					this.allSupplierList = []
				}
			},

			// 打开选择弹窗
			openSelectModal(field) {
				this.currentSelectField = field
				this.currentPage = 1
				this.hasMoreData = true
				this.searchKeyword = ''
				this.searchParam = ''

				if (field === 'batch') {
					this.modalTitle = '选择批次号'
					this.searchParam = '请输入批次号'
				} else if (field === 'supplier') {
					this.modalTitle = '选择清洗商'
					this.searchParam = '请输入清洗商名称'
				}

				this.showModal = true
				this.loadOptionsData(field, 1)
			},

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

				try {
					if (fieldId === 'batch') {
						options = this.getBatchOptions(searchKeyword)
					} else if (fieldId === 'supplier') {
						options = this.getSupplierOptions(searchKeyword)
					}

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

					this.hasMoreData = false // 批次和清洗商列表不需要分页
				} catch (error) {
					console.error('加载选项数据失败:', error)
					this.currentOptions = []
				} finally {
					this.modalLoading = false
				}
			},

			// 获取批次选项
			getBatchOptions(searchKeyword = '') {
				let list = this.batchList

				if (searchKeyword) {
					list = list.filter(item => 
						item.batchNumber.includes(searchKeyword) ||
						item.storeName.includes(searchKeyword) ||
						item.productType.includes(searchKeyword)
					)
				}

				return list.map(item => ({
					value: item.batchNumber,
					label: `${item.batchNumber} (${item.storeName} - ${item.productType} - 送出${item.quantity}件)`,
					batchNumber: item.batchNumber,
					storeName: item.storeName,
					productType: item.productType,
					quantity: item.quantity
				}))
			},

			// 获取清洗商选项
			getSupplierOptions(searchKeyword = '') {
				let list = this.filteredSupplierList

				if (searchKeyword) {
					list = list.filter(item => 
						item.supplierName && item.supplierName.includes(searchKeyword)
					)
				}

				return list.map(item => ({
					value: item.id,
					label: item.supplierName || '未知清洗商',
					supplierName: item.supplierName,
					productType: item.productType,
					laundryPrice: item.laundryPrice,
					id: item.id
				}))
			},

			// 处理弹窗确认
			handleModalConfirm(item) {
				if (this.currentSelectField === 'batch') {
					this.formData.batchNumber = item.batchNumber
					this.sendRecordInfo = {
						storeName: item.storeName || '',
						productType: item.productType || '',
						quantity: item.quantity || 0
					}
					// 清空已选择的清洗商
					this.formData.laundrySupplierId = ''
					this.formData.supplierName = ''
					this.formData.laundryPrice = ''
					this.selectedSupplier = null
				} else if (this.currentSelectField === 'supplier') {
					this.formData.laundrySupplierId = item.value
					this.formData.supplierName = item.label
					this.selectedSupplier = item
					// 自动填充清洗单价
					this.formData.laundryPrice = item.laundryPrice || ''
					// 验证产品类型是否匹配
					if (this.sendRecordInfo.productType && item.productType && this.sendRecordInfo.productType !== item.productType) {
						uni.showToast({
							title: `清洗商【${item.supplierName}】不支持清洗产品类型【${this.sendRecordInfo.productType}】`,
							icon: 'none',
							duration: 3000
						})
					}
				}
				this.closeModal()
			},

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

			// 处理加载更多
			async handleLoadMore() {
				// 批次和清洗商列表不需要分页
			},

			// 处理刷新
			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 handleFormSubmit() {
				// 验证必填字段
				if (!this.formData.batchNumber) {
					uni.showToast({
						title: '请选择批次号',
						icon: 'none'
					})
					return
				}

				if (!this.formData.laundrySupplierId) {
					uni.showToast({
						title: '请选择清洗商',
						icon: 'none'
					})
					return
				}

				// 验证产品类型是否匹配
				if (this.selectedSupplier && this.sendRecordInfo.productType && this.sendRecordInfo.productType !== this.selectedSupplier.productType) {
					uni.showToast({
						title: `清洗商【${this.selectedSupplier.supplierName}】不支持清洗产品类型【${this.sendRecordInfo.productType}】`,
						icon: 'none',
						duration: 3000
					})
					return
				}

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

				this.isSubmitting = true

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

					const submitData = {
						batchNumber: this.formData.batchNumber,
						laundrySupplierId: this.formData.laundrySupplierId,
						quantity: parseInt(this.formData.quantity),
						remark: this.formData.remark || ''
					}

					const res = await laundryFlowApi.createReturnRecord(submitData)

					if (res.code === 200) {
						uni.showToast({
							title: res.msg || '创建成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						throw new Error(res.msg || res.message || '创建失败')
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({
						title: error.message || error.msg || '创建失败，请重试',
						icon: 'none',
						duration: 3000
					})
				} 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;
		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: 88rpx;
		box-sizing: border-box;
	}

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

	.select-text:empty::before {
		content: '请选择';
		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;
		min-height: 88rpx;
		box-sizing: border-box;
	}

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

	.btn {
		width: 100%;
		height: 96rpx;
		border-radius: 32rpx;
		font-size: 32rpx;
		font-weight: 600;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
		letter-spacing: 2rpx;
	}

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

