﻿<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll width="600px">
		<el-row :gutter="15" class="" >
				<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
					<el-col :span="24">
						<el-form-item label="记录编号" prop="id">
							<el-input v-model="dataForm.id" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="购买物品" prop="reimbursementCategoryId">
							<el-select
								v-model="dataForm.reimbursementCategoryId"
								filterable
								remote
								reserve-keyword
								placeholder="请输入一级名称或二级名称搜索"
								:remote-method="searchReimbursementCategory"
								:loading="categoryLoading"
								@change="handleCategoryChange"
								clearable
								:style='{"width":"100%"}'>
								<el-option
									v-for="item in categoryOptions"
									:key="item.id"
									:label="getCategoryLabel(item)"
									:value="item.level2Code">
									<span style="float: left">{{ item.level1Name }} - {{ item.typeName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">({{ item.level2Code }})</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="单价" prop="unitPrice">
							<el-input v-model="dataForm.unitPrice" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="数量" prop="quantity">
							<el-input v-model="dataForm.quantity" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="总金额" prop="amount">
							<el-input v-model="dataForm.amount" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="备注说明" prop="memo">
							<el-input v-model="dataForm.memo" placeholder="请输入" show-word-limit :style='{"width":"100%"}' type='textarea' :autosize='{"minRows":4,"maxRows":4}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="附件" prop="attachment">
							<NCC-UploadFz v-model="dataForm.attachment" :fileSize="5" sizeUnit="MB" :limit="9" buttonText="点击上传" >
							</NCC-UploadFz>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="购买时间" prop="purchaseTime">
							<el-date-picker v-model="dataForm.purchaseTime" placeholder="请选择" clearable :style='{"width":"100%"}' type='date' format="yyyy-MM-dd" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建时间" prop="createTime">
							<el-date-picker v-model="dataForm.createTime" placeholder="请选择" clearable :style='{"width":"100%"}' type='date' format="yyyy-MM-dd" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建人" prop="createUser">
							<user-select v-model="dataForm.createUser" placeholder="请选择" clearable >
							</user-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="创建人门店" prop="createUserStoreId">
							<el-input v-model="dataForm.createUserStoreId" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="审批状态" prop="approveStatus">
							<el-input v-model="dataForm.approveStatus" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="审批人" prop="approveUser">
							<user-select v-model="dataForm.approveUser" placeholder="请选择" clearable >
							</user-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="审批时间" prop="approveTime">
							<el-date-picker v-model="dataForm.approveTime" placeholder="请选择" clearable :style='{"width":"100%"}' type='date' format="yyyy-MM-dd" value-format="timestamp" >
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="审批单编号" prop="applicationId">
							<el-input v-model="dataForm.applicationId" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
				</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	import { previewDataInterface } from '@/api/systemData/dataInterface'
	import { UserSettingInfo } from '@/api/permission/userSetting'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				categoryLoading: false,
				categoryOptions: [],
				dataForm: {
					id:undefined,
					reimbursementCategoryId:undefined,
					reimbursementCategoryName:undefined,
					unitPrice:undefined,
					quantity:undefined,
					amount:undefined,
					memo:undefined,
					attachment:[],
					purchaseTime:undefined,
					createTime:undefined,
					createUser:undefined,
					createUserStoreId:undefined,
					approveStatus:undefined,
					approveUser:undefined,
					approveTime:undefined,
					applicationId:undefined,
				},
				rules: {
				},
			}
		},
		computed: {},
        watch: {},
        created() {
		},
		mounted() {
        },
		methods: {
			goBack() {
                this.$emit('refresh')
            },
			// 获取分类标签显示
			getCategoryLabel(item) {
				if (!item) return '';
				return `${item.level1Name || ''} - ${item.typeName || ''} (${item.level2Code || ''})`;
			},
			// 搜索报销分类（支持OR逻辑：一级名称、二级名称或二级编号）
			searchReimbursementCategory(query) {
				if (query !== '') {
					this.categoryLoading = true;
					// 由于后端是AND逻辑，我们需要分别查询然后合并结果
					Promise.all([
						request({
							url: '/api/Extend/LqReimbursementCategory/Actions/GetNoPagingList',
							method: 'GET',
							data: { level1Name: query }
						}),
						request({
							url: '/api/Extend/LqReimbursementCategory/Actions/GetNoPagingList',
							method: 'GET',
							data: { typeName: query }
						}),
						request({
							url: '/api/Extend/LqReimbursementCategory/Actions/GetNoPagingList',
							method: 'GET',
							data: { level2Code: query }
						})
					]).then(results => {
						// 合并结果并去重
						const allResults = [];
						results.forEach(result => {
							if (result.data && Array.isArray(result.data)) {
								allResults.push(...result.data);
							}
						});
						// 根据id去重
						const uniqueResults = [];
						const seenIds = new Set();
						allResults.forEach(item => {
							if (!seenIds.has(item.id)) {
								seenIds.add(item.id);
								uniqueResults.push(item);
							}
						});
						this.categoryOptions = uniqueResults;
						this.categoryLoading = false;
					}).catch(() => {
						this.categoryLoading = false;
					});
				} else {
					this.categoryOptions = [];
				}
			},
			// 选择分类后自动填充
			handleCategoryChange(value) {
				if (value) {
					const selectedCategory = this.categoryOptions.find(item => item.level2Code === value);
					if (selectedCategory) {
						// value已经是level2Code，直接赋值
						this.dataForm.reimbursementCategoryId = value;
						this.dataForm.reimbursementCategoryName = selectedCategory.typeName;
					}
				} else {
					this.dataForm.reimbursementCategoryId = undefined;
					this.dataForm.reimbursementCategoryName = undefined;
				}
			},
			init(id, isDetail) {
				this.dataForm.id = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				this.categoryOptions = [];
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						// 编辑模式：加载已有数据
						request({
							url: '/api/Extend/LqPurchaseRecords/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							if(!this.dataForm.attachment)this.dataForm.attachment=[];
							// 如果有已选择的分类，加载对应的选项
							if (this.dataForm.reimbursementCategoryId) {
								this.loadCategoryOption(this.dataForm.reimbursementCategoryId);
							}
						})
					} else {
						// 新增模式：设置默认值
						// 创建时间：当前时间（时间戳）
						this.dataForm.createTime = new Date().getTime();
						// 审批状态：默认"未审批"
						this.dataForm.approveStatus = '未审批';
						// 创建人：获取当前用户信息
						UserSettingInfo().then(response => {
							if (response.data && response.data.id) {
								this.dataForm.createUser = response.data.id;
							}
						}).catch(() => {
							// 如果API调用失败，尝试从store获取
							const userInfo = this.$store.getters.userInfo;
							if (userInfo) {
								this.dataForm.createUser = userInfo.userId || userInfo.id;
							}
						});
					}
				})
			},
			// 加载已选择的分类选项（用于编辑时显示）
			loadCategoryOption(level2Code) {
				request({
					url: '/api/Extend/LqReimbursementCategory/Actions/GetNoPagingList',
					method: 'GET',
					data: {
						level2Code: level2Code
					}
				}).then(res => {
					if (res.data && res.data.length > 0) {
						this.categoryOptions = res.data;
					}
				});
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/LqPurchaseRecords`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false,
                                            this.$emit('refresh', true)
                                    }
                                })
                            })
                        } else {
                            request({
                                url: '/api/Extend/LqPurchaseRecords/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            })
                        }
                    }
                })
			},
		}
	}
</script>
