﻿<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll width="1200px">
		<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="8">
					<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="8">
					<el-form-item label="申请人编号" prop="applicationUserId">
						<el-input v-model="dataForm.applicationUserId" placeholder="请输入" clearable :style='{"width":"100%"}' >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="申请人姓名" prop="applicationUserName">
						<el-input v-model="dataForm.applicationUserName" placeholder="请输入" clearable :style='{"width":"100%"}' >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="申请门店" prop="applicationStoreId">
						<el-input v-model="dataForm.applicationStoreId" placeholder="请输入" clearable :style='{"width":"100%"}' >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="申请时间" prop="applicationTime">
						<el-date-picker v-model="dataForm.applicationTime" 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="8">
					<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="8">
					<el-form-item label="审批人" prop="approveUser">
						<user-select v-model="dataForm.approveUser" placeholder="请选择" clearable >
						</user-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<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="8">
					<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="购买物品清单">
						<el-button type="primary" @click="openPurchaseDialog" :disabled="!!isDetail">选择购买物品</el-button>
						<span v-if="selectedPurchaseRecords.length > 0" style="margin-left: 10px;">
							已选择 {{ selectedPurchaseRecords.length }} 条记录
						</span>
					</el-form-item>
				</el-col>
				
				<!-- 已选择的购买物品清单 -->
				<el-col :span="24" v-if="selectedPurchaseRecords.length > 0">
					<el-form-item label="已选清单">
						<el-table 
							:data="selectedPurchaseRecords" 
							:max-height="200"
							border
							size="small">
							<el-table-column type="index" label="序号" width="60" align="center" />
							<el-table-column prop="id" label="记录编号" width="150" align="left" />
							<el-table-column prop="reimbursementCategoryId" label="购买物品编号" width="150" align="left" />
							<el-table-column prop="reimbursementCategoryName" label="购买物品名称" width="150" align="left" />
							<el-table-column prop="unitPrice" label="单价" width="100" align="right" />
							<el-table-column prop="quantity" label="数量" width="80" align="right" />
							<el-table-column prop="amount" label="总金额" width="100" align="right" />
							<el-table-column prop="purchaseTime" label="购买时间" width="120" align="left">
								<template slot-scope="scope">
									{{ scope.row.purchaseTime ? formatDate(scope.row.purchaseTime) : '' }}
								</template>
							</el-table-column>
							<el-table-column prop="memo" label="备注说明" min-width="150" align="left" show-overflow-tooltip />
							<el-table-column label="操作" width="80" align="center" v-if="!isDetail">
								<template slot-scope="scope">
									<el-button type="text" size="small" @click="removePurchaseRecord(scope.$index)" style="color: #F56C6C;">移除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</el-col>
				
				<!-- 购买物品选择弹窗 -->
				<el-dialog 
					title="选择购买物品" 
					:visible.sync="purchaseDialogVisible" 
					width="1000px" 
					:close-on-click-modal="false"
					append-to-body
					:modal-append-to-body="false"
					class="NCC-dialog NCC-dialog_center">
					<el-table 
						ref="purchaseDialogTable"
						v-loading="purchaseListLoading"
						:data="purchaseList" 
						@selection-change="handlePurchaseSelectionChange"
						:max-height="400"
						border>
						<el-table-column type="selection" width="55" />
						<el-table-column prop="id" label="记录编号" width="120" align="left" />
						<el-table-column prop="reimbursementCategoryId" label="购买物品编号" width="150" align="left" />
						<el-table-column prop="reimbursementCategoryName" label="购买物品名称" width="150" align="left" />
						<el-table-column prop="unitPrice" label="单价" width="100" align="right" />
						<el-table-column prop="quantity" label="数量" width="80" align="right" />
						<el-table-column prop="amount" label="总金额" width="100" align="right" />
						<el-table-column prop="purchaseTime" label="购买时间" width="120" align="left">
							<template slot-scope="scope">
								{{ scope.row.purchaseTime ? formatDate(scope.row.purchaseTime) : '' }}
							</template>
						</el-table-column>
						<el-table-column prop="memo" label="备注说明" min-width="150" align="left" show-overflow-tooltip />
					</el-table>
					<span slot="footer" class="dialog-footer">
						<el-button @click="purchaseDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="confirmPurchaseSelection">确 定</el-button>
					</span>
				</el-dialog>
			</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="success" @click="handleApprove" v-if="dataForm.id && !isDetail">通过审批</el-button>
			<el-button type="danger" @click="handleReject" v-if="dataForm.id && !isDetail">拒绝审批</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,
				purchaseDialogVisible: false,
				purchaseListLoading: false,
				purchaseList: [],
				selectedPurchaseRecords: [],
				tempSelectedPurchaseRecords: [], // 弹窗中临时选中的记录
				dataForm: {
					id:undefined,
					applicationUserId:undefined,
					applicationUserName:undefined,
					applicationStoreId:undefined,
					applicationTime:undefined,
					amount:undefined,
					approveUser:undefined,
					approveStatus:undefined,
					approveTime:undefined,
					purchaseRecordsId:undefined,
					selectedPurchaseRecordIds: [], // 选中的购买记录ID列表
				},
				rules: {
				},
			}
		},
		computed: {},
        watch: {},
        created() {
		},
		mounted() {
        },
		methods: {
			goBack() {
                this.$emit('refresh')
            },
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			// 打开购买物品选择弹窗
			openPurchaseDialog() {
				this.purchaseDialogVisible = true;
				// 初始化临时选中列表为当前已选中的记录（用于追加选择）
				this.tempSelectedPurchaseRecords = [...this.selectedPurchaseRecords];
				// 加载当前用户的未报销购买记录
				this.loadCurrentUserPurchaseRecords();
			},
			// 加载当前用户的未报销购买记录
			loadCurrentUserPurchaseRecords() {
				this.purchaseListLoading = true;
				// 先获取当前用户信息
				UserSettingInfo().then(userRes => {
					const currentUserId = userRes.data && userRes.data.id;
					if (!currentUserId) {
						this.$message.warning('无法获取当前用户信息');
						this.purchaseListLoading = false;
						return;
					}
					// 加载购买记录
					request({
						url: '/api/Extend/LqPurchaseRecords/Actions/GetNoPagingList',
						method: 'GET',
						data: {
							createUser: currentUserId
						}
					}).then(res => {
						// 过滤出未报销的记录（ApplicationId为空）
						const allRecords = res.data || [];
						this.purchaseList = allRecords.filter(item => {
							return !item.applicationId || item.applicationId === '';
						});
						// 如果已有选中的记录，在弹窗中选中它们（用于追加选择）
						this.$nextTick(() => {
							if (this.tempSelectedPurchaseRecords.length > 0 && this.$refs.purchaseDialogTable) {
								this.tempSelectedPurchaseRecords.forEach(record => {
									const found = this.purchaseList.find(item => item.id === record.id);
									if (found) {
										this.$refs.purchaseDialogTable.toggleRowSelection(found, true);
									}
								});
							}
						});
						this.purchaseListLoading = false;
					}).catch(() => {
						this.purchaseListLoading = false;
					});
				}).catch(() => {
					this.purchaseListLoading = false;
					this.$message.error('获取用户信息失败');
				});
			},
			// 购买记录选择变化（弹窗中）
			handlePurchaseSelectionChange(selection) {
				this.tempSelectedPurchaseRecords = selection;
			},
			// 确认选择购买物品
			confirmPurchaseSelection() {
				// 追加选择：将弹窗中选中的记录追加到已选记录中（去重）
				const existingIds = new Set(this.selectedPurchaseRecords.map(item => item.id));
				const newRecords = this.tempSelectedPurchaseRecords.filter(item => !existingIds.has(item.id));
				
				// 追加新选中的记录
				this.selectedPurchaseRecords = [...this.selectedPurchaseRecords, ...newRecords];
				
				// 更新ID列表
				this.dataForm.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id);
				
				// 自动计算总金额
				const totalAmount = this.selectedPurchaseRecords.reduce((sum, item) => {
					return sum + (parseFloat(item.amount) || 0);
				}, 0);
				this.dataForm.amount = totalAmount.toFixed(2);
				this.purchaseDialogVisible = false;
			},
			// 移除已选中的购买记录
			removePurchaseRecord(index) {
				this.selectedPurchaseRecords.splice(index, 1);
				this.dataForm.selectedPurchaseRecordIds = this.selectedPurchaseRecords.map(item => item.id);
				// 重新计算总金额
				const totalAmount = this.selectedPurchaseRecords.reduce((sum, item) => {
					return sum + (parseFloat(item.amount) || 0);
				}, 0);
				this.dataForm.amount = totalAmount.toFixed(2);
			},
			init(id, isDetail) {
				this.dataForm.id = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				this.selectedPurchaseRecords = [];
				this.purchaseList = [];
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						// 编辑模式：加载已有数据
						request({
							url: '/api/Extend/LqReimbursementApplication/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							// 转换时间格式：如果 approveTime 是 ISO 8601 字符串，转换为时间戳
							if (this.dataForm.approveTime && typeof this.dataForm.approveTime === 'string') {
								this.dataForm.approveTime = new Date(this.dataForm.approveTime).getTime();
							}
							// 如果有关联的购买记录，加载并选中
							if (this.dataForm.purchaseRecordsId) {
								this.loadSelectedPurchaseRecords(this.dataForm.purchaseRecordsId);
							}
						})
					} else {
						// 新增模式：设置默认值
						UserSettingInfo().then(response => {
							if (response.data) {
								this.dataForm.applicationUserId = response.data.id;
								this.dataForm.applicationUserName = response.data.realName || response.data.userName;
							}
						}).catch(() => {
							const userInfo = this.$store.getters.userInfo;
							if (userInfo) {
								this.dataForm.applicationUserId = userInfo.userId || userInfo.id;
								this.dataForm.applicationUserName = userInfo.userName;
							}
						});
						this.dataForm.applicationTime = new Date().getTime();
					}
				})
			},
			// 加载已选中的购买记录（编辑时使用）
			loadSelectedPurchaseRecords(purchaseRecordsId) {
				if (!purchaseRecordsId) {
					this.selectedPurchaseRecords = [];
					this.dataForm.selectedPurchaseRecordIds = [];
					return;
				}
				// 处理逗号分隔的ID字符串，去除空格、换行符和空值
				// 先替换所有换行符和回车符为逗号，然后按逗号分割
				const normalizedStr = purchaseRecordsId.replace(/[\r\n]+/g, ',').replace(/\s+/g, '');
				const ids = normalizedStr.split(',').map(id => id.trim()).filter(id => id && id !== '');
				
				if (ids.length === 0) {
					this.selectedPurchaseRecords = [];
					this.dataForm.selectedPurchaseRecordIds = [];
					return;
				}
				
				console.log('解析的购买记录ID列表:', ids);
				
				// 加载所有购买记录
				request({
					url: '/api/Extend/LqPurchaseRecords/Actions/GetNoPagingList',
					method: 'GET',
					data: {}
				}).then(res => {
					const allRecords = res.data || [];
					console.log('加载的所有购买记录数量:', allRecords.length);
					
					// 清空已选记录列表
					this.selectedPurchaseRecords = [];
					this.dataForm.selectedPurchaseRecordIds = [];
					
					// 按照ID顺序选中已关联的记录
					const foundIds = [];
					const notFoundIds = [];
					ids.forEach(id => {
						const record = allRecords.find(item => item.id === id);
						if (record) {
							this.selectedPurchaseRecords.push(record);
							this.dataForm.selectedPurchaseRecordIds.push(id);
							foundIds.push(id);
						} else {
							notFoundIds.push(id);
							console.warn('未找到购买记录，ID:', id);
						}
					});
					
					console.log('找到的记录数量:', foundIds.length, '未找到的ID:', notFoundIds);
					
					// 计算总金额
					const totalAmount = this.selectedPurchaseRecords.reduce((sum, item) => {
						return sum + (parseFloat(item.amount) || 0);
					}, 0);
					this.dataForm.amount = totalAmount.toFixed(2);
					
					// 如果有未找到的记录，提示用户
					if (notFoundIds.length > 0) {
						this.$message.warning(`有 ${notFoundIds.length} 条购买记录未找到，可能已被删除`);
					}
				}).catch((error) => {
					console.error('加载购买记录失败:', error);
					this.$message.error('加载购买记录失败');
				});
			},
			dataFormSubmit() {
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						// 验证是否选择了购买记录
						if (!this.dataForm.id && (!this.dataForm.selectedPurchaseRecordIds || this.dataForm.selectedPurchaseRecordIds.length === 0)) {
							this.$message({
								message: '请至少选择一条购买记录',
								type: 'warning',
								duration: 2000
							});
							return;
						}
						
						// 设置关联购买编号（多个ID用逗号分隔）
						this.dataForm.purchaseRecordsId = this.dataForm.selectedPurchaseRecordIds.join(',');
						
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/LqReimbursementApplication`,
                                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/LqReimbursementApplication/' + 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)
                                    }
                                })
                            })
                        }
                    }
                })
			},
			handleApprove() {
				this.$confirm('确定要通过审批吗?', '提示', {
					type: 'warning'
				}).then(() => {
					request({
						url: `/api/Extend/LqReimbursementApplication/${this.dataForm.id}/Actions/Approve`,
						method: 'POST'
					}).then(res => {
						this.$message({
							type: 'success',
							message: res.msg || '审批通过成功',
							onClose: () => {
								this.visible = false;
								this.$emit('refresh', true);
							}
						});
					})
				}).catch(() => {
				});
			},
			handleReject() {
				this.$confirm('确定要拒绝审批吗?', '提示', {
					type: 'warning'
				}).then(() => {
					request({
						url: `/api/Extend/LqReimbursementApplication/${this.dataForm.id}/Actions/Reject`,
						method: 'POST'
					}).then(res => {
						this.$message({
							type: 'success',
							message: res.msg || '拒绝审批成功',
							onClose: () => {
								this.visible = false;
								this.$emit('refresh', true);
							}
						});
					})
				}).catch(() => {
				});
			},
		}
	}
</script>
