<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="审批人" prop="approverId">
						<el-select v-model="dataForm.approverId" placeholder="请选择审批人（财务老师或库管）" clearable filterable
							:style='{"width":"100%"}' @change="onApproverChange">
							<el-option v-for="approver in approverOptions" :key="approver.id" :label="approver.label"
								:value="approver.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="申请门店" prop="applicationStoreId">
						<el-select v-model="dataForm.applicationStoreId" 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="24">
					<el-form-item label="备注" prop="remarks">
						<el-input v-model="dataForm.remarks" type="textarea" :rows="2" placeholder="请输入备注（可选）"
							:style='{"width":"100%"}' maxlength="500" show-word-limit />
					</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%"}' :disabled="!!defaultProductId">
									<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">
							<el-form-item :label="index === 0 ? '关联消费ID' : ''"
								:prop="`usageItems.${index}.relatedConsumeId`">
								<el-input v-model="item.relatedConsumeId" placeholder="请输入关联消费ID（可选）" clearable
									: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'

export default {
		data() {
		return {
			visible: false,
			btnLoading: false,
			defaultProductId: '',
			dataForm: {
				approverId: '',
				applicationStoreId: '',
				remarks: '',
				usageItems: [
					{
						productId: '',
						storeId: '',
						usageTime: '',
						usageQuantity: 1,
						relatedConsumeId: ''
					}
				]
			},
			productOptions: [],
			storeOptions: [],
			approverOptions: [],
			rules: {
				approverId: [
					{ required: true, message: '请选择审批人', trigger: 'change' }
				],
				applicationStoreId: [
					{ required: true, message: '请选择申请门店', trigger: 'change' }
				],
				productId: [
					{ required: true, message: '请选择产品', trigger: 'change' }
				],
				storeId: [
					{ required: true, message: '请选择门店', trigger: 'change' }
				],
				usageQuantity: [
					{ required: true, message: '请输入使用数量', trigger: 'blur' }
				],
				usageTime: [
					{ required: true, message: '请选择使用时间', trigger: 'change' }
				]
			}
		}
	},
	methods: {
		init(productId) {
			this.visible = true
			this.defaultProductId = productId || ''
			this.dataForm = {
				approverId: '',
				applicationStoreId: '',
				remarks: '',
				usageItems: [
					{
						productId: productId || '',
						storeId: '',
						usageTime: '',
						usageQuantity: 1,
						relatedConsumeId: ''
					}
				]
			}
			this.initProductOptions()
			this.initStoreOptions()
			this.initApproverOptions()
		},
		initProductOptions() {
			request({
				url: '/api/Extend/LqProduct/GetList',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				if (res.code == 200 && res.data && res.data.list) {
					this.productOptions = res.data.list
				}
			}).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 = []
			})
		},
		initApproverOptions() {
			// 获取财务老师和库管列表
			Promise.all([
				request({
					url: '/api/Extend/user',
					method: 'GET',
					data: {
						page: 1,
						pageSize: 1000,
						gw: '主管'
					}
				}),
				// request({
				// 	url: '/api/Extend/user',
				// 	method: 'GET',
				// 	data: {
				// 		page: 1,
				// 		pageSize: 1000,
				// 		gw: '经理'
				// 	}
				// })
			]).then(([financeRes, storekeeperRes]) => {
				this.approverOptions = []
				// 添加财务老师
				if (financeRes.code == 200 && financeRes.data && financeRes.data.list) {
					financeRes.data.list.forEach(item => {
						this.approverOptions.push({
							id: item.id,
							label: `${item.realName || item.name || item.userName}（主管）`
						})
					})
				}
				// // 添加库管
				// if (storekeeperRes.code == 200 && storekeeperRes.data && storekeeperRes.data.list) {
				// 	storekeeperRes.data.list.forEach(item => {
				// 		this.approverOptions.push({
				// 			id: item.id,
				// 			label: `${item.realName || item.name || item.userName}（库管）`
				// 		})
				// 	})
				// }
			}).catch(() => {
				this.approverOptions = []
			})
		},
		onApproverChange() {
			// 审批人选择变化时的处理
		},
		addItem() {
			this.dataForm.usageItems.push({
				productId: this.defaultProductId || '',
				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() {
			// 验证审批信息
			if (!this.dataForm.approverId) {
				this.$message({
					type: 'error',
					message: '请选择审批人'
				})
				return false
			}
			if (!this.dataForm.applicationStoreId) {
				this.$message({
					type: 'error',
					message: '请选择申请门店'
				})
				return false
			}

			// 验证所有表单项
			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}条记录：请输入使用数量`
					})
					isValid = false
				}
				if (!item.usageTime) {
					this.$message({
						type: 'error',
						message: `第${index + 1}条记录：请选择使用时间`
					})
					isValid = false
				}
			})

			if (!isValid) {
				return false
			}

			this.btnLoading = true
			// 转换日期时间为ISO格式
			const usageItems = this.dataForm.usageItems.map(item => {
				let usageTime = item.usageTime
				// 如果日期时间不是ISO格式，转换为ISO格式
				if (usageTime && !usageTime.includes('T')) {
					const date = new Date(usageTime)
					usageTime = date.toISOString()
				}
				return {
					productId: item.productId,
					storeId: item.storeId,
					usageTime: usageTime,
					usageQuantity: item.usageQuantity,
					relatedConsumeId: item.relatedConsumeId || ''
				}
			})
			request({
				url: '/api/Extend/LqInventoryUsage/BatchCreate',
				method: 'POST',
				data: {
					approverId: this.dataForm.approverId,
					applicationStoreId: this.dataForm.applicationStoreId,
					remarks: this.dataForm.remarks || '',
					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
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.usage-items-container {
	// max-height: 500px;
	// overflow-y: scroll;
	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;
}
</style>

