Form.vue 12.4 KB
<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="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.id">
									<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%"}' @input="calculateAmount">
							</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%"}' @input="calculateAmount">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="总金额" prop="amount">
							<el-input v-model="dataForm.amount" placeholder="自动计算" readonly :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 @change="handleCreateUserChange">
							</user-select>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="门店" prop="createUserStoreId">
							<el-select v-model="dataForm.createUserStoreId" placeholder="自动填充" disabled :style='{"width":"100%"}' clearable>
								<el-option
									v-for="store in storeOptions"
									:key="store.id"
									:label="store.dm"
									:value="store.id">
								</el-option>
							</el-select>
						</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'
	import { getUserInfo } from '@/api/permission/user'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				categoryLoading: false,
				categoryOptions: [],
				storeOptions: [],
				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() {
			this.loadStoreOptions();
		},
		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.id === value);
					if (selectedCategory) {
						// value已经是level2Code,直接赋值
						this.dataForm.reimbursementCategoryId = value;
						this.dataForm.reimbursementCategoryName = selectedCategory.typeName;
					}
				} else {
					this.dataForm.reimbursementCategoryId = undefined;
					this.dataForm.reimbursementCategoryName = undefined;
				}
			},
			// 自动计算总金额:单价 * 数量
			calculateAmount() {
				const unitPrice = parseFloat(this.dataForm.unitPrice) || 0;
				const quantity = parseFloat(this.dataForm.quantity) || 0;
				this.dataForm.amount = (unitPrice * quantity).toFixed(2);
			},
			// 创建人改变时,自动填充创建人门店
			handleCreateUserChange(userId) {
				if (userId) {
					// 获取用户信息
					request({
						url: '/api/permission/Users/' + userId,
						method: 'GET',
					}).then(res => {
						this.dataForm.createUserStoreId = res.data.mdid || '';
					});
				} else {
					// 清空创建人时,也清空门店
					this.dataForm.createUserStoreId = '';
				}
			},
			// 加载门店列表
			loadStoreOptions() {
				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 = [];
				});
			},
			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);
							}
							// 加载数据后重新计算总金额,确保数据一致性
							this.calculateAmount();
						})
					} else {
						// 新增模式:设置默认值
						// 创建时间:当前时间(时间戳)
						this.dataForm.createTime = new Date().getTime();
						// 购买时间:默认今日(时间戳,设置为今天的00:00:00)
						const today = new Date();
						today.setHours(0, 0, 0, 0);
						this.dataForm.purchaseTime = today.getTime();
						// 审批状态:默认"未审批"
						this.dataForm.approveStatus = '未审批';
						// 创建人:获取当前用户信息
						UserSettingInfo().then(response => {
							if (response.data && response.data.id) {
								this.dataForm.createUser = response.data.id;
								// 自动填充创建人门店
								this.handleCreateUserChange(response.data.id);
							}
						}).catch(() => {
							// 如果API调用失败,尝试从store获取
							const userInfo = this.$store.getters.userInfo;
							if (userInfo) {
								const userId = userInfo.userId || userInfo.id;
								this.dataForm.createUser = userId;
								// 自动填充创建人门店
								this.handleCreateUserChange(userId);
							}
						});
					}
				})
			},
			// 加载已选择的分类选项(用于编辑时显示)
			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>