<template>
	<el-dialog title="编辑库存" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center"
		lock-scroll width="800px">
		<el-form ref="elForm" :model="dataForm" size="small" label-width="120px" label-position="right" :rules="rules">
			<el-row :gutter="15">
				<el-col :span="12">
					<el-form-item label="产品">
						<el-input v-model="productName" placeholder="产品名称" readonly :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="入库类型">
						<el-tag :type="dataForm.stockInType === 2 ? 'warning' : 'info'" size="small">
							{{ dataForm.stockInType === 2 ? '采购入库' : '普通入库' }}
						</el-tag>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="数量" prop="quantity">
						<el-input-number v-model="dataForm.quantity" placeholder="请输入数量" :min="1" :precision="0"
							:style='{"width":"100%"}' @change="calculateFinalAmount" />
					</el-form-item>
				</el-col>
				<el-col :span="12" v-if="dataForm.stockInType === 2">
					<el-form-item label="采购单价" prop="purchaseUnitPrice">
						<el-input-number v-model="dataForm.purchaseUnitPrice" placeholder="请输入采购单价" :min="0"
							:precision="2" :style='{"width":"100%"}' @change="calculateFinalAmount" />
					</el-form-item>
				</el-col>
				<el-col :span="12" v-if="dataForm.stockInType === 2">
					<el-form-item label="采购总金额">
						<el-input v-model="purchaseAmountDisplay" placeholder="系统自动计算" readonly
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12" v-if="dataForm.stockInType === 1">
					<el-form-item label="单价">
						<el-input-number v-model="dataForm.unitPrice" :placeholder="productAveragePrice ? `产品平均单价：¥${formatMoney(productAveragePrice)}` : '请输入单价'" :min="0"
							:precision="2" :style='{"width":"100%"}' @change="calculateFinalAmount" />
						<div v-if="productAveragePrice && !dataForm.unitPrice" style="font-size: 12px; color: #909399; margin-top: 4px;">
							默认使用产品平均单价：¥{{ formatMoney(productAveragePrice) }}
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="最终金额" prop="finalAmount">
						<el-input-number v-model="dataForm.finalAmount" placeholder="自动计算" :min="0"
							:precision="2" :style='{"width":"100%"}' @change="onFinalAmountChange" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="入库时间" prop="stockInTime">
						<el-date-picker v-model="dataForm.stockInTime" type="date" placeholder="请选择入库时间"
							value-format="yyyy-MM-dd" format="yyyy-MM-dd" :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="生产日期" prop="productionDate">
						<el-date-picker v-model="dataForm.productionDate" type="date" placeholder="请选择生产日期"
							value-format="yyyy-MM-dd" format="yyyy-MM-dd" :style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="保质期(天)" prop="shelfLife">
						<el-input-number v-model="dataForm.shelfLife" placeholder="请输入保质期" :min="1" :precision="0"
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="批次号" prop="batchNumber">
						<el-input v-model="dataForm.batchNumber" placeholder="请输入批次号" clearable
							:style='{"width":"100%"}' />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
	data() {
		return {
			visible: false,
			btnLoading: false,
			productName: '',
			productAveragePrice: null, // 产品平均单价
			dataForm: {
				id: '',
				productId: '',
				stockInType: 1,
				quantity: 1,
				stockInTime: '',
				productionDate: '',
				shelfLife: null,
				batchNumber: '',
				purchaseUnitPrice: null,
				unitPrice: null, // 普通入库时的单价
				finalAmount: null
			},
			isManualEditFinalAmount: false, // 标记是否手动修改了最终金额
			rules: {
				quantity: [
					{ required: true, message: '请输入数量', trigger: 'blur' }
				],
				purchaseUnitPrice: [
					{ required: false, message: '请输入采购单价', trigger: 'blur' }
				],
				finalAmount: [
					{ required: false, message: '请输入最终金额', trigger: 'blur' }
				]
			}
		}
	},
	computed: {
		// 计算采购总金额（采购单价 × 数量）
		purchaseAmountDisplay() {
			if (this.dataForm.stockInType === 2 && this.dataForm.purchaseUnitPrice && this.dataForm.quantity) {
				return '¥' + (this.dataForm.purchaseUnitPrice * this.dataForm.quantity).toFixed(2)
			}
			return '无'
		},
		// 获取当前使用的单价
		currentUnitPrice() {
			if (this.dataForm.stockInType === 2) {
				// 采购入库：使用采购单价
				return this.dataForm.purchaseUnitPrice || 0
			} else {
				// 普通入库：使用输入的单价，如果没有则使用产品平均单价
				return this.dataForm.unitPrice || this.productAveragePrice || 0
			}
		}
	},
	methods: {
		// 初始化（编辑模式）
		init(row) {
			this.visible = true
			this.productName = row.productName || ''
			this.productAveragePrice = row.productAveragePrice || row.productPrice || null
			this.isManualEditFinalAmount = false
			
			// 计算普通入库时的单价（如果有最终金额和数量，反推单价）
			let unitPrice = null
			if (row.stockInType === 1 && row.finalAmount && row.quantity && row.quantity > 0) {
				unitPrice = Number((row.finalAmount / row.quantity).toFixed(2))
			}
			
			this.dataForm = {
				id: row.id || '',
				productId: row.productId || '',
				stockInType: row.stockInType || 1,
				quantity: row.quantity || 1,
				stockInTime: row.stockInTime ? this.formatDateForInput(row.stockInTime) : '',
				productionDate: row.productionDate ? this.formatDateForInput(row.productionDate) : '',
				shelfLife: row.shelfLife || null,
				batchNumber: row.batchNumber || '',
				purchaseUnitPrice: row.purchaseUnitPrice || null,
				unitPrice: unitPrice,
				finalAmount: row.finalAmount || null
			}
			
			// 如果没有最终金额，自动计算（使用当前单价和数量）
			this.$nextTick(() => {
				if (!this.dataForm.finalAmount && this.currentUnitPrice && this.currentUnitPrice > 0 && this.dataForm.quantity && this.dataForm.quantity > 0) {
					this.calculateFinalAmount()
				}
			})
			
			this.$nextTick(() => {
				this.$refs.elForm && this.$refs.elForm.clearValidate()
			})
		},
		// 格式化日期用于输入框（yyyy-MM-dd格式）
		formatDateForInput(date) {
			if (!date) return ''
			try {
				const d = new Date(date)
				if (isNaN(d.getTime())) return ''
				const year = d.getFullYear()
				const month = String(d.getMonth() + 1).padStart(2, '0')
				const day = String(d.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			} catch (e) {
				return ''
			}
		},
		// 计算最终金额（数量 × 单价）
		calculateFinalAmount() {
			if (this.isManualEditFinalAmount) {
				// 如果用户手动修改了最终金额，不自动计算
				return
			}
			
			const unitPrice = this.currentUnitPrice
			const quantity = this.dataForm.quantity
			
			if (unitPrice && unitPrice > 0 && quantity && quantity > 0) {
				const calculatedAmount = unitPrice * quantity
				this.dataForm.finalAmount = Number(calculatedAmount.toFixed(2))
			} else {
				this.dataForm.finalAmount = null
			}
		},
		// 最终金额手动修改时的处理
		onFinalAmountChange() {
			// 标记为手动修改，停止自动计算
			this.isManualEditFinalAmount = true
		},
		// 格式化金额
		formatMoney(amount) {
			if (!amount && amount !== 0) return '0.00'
			return Number(amount).toFixed(2)
		},
		// 表单提交
		dataFormSubmit() {
			this.$refs.elForm.validate((valid) => {
				if (!valid) {
					return false
				}
				this.btnLoading = true

				// 构建请求参数
				const params = {
					id: this.dataForm.id,
					productId: this.dataForm.productId,
					quantity: this.dataForm.quantity,
					stockInType: this.dataForm.stockInType,
					stockInTime: this.dataForm.stockInTime || null,
					productionDate: this.dataForm.productionDate || null,
					shelfLife: this.dataForm.shelfLife || null,
					batchNumber: this.dataForm.batchNumber || null,
					purchaseUnitPrice: this.dataForm.purchaseUnitPrice || null,
					finalAmount: this.dataForm.finalAmount || null
				}

				// 如果是采购入库，验证采购单价
				if (params.stockInType === 2) {
					if (!params.purchaseUnitPrice || params.purchaseUnitPrice <= 0) {
						this.$message({
							type: 'warning',
							message: '采购入库时，采购单价必须大于0',
							duration: 1500
						})
						this.btnLoading = false
						return
					}
				}

				request({
					url: '/api/Extend/LqInventory/Update',
					method: 'PUT',
					data: params
				}).then(res => {
					this.btnLoading = false
					if (res.code == 200) {
						this.$message({
							type: 'success',
							message: res.msg || '更新成功',
							duration: 1500,
							onClose: () => {
								this.visible = false
								this.$emit('refresh')
							}
						})
					} else {
						this.$message({
							type: 'error',
							message: res.msg || '更新失败',
							duration: 2000
						})
					}
				}).catch(err => {
					this.btnLoading = false
					console.error('更新失败:', err)
					this.$message({
						type: 'error',
						message: err.msg || '更新失败，请重试',
						duration: 2000
					})
				})
			})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
	font-weight: 500;
}
</style>
