<template>
	<el-dialog title="创建送出记录" :visible.sync="visible" width="600px" :close-on-click-modal="false">
		<el-form ref="form" :model="form" :rules="rules" label-width="120px">
			<el-form-item label="门店" prop="storeId">
				<el-select v-model="form.storeId" placeholder="请选择门店" filterable style="width: 100%" @change="handleStoreChange">
					<el-option v-for="item in storeList" :key="item.id" :label="item.fullName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="产品类型" prop="productType">
				<el-select v-model="form.productType" placeholder="请选择产品类型" clearable filterable style="width: 100%" @change="handleProductTypeChange">
					<el-option v-for="item in productTypeOptions" :key="item.Value" :label="item.Name" :value="item.Name" />
				</el-select>
			</el-form-item>
			<el-form-item label="清洗商" prop="laundrySupplierId">
				<el-select v-model="form.laundrySupplierId" placeholder="请选择清洗商" filterable style="width: 100%" @change="handleSupplierChange">
					<el-option v-for="item in filteredSupplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="清洗单价" prop="laundryPrice">
				<el-input v-model="form.laundryPrice" placeholder="自动填充" disabled />
			</el-form-item>
			<el-form-item label="送出数量" prop="quantity">
				<el-input-number v-model="form.quantity" :min="1" :precision="0" style="width: 100%" />
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submit" :loading="loading">确定</el-button>
		</div>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getStoreSelector } from '@/api/extend/store'

export default {
	name: 'SendDialog',
	data() {
		return {
			visible: false,
			loading: false,
			form: {
				storeId: '',
				productType: '',
				laundrySupplierId: '',
				quantity: 1,
				remark: ''
			},
			rules: {
				storeId: [{ required: true, message: '请选择门店', trigger: 'change' }],
				productType: [{ required: true, message: '请选择产品类型', trigger: 'change' }],
				laundrySupplierId: [{ required: true, message: '请选择清洗商', trigger: 'change' }],
				quantity: [{ required: true, message: '请输入送出数量', trigger: 'blur' }]
			},
			storeList: [],
			supplierList: [],
			allSupplierList: [], // 保存所有清洗商列表
			selectedSupplier: null,
			productTypeOptions: []
		}
	},
	computed: {
		// 过滤后的清洗商列表（根据产品类型）
		filteredSupplierList() {
			if (!this.form.productType) {
				return this.allSupplierList
			}
			return this.allSupplierList.filter(supplier => supplier.productType === this.form.productType)
		}
	},
	mounted() {
		this.initStoreList()
		this.initSupplierList()
		this.loadProductTypeOptions()
	},
	methods: {
		// 初始化
		init() {
			this.visible = true
			this.form = {
				storeId: '',
				productType: '',
				laundrySupplierId: '',
				quantity: 1,
				remark: ''
			}
			this.selectedSupplier = null
			this.$nextTick(() => {
				if (this.$refs.form) {
					this.$refs.form.clearValidate()
				}
			})
		},
		// 初始化门店列表
		initStoreList() {
			getStoreSelector().then(res => {
				if (res.code == 200 && res.data && res.data.list) {
					this.storeList = res.data.list
				}
			}).catch(() => {
				this.storeList = []
			})
		},
		// 初始化清洗商列表
		initSupplierList() {
			request({
				url: '/api/Extend/LqLaundrySupplier/GetList',
				method: 'GET',
				data: { currentPage: 1, pageSize: 1000, isEffective: 1 }
			}).then(res => {
				if (res.code == 200 && res.data && res.data.list) {
					this.allSupplierList = res.data.list
					this.supplierList = res.data.list
				}
			}).catch(() => {
				this.allSupplierList = []
				this.supplierList = []
			})
		},
		// 加载产品类型选项
		loadProductTypeOptions() {
			request({
				url: '/api/Extend/LqStoreConsumableInventory/consumable-product-type',
				method: 'GET'
			}).then(res => {
				if (res.code == 200 && res.data && Array.isArray(res.data)) {
					this.productTypeOptions = res.data
				} else {
					this.productTypeOptions = []
				}
			}).catch(() => {
				this.productTypeOptions = []
			})
		},
		// 门店变化
		handleStoreChange() {
			// 可以在这里添加逻辑
		},
		// 产品类型变化
		handleProductTypeChange() {
			// 如果已选择清洗商，检查是否支持新的产品类型
			if (this.form.laundrySupplierId) {
				const supplier = this.allSupplierList.find(item => item.id === this.form.laundrySupplierId)
				if (supplier && this.form.productType && supplier.productType !== this.form.productType) {
					// 如果当前清洗商不支持新的产品类型，清空选择
					this.form.laundrySupplierId = ''
					this.form.laundryPrice = 0
					this.selectedSupplier = null
					this.$message.warning('当前清洗商不支持该产品类型，请重新选择清洗商')
				}
			}
		},
		// 清洗商变化
		handleSupplierChange(value) {
			const supplier = this.filteredSupplierList.find(item => item.id === value)
			if (supplier) {
				this.selectedSupplier = supplier
				this.$set(this.form, 'laundryPrice', supplier.laundryPrice || 0)
			} else {
				this.selectedSupplier = null
				this.$set(this.form, 'laundryPrice', 0)
			}
		},
		// 提交
		submit() {
			this.$refs.form.validate(valid => {
				if (!valid) return

				// 验证产品类型是否匹配
				if (this.selectedSupplier && this.form.productType !== this.selectedSupplier.productType) {
					this.$message.error(`清洗商【${this.selectedSupplier.supplierName}】不支持清洗产品类型【${this.form.productType}】`)
					return
				}

				this.loading = true
				request({
					url: '/api/Extend/LqLaundryFlow/Send',
					method: 'POST',
					data: {
						storeId: this.form.storeId,
						productType: this.form.productType,
						laundrySupplierId: this.form.laundrySupplierId,
						quantity: this.form.quantity,
						remark: this.form.remark
					}
				}).then(res => {
					this.loading = false
					if (res.code == 200) {
						this.$message.success(res.msg || '创建成功')
						this.visible = false
						this.$emit('refresh')
					} else {
						this.$message.error(res.msg || '创建失败')
					}
				}).catch(() => {
					this.loading = false
				})
			})
		}
	},
	watch: {
		visible(val) {
			if (!val) {
				this.$refs.form && this.$refs.form.resetFields()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.dialog-footer {
	text-align: right;
}
</style>

