<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('store')">
							<text class="select-text">{{ formData.storeName || '请选择门店' }}</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('productType')">
							<text class="select-text">{{ formData.productType || '请选择产品类型' }}</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('supplier')">
							<text class="select-text">{{ formData.supplierName || '请选择清洗商' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>
				</view>

				<!-- 清洗单价 -->
				<view class="form-group" v-if="false">
					<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">
						<view class="custom-select" @tap="openDateTimePicker">
							<text class="select-text">{{ formData.sendTimeStr || '请选择送出时间' }}</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.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" />

		<!-- 日期时间选择器 -->
		<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 laundryFlowApi from '@/apis/modules/laundry-flow.js'
	import memberApi from '@/apis/modules/member.js'

	export default {
		components: {
			SearchSelectModal
		},
		data() {
			return {
				isSubmitting: false,
				formData: {
					storeId: '',
					storeName: '',
					productType: '',
					laundrySupplierId: '',
					supplierName: '',
					laundryPrice: '',
					quantity: 1,
					sendTime: '',
					sendTimeStr: '',
					remark: ''
				},
				selectedSupplier: null,
				productTypeOptions: [],
				// 选择弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',
				// 日期时间选择器相关
				showDateTimePicker: false,
				currentDateTimeValue: 0
			}
		},

		onLoad() {
			this.checkLoginStatus()
			this.loadProductTypeOptions()
			// 设置默认送出时间为当前时间
			this.setDefaultSendTime()
		},

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

			// 设置默认送出时间
			setDefaultSendTime() {
				const now = new Date()
				this.formData.sendTime = now.getTime()
				this.formData.sendTimeStr = this.utils.formatTime(now)
			},
			// 打开日期时间选择器
			openDateTimePicker() {
				this.currentDateTimeValue = this.formData.sendTime || new Date().getTime()
				this.showDateTimePicker = true
			},

			// 日期时间确认
			onDateTimeConfirm(e) {
				const timestamp = e.value
				const date = new Date(timestamp)
				this.formData.sendTime = timestamp
				this.formData.sendTimeStr = this.utils.formatTime(date)
				this.closeDateTimePicker()
			},

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

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

				if (field === 'store') {
					this.modalTitle = '选择门店'
					this.searchParam = '请输入门店名称'
				} else if (field === 'supplier') {
					this.modalTitle = '选择清洗商'
					this.searchParam = '请输入清洗商名称'
				} else if (field === 'productType') {
					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 === 'store') {
						options = await this.getStoreOptions(page, searchKeyword)
					} else if (fieldId === 'supplier') {
						options = await this.getSupplierOptions(page, searchKeyword)
					} else if (fieldId === 'productType') {
						options = this.getProductTypeOptions(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 = []
				} finally {
					this.modalLoading = false
				}
			},

			// 获取门店选项
			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 getSupplierOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize,
						isEffective: 1
					}
					if (searchKeyword) {
						params.supplierName = searchKeyword
					}
					if (this.formData.productType) {
						params.productType = this.formData.productType
					}
					const result = await laundryFlowApi.getSupplierList(params)
					if (result.code === 200 && result.data) {
						const list = result.data.list || []
						const options = list.map(item => ({
							value: item.id,
							label: item.supplierName || '未知清洗商',
							supplierName: item.supplierName,
							productType: item.productType,
							laundryPrice: item.laundryPrice,
							id: item.id
						}))

						return options
					}
					return []
				} catch (error) {
					console.error('获取清洗商列表失败:', error)
					return []
				}
			},

			// 加载产品类型选项
			async loadProductTypeOptions() {
				try {
					const result = await laundryFlowApi.getProductTypeList()
					if (result.code === 200 && result.data && Array.isArray(result.data)) {
						this.productTypeOptions = result.data
					} else {
						this.productTypeOptions = []
					}
				} catch (error) {
					console.error('获取产品类型列表失败:', error)
					this.productTypeOptions = []
				}
			},

			// 获取产品类型选项
			getProductTypeOptions(searchKeyword = '') {
				let list = this.productTypeOptions

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

				return list.map(item => ({
					value: item.Name,
					label: item.Name || '未知产品类型',
					Name: item.Name
				}))
			},

			// 处理弹窗确认
			handleModalConfirm(item) {
				if (this.currentSelectField === 'store') {
					this.formData.storeId = item.value
					this.formData.storeName = item.label
				} else if (this.currentSelectField === 'productType') {
					this.formData.productType = item.value
					// 验证产品类型是否匹配已选择的清洗商
					if (this.selectedSupplier && this.selectedSupplier.productType && this.formData.productType !== this.selectedSupplier.productType) {
						uni.showToast({
							title: `清洗商【${this.selectedSupplier.supplierName}】不支持清洗产品类型【${this.formData.productType}】`,
							icon: 'none',
							duration: 3000
						})
					}
				} 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.formData.productType && item.productType && this.formData.productType !== item.productType) {
						uni.showToast({
							title: `清洗商【${item.supplierName}】不支持清洗产品类型【${this.formData.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() {
				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 handleFormSubmit() {
				// 验证必填字段
				if (!this.formData.storeId) {
					uni.showToast({
						title: '请选择门店',
						icon: 'none'
					})
					return
				}

				if (!this.formData.productType) {
					uni.showToast({
						title: '请选择产品类型',
						icon: 'none'
					})
					return
				}

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

				// 验证产品类型是否匹配
				if (this.selectedSupplier && this.formData.productType !== this.selectedSupplier.productType) {
					uni.showToast({
						title: `清洗商【${this.selectedSupplier.supplierName}】不支持清洗产品类型【${this.formData.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: '提交中...'
					})

					// 格式化日期时间为 yyyy-MM-dd HH:mm:ss
					let sendTimeStr = ''
					if (this.formData.sendTime) {
						const date = new Date(this.formData.sendTime)
						sendTimeStr = this.utils.formatTimess(date)
					}

					const submitData = {
						storeId: this.formData.storeId,
						productType: this.formData.productType,
						laundrySupplierId: this.formData.laundrySupplierId,
						quantity: parseInt(this.formData.quantity),
						sendTime: sendTimeStr,
						remark: this.formData.remark || ''
					}

					const res = await laundryFlowApi.createSendRecord(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>

