<template>
	<el-dialog title="修改使用记录" :close-on-click-modal="false" :visible.sync="visible"
		class="NCC-dialog NCC-dialog_center" lock-scroll width="900px">
		<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="申请编号">
						<span>{{ applicationInfo.id || '无' }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="申请人">
						<span>{{ applicationInfo.applicationUserName || '无' }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="申请门店">
						<span>{{ applicationInfo.applicationStoreName || '无' }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="审批状态">
						<el-tag :type="getStatusType(applicationInfo.approvalStatus)" size="small">
							{{ applicationInfo.approvalStatus || '无' }}
						</el-tag>
					</el-form-item>
				</el-col>
			</el-row>
			<el-divider></el-divider>
			<!-- 使用记录列表 -->
			<div class="usage-items-container">
				<div v-for="(item, index) in dataForm.usageItems" :key="index" class="usage-item-row">
					<el-row :gutter="15">
						<el-col :span="12">
							<el-form-item label="产品" :prop="`usageItems.${index}.productId`"
								:rules="rules.productId">
								<el-select v-model="item.productId" placeholder="请选择产品" clearable filterable
									:style='{"width":"100%"}' @change="onProductChange(item, index)">
									<el-option v-for="product in productOptions" :key="product.id"
										:label="product.productName" :value="product.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="门店" :prop="`usageItems.${index}.storeId`"
								:rules="rules.storeId">
								<el-select v-model="item.storeId" placeholder="请选择门店" clearable filterable
									:style='{"width":"100%"}'>
									<el-option v-for="store in storeOptions" :key="store.id" :label="store.dm"
										:value="store.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="使用数量"
								:prop="`usageItems.${index}.usageQuantity`" :rules="rules.usageQuantity">
								<el-input-number v-model="item.usageQuantity" placeholder="数量" :min="1" :precision="0"
									:style='{"width":"100%"}' />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="使用时间"
								:prop="`usageItems.${index}.usageTime`" :rules="rules.usageTime">
								<el-date-picker v-model="item.usageTime" type="datetime" placeholder="使用时间"
									value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
									:style='{"width":"100%"}' />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="dataForm.usageItems.length > 1">
							<div class="item-actions">
								<el-button type="text" icon="el-icon-delete" @click="removeItem(index)"
									class="delete-btn">删除</el-button>
							</div>
						</el-col>
					</el-row>
					<el-divider v-if="index < dataForm.usageItems.length - 1"></el-divider>
				</div>
			</div>
			<div class="add-item-btn">
				<el-button type="text" icon="el-icon-plus" @click="addItem()">添加一条记录</el-button>
			</div>
		</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'
import { getBatchInfo } from '@/api/extend/lqInventory'

export default {
	data() {
		return {
			visible: false,
			btnLoading: false,
			applicationId: '',
			applicationInfo: {
				id: '',
				applicationUserName: '',
				applicationStoreName: '',
				approvalStatus: ''
			},
			dataForm: {
				usageItems: [
					{
						productId: '',
						storeId: '',
						usageTime: '',
						usageQuantity: 1,
						relatedConsumeId: ''
					}
				]
			},
			productOptions: [],
			storeOptions: [],
			rules: {
				productId: [
					{ required: true, message: '请选择产品', trigger: 'change' }
				],
				storeId: [
					{ required: true, message: '请选择门店', trigger: 'change' }
				],
				usageQuantity: [
					{ required: true, message: '请输入使用数量', trigger: 'blur' },
					{ type: 'number', min: 1, message: '使用数量必须大于0', trigger: 'blur' }
				],
				usageTime: [
					{ required: true, message: '请选择使用时间', trigger: 'change' }
				]
			}
		}
	},
	methods: {
		init(row) {
			this.visible = true
			this.applicationId = row.id || ''
			this.applicationInfo = {
				id: row.id || '',
				applicationUserName: row.applicationUserName || '',
				applicationStoreName: row.applicationStoreName || '',
				approvalStatus: row.approvalStatus || ''
			}
			this.dataForm = {
				usageItems: []
			}
			this.initProductOptions()
			this.initStoreOptions()
			this.loadUsageRecords(row.usageBatchId)
		},
		loadUsageRecords(batchId) {
			if (!batchId) {
				this.$message({
					type: 'warning',
					message: '批次ID不存在，无法加载使用记录'
				})
				return
			}
			getBatchInfo(batchId).then(res => {
				if (res.code == 200 && res.data && res.data.UsageRecords) {
					// 将使用记录转换为表单数据格式
					this.dataForm.usageItems = res.data.UsageRecords.map(record => {
						// 转换时间格式
						let usageTime = ''
						if (record.usageTime) {
							const date = new Date(record.usageTime)
							if (!isNaN(date.getTime())) {
								const year = date.getFullYear()
								const month = String(date.getMonth() + 1).padStart(2, '0')
								const day = String(date.getDate()).padStart(2, '0')
								const hours = String(date.getHours()).padStart(2, '0')
								const minutes = String(date.getMinutes()).padStart(2, '0')
								const seconds = String(date.getSeconds()).padStart(2, '0')
								usageTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
							}
						}
						return {
							productId: record.productId || '',
							storeId: record.storeId || '',
							usageTime: usageTime,
							usageQuantity: record.usageQuantity || 1,
							relatedConsumeId: record.relatedConsumeId || ''
						}
					})
					// 如果没有任何记录，至少添加一条空记录
					if (this.dataForm.usageItems.length === 0) {
						this.dataForm.usageItems = [{
							productId: '',
							storeId: '',
							usageTime: '',
							usageQuantity: 1,
							relatedConsumeId: ''
						}]
					}
				} else {
					this.$message({
						type: 'error',
						message: res.msg || '加载使用记录失败'
					})
					// 如果加载失败，至少添加一条空记录
					this.dataForm.usageItems = [{
						productId: '',
						storeId: '',
						usageTime: '',
						usageQuantity: 1,
						relatedConsumeId: ''
					}]
				}
			}).catch(() => {
				this.$message({
					type: 'error',
					message: '加载使用记录失败，请稍后重试'
				})
				// 如果加载失败，至少添加一条空记录
				this.dataForm.usageItems = [{
					productId: '',
					storeId: '',
					usageTime: '',
					usageQuantity: 1,
					relatedConsumeId: ''
				}]
			})
		},
		initProductOptions() {
			request({
				url: '/api/Extend/LqProduct/GetList',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000,
					onShelfStatus: 1  // 只获取上架的产品
				}
			}).then(res => {
				if (res.code == 200 && res.data && res.data.list) {
					// 过滤出上架的产品
					this.productOptions = res.data.list.filter(product => product.onShelfStatus === 1)
				}
			}).catch(() => {
				this.productOptions = []
			})
		},
		initStoreOptions() {
			request({
				url: '/api/Extend/LqMdxx',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				if (res.data && res.data.list) {
					this.storeOptions = res.data.list
				}
			}).catch(() => {
				this.storeOptions = []
			})
		},
		onProductChange(item, index) {
			// 产品选择变化时的处理
		},
		addItem() {
			this.dataForm.usageItems.push({
				productId: '',
				storeId: '',
				usageTime: '',
				usageQuantity: 1,
				relatedConsumeId: ''
			})
		},
		removeItem(index) {
			if (this.dataForm.usageItems.length > 1) {
				this.dataForm.usageItems.splice(index, 1)
			} else {
				this.$message({
					type: 'warning',
					message: '至少保留一条记录'
				})
			}
		},
		dataFormSubmit() {
			// 验证所有表单项
			let isValid = true
			this.dataForm.usageItems.forEach((item, index) => {
				if (!item.productId) {
					this.$message({
						type: 'error',
						message: `第${index + 1}条记录：请选择产品`
					})
					isValid = false
				}
				if (!item.storeId) {
					this.$message({
						type: 'error',
						message: `第${index + 1}条记录：请选择门店`
					})
					isValid = false
				}
				if (!item.usageQuantity || item.usageQuantity <= 0) {
					this.$message({
						type: 'error',
						message: `第${index + 1}条记录：请输入使用数量（必须大于0）`
					})
					isValid = false
				}
				if (!item.usageTime) {
					this.$message({
						type: 'error',
						message: `第${index + 1}条记录：请选择使用时间`
					})
					isValid = false
				}
			})

			if (!isValid) {
				return false
			}

			if (!this.applicationId) {
				this.$message({
					type: 'error',
					message: '申请ID不存在'
				})
				return false
			}

			this.btnLoading = true
			// 转换日期时间为ISO格式
			const usageItems = this.dataForm.usageItems.map(item => {
				let usageTime = item.usageTime
				// 如果日期时间不是ISO格式，转换为ISO格式
				if (usageTime && !usageTime.includes('T')) {
					// 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 ISO 格式
					const dateStr = usageTime.replace(' ', 'T')
					const date = new Date(dateStr)
					if (!isNaN(date.getTime())) {
						usageTime = date.toISOString()
					}
				}
				return {
					productId: item.productId,
					storeId: item.storeId,
					usageTime: usageTime,
					usageQuantity: item.usageQuantity,
					relatedConsumeId: item.relatedConsumeId || ''
				}
			})
			request({
				url: '/api/Extend/LqInventoryUsage/UpdateApplicationUsageRecords',
				method: 'PUT',
				data: {
					applicationId: this.applicationId,
					usageItems: usageItems
				}
			}).then(res => {
				this.btnLoading = false
				this.$message({
					type: 'success',
					message: res.msg || '修改成功',
					onClose: () => {
						this.visible = false
						this.$emit('refresh')
					}
				})
			}).catch(() => {
				this.btnLoading = false
			})
		},
		getStatusType(status) {
			const statusMap = {
				'待审批': 'info',
				'审批中': 'warning',
				'已通过': 'success',
				'未通过': 'danger',
				'已退回': 'info'
			}
			return statusMap[status] || 'info'
		}
	}
}
</script>

<style lang="scss" scoped>
.usage-items-container {
	padding: 10px 0;
}

.usage-item-row {
	margin-bottom: 10px;
}

.item-actions {
	display: flex;
	justify-content: flex-end;
	margin-top: 10px;

	.delete-btn {
		color: #F56C6C;

		&:hover {
			color: #f78989;
		}
	}
}

.add-item-btn {
	margin-top: 10px;
	text-align: center;
	padding: 10px 0;
	border-top: 1px dashed #dcdfe6;
}

::v-deep .el-form-item {
	margin-bottom: 18px;
}
</style>

