<!--文件上传组件-->
<template>
	<div :key="uploadKey">
		<!-- <el-divider v-if="showDivider" content-position="left"><i class="el-icon-document"></i> {{ dividerName }} -->
		<el-upload ref="upload" style="display: inline-block; " :show-header="'status'" action="" :limit="999"
			:on-success="handleSuccessUpload" :http-request="httpRequest" multiple :on-exceed="(files, fileList) => {
				$message.warning(`当前限制选择 999 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
			}" :show-file-list="false" :before-upload="beforeUpload" :on-change="changes" :on-progress="uploadVideoProcess"
			:file-list="fileList">
			<template v-if="auth === 'view' && uploadFlag === false" #tip>
				<el-button v-show="false" :loading="loading" type="primary" size="default" :disabled="true"> 点击上传
				</el-button>
			</template>
			<template v-else #trigger>
				<el-button v-show="false" class="upload-btn" :loading="loading" type="primary" size="default"> 点击上传
				</el-button> <span v-show="false" style="margin-left: 20px;font-size:14px;font-weight:normal;color:red;"
					type="primary">
					上传报销的数电发票xml文件</span>
			</template>
		</el-upload>
		<!-- </el-divider> -->
		<div style="height: calc(100% - 80px);margin-top: -20px;">
			<!-- 进度条 -->
			<el-progress style="margin-left: 5em" v-if="progressFlag" :percentage="loadProgress"></el-progress>
			<el-table :row-class-name="tableRowClassName" ref="uploadTable" v-loading="loading" :key="tableKey"
				:summary-method="getSummaries" show-summary :data="dataListNew">
				<el-table-column label="" width="80" />
				<el-table-column label="序号" type="index" width="80" />
				<!--        <el-table-column type="seq" width="40"></el-table-column>-->
				<el-table-column label="文件名称" prop="name" align="center" width="290">
					<template #default="scope">
						<div v-if="ifName(scope.row) === true">
							<el-image style="width: 30px; height: 30px;padding-top: 4px;" :src="scope.row.lsUrl"
								:preview-src-list="[scope.row.lsUrl]" :preview-teleported="true"></el-image>
						</div>
						<div v-else>
							<el-link type="primary" :underline="false" @click="showFile(scope.row)">{{ scope.row.name
							}}</el-link>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="创建人" prop="createBy.name" align="center"></el-table-column>
				<el-table-column label="创建时间" prop="createTime" align="center" width="180"></el-table-column>
				<el-table-column label="文件大小" prop="size" align="center" width="110">
					<template #default="scope">
						{{ getSize(scope.row.size) }}
					</template>
				</el-table-column>
				<el-table-column prop="invoiceType" label="发票类型" align="center" show-overflow="title" width="110">
					<template #default="scope">
						{{
							$dictUtils.getDictLabel(
								"invoice_reimbursement_type",
								scope.row.invoiceType,
								"-"
							)
						}}
					</template>
				</el-table-column>
				<el-table-column prop="invoiceProjectName" label="发票项目名" align="center" width="200" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input maxlength="50" readonly="true" v-model="scope.row.invoiceProjectName"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="number" label="发票号" align="center" width="250" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input oninput="value=value.replace(/\D|^/g,'')" readonly="true" maxlength="30"
							@change="isExict(scope.row)" v-model="scope.row.number"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="invoiceDate" label="开票日期" align="center" width="110" :edit-render="{}"
					show-overflow="title">
					<template v-slot:edit="scope">
						<el-input v-model="scope.row.invoiceDate" readonly="true" type="date" transfer
							placeholder="请选择日期"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="invoiceUnit" label="开票单位" align="center" width="200" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input maxlength="50" readonly="true" v-model="scope.row.invoiceUnit"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="buyerName" label="购买方名称" align="center" width="200" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input maxlength="50" readonly="true" v-model="scope.row.buyerName"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="amount" label="金额" align="center" width="120" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input maxlength="15" readonly="true" v-model="scope.row.amount"
							@input="scope.row.amount = twoDecimalPlaces(scope.row.amount)"
							@change="countAmount(scope.row)"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="taxAmount" label="税额" align="center" width="120" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input maxlength="15" readonly="true" v-model="scope.row.taxAmount"
							@input="scope.row.taxAmount = twoDecimalPlaces(scope.row.taxAmount)"
							@change="countAmount(scope.row)"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="count" label="价税合计" align="center" width="120" :edit-render="{}"
					show-overflow="title">
					<template #edit="scope">
						<el-input disabled="true" v-model="scope.row.count"></el-input>
					</template>
				</el-table-column>
				<el-table-column v-if="isConfirm == 1 || isConfirm == 2" prop="confirmStatus" label="确认状态"
					align="center" width="120" :edit-render="{}" show-overflow="title">
					<template #default="scope">
						<el-tag v-if="scope.row.confirmStatus == '1'" type="success">已确认</el-tag>
						<el-tag v-if="!scope.row.confirmStatus || scope.row.confirmStatus == '0'"
							type="danger">未确认</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200px" fixed="right" align="center">
					<template #default="scope">
						<el-form inline :disabled="false" style="display: inline-block;">
							<el-button
								v-if="isConfirm == 1 && (!scope.row.confirmStatus || scope.row.confirmStatus == '0')"
								text type="primary" key="btn01" icon="el-icon-check" size="small"
								@click="changeStatus(scope.row, '1')" style="margin-right: 12px;">确认</el-button>
							<el-button v-if="isConfirm == 1 && scope.row.confirmStatus == '1'" text type="danger"
								key="btn02" icon="el-icon-close" size="small"
								@click="changeStatus(scope.row, '0')">取消确认</el-button>
							<el-button style="margin-right: 12px;" text type="primary" key="01" icon="el-icon-download"
								size="small" @click="toHref(scope.row)">下载</el-button>
						</el-form>
						<el-button text type="primary" key="02" icon="el-icon-delete" size="small"
							@click="deleteFileById(scope.row, scope.$index, this.dataListNew)"
							:disabled="auth === 'view' && delFlag === false && createBy !== scope.row.createBy.name">删除</el-button>

					</template>
				</el-table-column>
			</el-table>
		</div>
		<!--    <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="[url]" :zIndex=9999></el-image-viewer>-->
	</div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import OSSSerivce, {
	httpRequest,
	// eslint-disable-next-line no-unused-vars
	handleRemove,
	fileNameInvoice,
	// eslint-disable-next-line no-unused-vars
	beforeAvatarUpload,
	exnameFix,
	// eslint-disable-next-line no-unused-vars
	openWindowOnUrl,
	// eslint-disable-next-line no-unused-vars
	toHref
} from '@/api/sys/OSSService'
// import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import moment from 'moment'
import Sortable from 'sortablejs';

export default {
	data() {
		return {
			isConfirm: 0,//1:为主任审批，需要确认发票。2:为财务审批，无需确认
			uploadKey: '',
			progressFlag: false,
			loadProgress: 0,
			fileList: [],
			dataList: [],
			oldDataList: [],
			dataListNew: [],
			url: '',
			showViewer: false,
			ossService: null,
			auth: '',
			directory: 'public',
			maxValue: 300,
			tableKey: '',
			fileLoading: true,
			dividerName: '',
			uploadFlag: false,
			delFlag: false,
			createBy: '',
			showDivider: true,
			loading: false,
			dataListLength: '',
			uploadDelFlag: false,
			// reNumFiles: [], // 存储重复发票号
			toCompany: '', //用于区分属于哪个公司的数电发票,
			motorFileLabel: [
				"BasicInformationTotalTaxincludedAmount",
				"BasicInformationTotalTaxAm",
				"SpecificInformationMotorVehicleSalesVehicleModel"
			],
			fileLabel: [
				"BasicInformationTotalTaxAm",//税额
				"IssueTime",//
				"IssuItemInformationTaxRate",//
				// "IssuItemInformationTaxClassificationCode",
				// "IssuItemInformationQuantity",
				"InherentLabelEInvoiceTypeLabelName",//
				// "InherentLabelInIssuTypeLabelName",
				"SellerInformationSellerName",//开票单位
				// "IssuItemInformationAmount",
				// "InherentLabelTaxpayerTypeLabelCode",
				"BuyerInformationBuyerIdNum",//
				"BasicInformationTotalTaxincludedAmount",//合计
				// "Version",
				"InherentLabelGeneralOrSpecialVATLabelName",//发票类型
				"BasicInformationRequestTime",//
				"BasicInformationTotalTaxincludedAmountInChinese",//
				// "UndefinedLabelLabelLabelName",
				"IssuItemInformationTotaltaxIncludedAmount",//
				"InvoiceNumber",// 发票号
				// "TaxBureauCode",
				"IssuItemInformationComTaxAm", //
				// "EIid",
				"IssuItemInformationItemName",//项目名
				//"SellerInformationSellerBankName",//
				"BasicInformationDrawer",//
				// "UndefinedLabelLabelLabelCode",
				// "IssuItemInformationUnPrice",
				"UndefinedLabelLabelLabelType",
				"BuyerInformationBuyerName",//购买方
				// "SellerInformationSellerAddr",
				"BasicInformationTotalAmWithoutTax",//金额
				//"SellerInformationSellerBankAccNum",//
				"InherentLabelEInvoiceTypeLabelCode",//
				"InherentLabelInIssuTypeLabelCode",
				//"SellerInformationSellerTelNum",//
				// "AdditionalInformationRemark",
				// "IssuItemInformationMeaUnits",
				// "EInvoiceTag",
				// "InherentLabelTaxpayerTypeLabelName",
				"InherentLabelGeneralOrSpecialVATLabelCode",//
				// "SellerInformationSellerIdNum",
				// "IssuItemInformationSpecMod",
				// "TaxBureauName"

			],
			uniqueId: "",
			allFiles: [],
			hasUploading: false,
			invoiceNoSet: new Set(), // 已存在的发票号
		}
	},
	watch: {
		dataListNew: {
			handler(val) {
			},
			deep: true,
			immediate: true
		}
	},
	created() {
		this.ossService = new OSSSerivce()
	},
	computed: {
		allStatus() {
			return this.dataListNew.length > 0 && this.dataListNew.every(item => item.confirmStatus == 1);
		},
	},
	components: {
		// ElImageViewer
	},
	mounted() {
		window.onPreview = this.onPreview
	},
	methods: {
		/**
		 * dividerName: 组件中divider的名称赋值
		 * showDivider: ‘附件‘Divider是否展示
		 *     注：值为空时，默认值为true
		 *    showDivider=false时 ‘附件‘Divider隐藏
		 **/
		setDividerName(dividerName, showDivider) {
			if (this.commonJS.isNotEmpty(dividerName)) {
				this.dividerName = dividerName
			}
			if (this.commonJS.isNotEmpty(showDivider)) {
				if (showDivider === false) {
					this.showDivider = false
				} else {
					this.showDivider = true
				}
			} else {
				this.showDivider = true
			}
		},
		/**
		 * 文件上传组件初始化
		 * @param auth
		 *    auth的值为"view"时,不可上传/编辑文件
		 *    auth为其他值时,可上传/编辑文件
		 * @param fileList  要显示到文件上传列表中的文件。
		 *    注：文件必须要有url属性并且文件的url属性值必须是在oss中的路径值
		 *    例：'/attachment-file/xxx/xxx/2022/9/08/xxx.jpg'
		 * @param directory  要存放到oss的哪个文件夹下。
		 *    注：值为空时，默认存放到"public"文件夹
		 * @param maxValue  上传文件允许的最大值，单位：MB
		 *    注：值为空时，默认值为300MB
		 * @param dividerName  组件中divider的名称
		 *    注：值为空时，默认值为‘附件’
		 * @param uploadFlag  ‘上传文件’按钮是否禁用
		 *    注：值为空时，默认值为false
		 *    auth=view&&uploadFlag=false时 ‘上传文件’按钮禁用
		 * @param delFlag  ‘删除’按钮是否禁用
		 *    注：值为空时，默认值为false
		 *    auth=view&&delFlag=false时 ‘删除’按钮禁用
		 * @param showDivider  ‘附件‘Divider是否展示
		 *    注：值为空时，默认值为true
		 *    showDivider=false时 ‘附件‘Divider隐藏
		 *         * @param toCompany  ‘动态区分属于那个公司
		 *    注：值为空时，默认值为 '江苏兴光项目管理有限公司'
		 *
		 *
		 */
		async newUpload(auth, fileList, directory, maxValue, dividerName, uploadFlag, delFlag, showDivider, toCompany, uniqueId) {
			this.loading = true
			this.$emit('changeLoading', true)
			this.uploadKey = Math.random()
			await this.fileLoadingFalse()
			if (this.commonJS.isEmpty(fileList)) {
				fileList = []
				this.fileLoading = true
			} else {
				const tempFiles = fileList.filter(item => item.remarks == uniqueId);
				this.dataListLength = tempFiles.length
				// this.allFiles = fileList
			}
			if (this.commonJS.isEmpty(dividerName)) {
				this.dividerName = '数电发票信息'
			} else {
				this.dividerName = dividerName
			}

			if (this.commonJS.isEmpty(toCompany)) {
				this.toCompany = '江苏兴光会计师事务所有限责任公司'
			} else {
				//对公司名中的括号进行转化,便于与附件中的公司名进行比较
				toCompany = toCompany
					.replace(/（/g, '(')
					.replace(/）/g, ')');
				this.toCompany = toCompany
			}
			if (directory !== undefined && directory !== null && directory !== '' && directory !== {}) {
				this.directory = directory
			} else {
				this.directory = 'public'
			}
			if (maxValue !== undefined && maxValue !== null && maxValue !== '' && maxValue !== 0) {
				this.maxValue = maxValue
			} else {
				this.maxValue = 300
			}
			this.auth = auth
			if (this.commonJS.isEmpty(uploadFlag)) {
				this.uploadFlag = false
			} else {
				if (uploadFlag !== true && uploadFlag !== false) {
					this.uploadFlag = false
				} else {
					this.uploadFlag = uploadFlag
				}
			}
			if (this.commonJS.isEmpty(delFlag)) {
				this.delFlag = false
			} else {
				if (delFlag !== true && delFlag !== false) {
					this.delFlag = false
					this.createBy = delFlag
				} else {
					this.delFlag = delFlag
				}
			}

			if (this.commonJS.isNotEmpty(uniqueId)) {
				this.uniqueId = uniqueId
			}
			this.oldDataList = []

			const filtered = fileList.filter(item => item.remarks === uniqueId)

			filtered.forEach(item => {
				this.invoiceNoSet.add(item.number)
			})

			this.dataList = filtered
			this.oldDataList = [...filtered]
			this.dataListNew = [...filtered]
			this.fileLoading = true
			// 防止数据未更新完成，用户操作上传

			this.loading = false
			this.$emit('changeLoading', false)
			// this.dataList = JSON.parse(JSON.stringify(fileList))
			// this.dataListNew = JSON.parse(JSON.stringify(fileList))
			if (this.commonJS.isEmpty(showDivider)) {
				this.showDivider = true
			} else {
				if (showDivider === false) {
					this.showDivider = false
				} else {
					this.showDivider = true
				}
			}

			// 如果是综合管理部主任或者发票上传本人，可以拖拽发票顺序

			if (this.isConfirm == 1 || this.isConfirm == 4) {
				const tbody = this.$refs.uploadTable.$el.querySelector('.el-table__body-wrapper tbody');
				Sortable.create(tbody, {
					group: 'shared',
					animation: 150,
					ghostClass: 'sortable-ghost', //拖拽样式
					easing: 'cubic-bezier(1, 0, 0, 1)',
					onStart: (item) => {
						console.log(item);
					},
					// 结束拖动事件
					onEnd: (item) => {
						this.setNodeSort(item.oldIndex, item.newIndex)
					},
				})
			}
		},
		setNodeSort(oldIndex, newIndex, type) {
			if (type == 'init') {
				// 初始化给sort
				this.dataListNew.forEach((item, index) => {
					item.sort = index + 1
				});
				return
			}
			// 使用arr复制一份表格数组数据
			const arr = this.dataListNew;
			const currentRow = arr.splice(oldIndex, 1)[0]
			arr.splice(newIndex, 0, currentRow)
			// 原数组置空
			this.dataListNew = [];
			this.$nextTick(async () => {
				this.dataListNew = arr;
				this.dataListNew.forEach((item, index) => {
					item.sort = index + 1
				});
				this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
			});
		},
		async httpRequest(file) {
			await httpRequest(file, fileNameInvoice(file), this.directory, this.maxValue)
		},
		handleSuccessUpload(response, file, fileList) {
		},
		async beforeUpload(file) {
			this.changeLoading(true)
			if (this.uploadDelFlag) {
				this.$message.warning('该文件已上传，请勿重复上传');
				this.uploadKey = Math.random()
				return false; // 取消上传
			} else {
				// 文件大小检查
				if (!beforeAvatarUpload(file, this.dataListNew, this.maxValue)) {
					this.$message.error('文件大小不能超过 ' + this.maxValue + ' MB!');
					this.changeLoading(false)
					return false;
				}
				// 对文件进行判定
				const isXml = file.type === 'text/xml'; // 假设只接受 XML 文件
				if (!isXml) {
					this.$message.error('只能上传 XML 文件');
					this.changeLoading(false)
					return false; // 取消上传
				}

				const formBody = new FormData()
				formBody.append('file', file)
				let fileData
				try {
					// 后端解析
					fileData = await this.ossService.disposeXmlFile(formBody)
				} catch (e) {
					this.$message.error('发票文件解析失败')
					this.changeLoading(false)
					return false
				}

				//判断文件是否重复
				let fileIndex = this.dataList.findIndex(fileItem => {
					return fileItem.number == fileData.InvoiceNumber
				})
				if (fileIndex != -1) {
					if (JSON.stringify(fileData) === "{}") {
						this.$message.warning({ message: `数电发票:${file.name}格式错误` });
						this.changeLoading(false)
						return false
					}

					if (this.commonJS.isNotEmpty(fileData.InvoiceNumber)) {
						this.$message.warning({ message: `数电发票:${file.name + "<br/>发票号：" + fileData.InvoiceNumber}<br/>已经上传，请勿重复上传`, dangerouslyUseHTMLString: true });
						this.changeLoading(false)
						return false
					}
				}

				this.uploadKey = Math.random();

				const fileUrl = file.url;
				// 检查临时 URL 是否有效
				if (fileUrl && fileUrl.trim() !== '') {
					try {
						const temporaryUrl = await this.ossService.getTemporaryUrl(fileUrl);

						if (!temporaryUrl || temporaryUrl.trim() === '') {
							// 如果临时 URL 无效，则标记该文件为无效并删除
							this.$message.warning({ message: `数电发票:${file.name}获取失败，上传失败。` });
							this.changeLoading(false)
							return false
						} else {
							// 如果临时 URL 有效，继续添加文件到有效文件列表
							file.lsUrl = temporaryUrl;
						}
					} catch (error) {
						// 如果临时 URL 获取失败，也标记该文件为无效
						this.$message.warning({ message: `数电发票:${file.name}获取失败，上传失败。` });
						this.changeLoading(false)
						return false
					}
				}

				// 6. 给文件添加上传时间和上传人
				file.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
				file.createBy = {
					id: this.$store.state.user.id,
					name: this.$store.state.user.name,
				};
				if (file !== undefined && file !== null && file !== {}) {
					// 设置文件的 URL
					// 仅处理 XML 文件
					if (file.name && file.name.toLowerCase().endsWith(".xml")) {
						if (JSON.stringify(fileData) === "{}") {
							this.$message.warning({ message: `数电发票:${file.name}格式错误` });
							this.changeLoading(false)
							return false
						}
						if (Object.keys(fileData).length > 0) {
							this.fieldComparison(fileData, this.fileLabel);
							// 检查 data 是否包含 BuyerInformationBuyerName 属性
							if (fileData && 'BuyerInformationBuyerName' in fileData) {
								// 验证是否有效，并进行替换操作
								if (typeof fileData.BuyerInformationBuyerName === 'string') {
									var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
										.replace(/（/g, '(')
										.replace(/）/g, ')');
									fileData.BuyerInformationBuyerName = buyerInformationBuyerName
								}
							}

							if (this.toCompany !== fileData.BuyerInformationBuyerName) {
								this.$message.warning({ message: `仅可上传${this.toCompany}的报销数电发票：<br/>${"文件名: " + file.name + "—— 发票号：" + fileData.InvoiceNumber}<br>上传失败 `, dangerouslyUseHTMLString: true });
								this.changeLoading(false)
								return false
							}
							if (this.commonJS.isNotEmpty(fileData.InvoiceNumber)) {
								var flag = this.invoiceReimbursementDispose(fileData)
								if (flag) {
									this.$message.warning({ message: `数电发票:${file.name + "-" + fileData.InvoiceNumber}<br/>已经上传，请勿重复上传`, dangerouslyUseHTMLString: true });
									this.changeLoading(false)
									return false
								}
								//查询当前发票号是否已经被报销
								let isUsed = await this.ossService.isUsedByInvoiceNumber(fileData.InvoiceNumber);
								if (isUsed) {
									this.$message.warning({ message: `数电发票:${file.name + "<br/> 发票号：" + fileData.InvoiceNumber}<br/>已经发起或已完成报销,无法重复报销`, dangerouslyUseHTMLString: true });
									this.changeLoading(false)
									return false
								}
								let inDate = this.formatDate(fileData.IssueTime)
								if (inDate.indexOf("NaN") != -1 && this.commonJS.isNotEmpty(inDate)) {
									this.$message.warning({ message: `数电发票:${file.name + "<br/> 发票号：" + fileData.InvoiceNumber}<br/>日期格式错误，上传失败。`, dangerouslyUseHTMLString: true });
									this.changeLoading(false)
									return false
								}
							}

						}
					}
				}
				file.fileData = fileData;
				return true
			}
		},
		uploadVideoProcess(event, file, fileList) {
			this.progressFlag = true // 显示进度条
			this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
			if (this.loadProgress >= 100) {
				this.loadProgress = 100
				setTimeout(() => {
					this.progressFlag = false
				}, 1000) // 一秒后关闭进度条
			}
		},
		invoiceReimbursementDisposeData(fileData, file) {
			var invoiceReimbursements = this.dataListNew;
			//创建判断值，若行信息存在相同的发票号，则进行数据检查调整，若不存在发票号，则新增行，并将信息写入
			var includeFlag = false;
			if (!invoiceReimbursements) {
				invoiceReimbursements = [];
			}
			if (this.toCompany === fileData.BuyerInformationBuyerName) {
				// 生成个随机数

				// const fileBody = new FormData();
				// fileBody.append('file', file.raw);
				// const fileData = await this.ossService.disposeXmlFile(fileBody);
				// if (data.InvoiceNumber === fileData.InvoiceNumber) {
				file.invoiceType = fileData.InherentLabelGeneralOrSpecialVATLabelCode;
				file.invoiceProjectName = fileData.IssuItemInformationItemName;
				file.number = fileData.InvoiceNumber;
				file.invoiceDate = this.formatDate(fileData.IssueTime);
				file.invoiceUnit = fileData.SellerInformationSellerName;
				file.amount = fileData.BasicInformationTotalAmWithoutTax;
				file.taxAmount = fileData.BasicInformationTotalTaxAm;
				file.count = fileData.BasicInformationTotalTaxincludedAmount;
				file.buyerName = fileData.BuyerInformationBuyerName;
				// }


				this.$emit("handleCount", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
				this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)

			}
		},
		formatDate(date) {
			// 正则表达式匹配 "xxx年x月x日" 格式的日期
			const regex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
			const matches = date.match(regex);
			const parts = date.split('/');

			if (matches) {
				const year = matches[1];  // 年
				const month = String(matches[2]).padStart(2, '0');  // 月，确保是两位数
				const day = String(matches[3]).padStart(2, '0');  // 日，确保是两位数
				return `${year}-${month}-${day}`;  // 返回 yyyy-mm-dd 格式的日期
			} else if (parts.length === 3) {
				const year = parts[0];  // 年份
				const month = String(parts[1]).padStart(2, '0');  // 月，确保是两位数
				const day = String(parts[2]).padStart(2, '0');  // 日，确保是两位数
				return `${year}-${month}-${day}`;  // 返回 yyyy-mm-dd 格式的日期
			} else {
				const d = new Date(date);
				const year = d.getFullYear();
				const month = String(d.getMonth() + 1).padStart(2, '0'); // 获取月份并确保是两位数
				const day = String(d.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
				return `${year}-${month}-${day}`;
			}

		},
		getSize(value) {

			if (this.commonJS.isEmpty(value)) {
				return '0 B'
			} else {
				let val = parseInt(value)
				if (this.commonJS.isEmpty(val)) {
					return '0 B'
				}
				if (isNaN(val)) {
					return '0 B'
				}
				if (val === 0) {
					return '0 B'
				}
				let k = 1024
				let sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
				let i = Math.floor(Math.log(val) / Math.log(k))
				let result = val / Math.pow(k, i);
				let kb = parseFloat(result.toPrecision(3));
				return kb + '' + sizes[i]
			}
		},
		async changes(file, fileList) {
			// 防止上传多次触发changes
			if (file.status == 'ready' || file.status == 'uploading') return //阻止上传多次触发changes

			// 检查是否有文件正在上传
			this.hasUploading = fileList.some(f =>
				f.status === 'ready' || f.status === 'uploading'
			)
			if (!this.hasUploading) {
				this.$emit('changeLoading', false)
				this.loading = false
			} else {
				this.$emit('changeLoading', this.hasUploading)
				this.loading = this.hasUploading
			}

			try {

				let fileData = file.raw.fileData
				// 6. 给文件添加上传时间和上传人
				file.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
				file.createBy = {
					id: this.$store.state.user.id,
					name: this.$store.state.user.name,
				};
				let obj = this.dataList.find(tempFile => {
					return tempFile.number == fileData.InvoiceNumber
				})
				if (obj) {
					this.$message.warning({ message: `数电发票:${file.name}<br/>已经上传，请勿重复上传`, dangerouslyUseHTMLString: true });
					return
				}

				// 发票号赋值给文件
				file.remarks = this.uniqueId
				file.number = fileData.InvoiceNumber
				// 将新符合条件的文件追加到原文件列表上
				this.dataListNew.push(file)
				this.fileList.push(file)
				this.dataList = this.dataListNew

				if (fileData.InvoiceNumber == file.number) {
					// 如果 file.raw 存在且有效
					if (file.raw !== undefined && file.raw !== null && file.raw !== {}) {
						// 设置文件的 URL
						file.url = file.raw.url;

						// 仅处理 XML 文件
						if (file.raw.name && file.raw.name.toLowerCase().endsWith(".xml")) {
							// 创建 FormData 对象并发送文件
							try {
								// 调用后端接口解析 XML 文件
								if (fileData && 'BuyerInformationBuyerName' in fileData) {
									this.fieldComparison(fileData, this.fileLabel);
									// 验证是否有效，并进行替换操作
									if (typeof fileData.BuyerInformationBuyerName === 'string') {
										var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
											.replace(/（/g, '(')
											.replace(/）/g, ')');
										fileData.BuyerInformationBuyerName = buyerInformationBuyerName
									}
								}

								if (Object.keys(fileData).length > 0) {
									// 解析成功，更新数据行
									this.invoiceReimbursementDisposeData(fileData, file);
								}

							} catch (error) {
								this.$message.error('处理 XML 文件失败');
								console.log('XML 处理失败', error);
							}
						}
					}
				}


				// 清空 fileList，如果 fileList 不为空
				if (fileList && fileList.length > 0) {
					this.fileList = [];
				}
				// 综合管理部主任或者发票上传本人，可以拖拽发票顺序
				if (this.isConfirm == 1 || this.isConfirm == 4) {
					const tbody = this.$refs.uploadTable.$el.querySelector('.el-table__body-wrapper tbody');
					Sortable.create(tbody, {
						group: 'shared',
						animation: 150,
						ghostClass: 'sortable-ghost', //拖拽样式
						easing: 'cubic-bezier(1, 0, 0, 1)',
						onStart: (item) => {
							console.log(item);
						},
						// 结束拖动事件
						onEnd: (item) => {
							this.setNodeSort(item.oldIndex, item.newIndex)
						},
					})
				}
				// 👇 初始化时主动触发一次
				this.setNodeSort(null, null, 'init');
				// 在 changes 完成后，手动调用 handleUploadSuccess
				// await this.handleUploadSuccess(null, fileData, this.fileList);  // 传入空参数或实际参数

			} catch (error) {
				this.$message.error({
					message: `上传出错，${error.message}`
				})
			}
		},
		// 处理返回结果字段大小写问题
		capitalizeKeys(obj) {
			return Object.entries(obj).reduce((acc, [key, value]) => {
				let newKey = key.charAt(0).toUpperCase() + key.slice(1);
				acc[newKey] = value;
				return acc;
			}, {});
		},
		fieldComparison(obj, fields) {
			let labelCode = obj["InherentLabelGeneralOrSpecialVATLabelCode"]
			// 处理机动车销售统一发票
			if (labelCode == '03') {
				obj.IssuItemInformationTaxRate = ""
				obj.IssuItemInformationTotaltaxIncludedAmount = obj.BasicInformationTotalTaxincludedAmount
				obj.IssuItemInformationComTaxAm = obj.BasicInformationTotalTaxAm
				obj.IssuItemInformationItemName = obj.SpecificInformationMotorVehicleSalesVehicleModel
			}
			//--------------------------
			if (labelCode == '02') {
				if (!obj.IssuItemInformationComTaxAm) {
					obj.IssuItemInformationComTaxAm = 0
				}
			}
			// 遍历字段数组，检查每个字段名是否在对象中存在
			for (let field of fields) {
				// 忽略大小写来匹配属性名
				const fieldPattern = new RegExp(`^${field}$`, 'i');
				const matchedKeys = Object.keys(obj).filter(key => fieldPattern.test(key));

				// 如果没有找到匹配的字段，抛出错误
				if (matchedKeys.length === 0) {
					if (!field.includes("UndefinedLabel")) {
						throw new Error(`未找到发票字段: ${field}，请核对XML文件`)
					}
				}
				// 替换属性名
				for (let key of matchedKeys) {
					if (!field.includes("UndefinedLabel")) {
						if (key !== field) {
							obj[field] = obj[key];
							delete obj[key];
						}
					}
				}

			}
		},
		async handleUploadSuccess(response, fileData, fileList) {

			// 遍历当前的数据列表
			if (this.dataListNew.length > 0) {
				for (let item of this.dataListNew) {
					if (fileData.InvoiceNumber == item.number) {
						// 如果 item.raw 存在且有效
						if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
							// 设置文件的 URL
							item.url = item.raw.url;

							// 仅处理 XML 文件
							if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
								// 创建 FormData 对象并发送文件
								try {
									// 调用后端接口解析 XML 文件
									if (fileData && 'BuyerInformationBuyerName' in fileData) {
										this.fieldComparison(fileData, this.fileLabel);
										// 验证是否有效，并进行替换操作
										if (typeof fileData.BuyerInformationBuyerName === 'string') {
											var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
												.replace(/（/g, '(')
												.replace(/）/g, ')');
											fileData.BuyerInformationBuyerName = buyerInformationBuyerName
										}
									}

									if (Object.keys(fileData).length > 0) {
										// 解析成功，更新数据行
										await this.invoiceReimbursementDisposeData(fileData, item);
									}

								} catch (error) {
									this.$message.error('处理 XML 文件失败');
									console.log('XML 处理失败', error);
								}
							}
						}
					}

				}

				// 更新表格数据
				this.$nextTick(() => {
					this.$forceUpdate(); // 强制更新表格
				});
			}

		},
		invoiceReimbursementDispose(data) {
			var invoiceReimbursements = this.dataList;
			//创建判断值，若行信息存在相同的发票号，则进行数据检查调整，若不存在发票号，则新增行，并将信息写入
			var includeFlag = false;
			if (!invoiceReimbursements) {
				invoiceReimbursements = [];
			}

			invoiceReimbursements.forEach(item => {
				if (item.number === data.InvoiceNumber) {
					includeFlag = true;
				}
			})
			return includeFlag;
		},
		async showFile(row) {
			let res = await this.ossService.getFileSizeByUrl(row.url)
			if (res.url) {
				row.lsUrl = res.url
				row.size = res.size
				openWindowOnUrl(row)
			}
		},
		onPreview(url) {
			this.url = url
			this.showViewer = true
		},
		// 关闭查看器
		closeViewer() {
			this.url = ''
			this.showViewer = false
		},
		async toHref(row) {
			let res = await this.ossService.getFileSizeByUrl(row.url)
			if (res.url) {
				row.lsUrl = res.url
				row.size = res.size
				toHref(row)
			}
		},
		async deleteById(row, index, fileList) {
			// this.$refs.upload.handleRemove(this.dataListNew[index])
			await this.dataListNew.splice(index, 1)
			await this.dataList.splice(index, 1)
			// if (this.commonJS.isNotEmpty(row.id)) {
			//   this.ossService.deleteMsgById(row.id)
			// }
			var newFileList = [];
			for (var i = 0; i < fileList.length; i++) {
				if (fileList[i].name !== row.name) {
					newFileList.push(fileList[i])
				}
			}
			this.fileList = newFileList;
			this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)

		},
		deleteFileById(row, index, fileList) {
			this.invoiceNoSet.delete(row.number)
			// this.$refs.upload.handleRemove(this.dataListNew[index])
			this.dataListNew.splice(index, 1)


			this.dataList = this.dataListNew
			// if (this.commonJS.isNotEmpty(row.id)) {
			// 	this.ossService.deleteMsgById(row.id)
			// }
			// var newFileList = [];
			// for (var i = 0; i < this.dataListNew.length; i++) {
			// 	if (this.dataListNew[i].name !== row.name) {
			// 		newFileList.push(this.dataListNew[i])
			// 	}
			// }

			// this.fileList = newFileList;
			// 更新表格数据
			this.$nextTick(() => {
				this.$forceUpdate(); // 强制更新表格
			});
			this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
			this.$emit("handleDelete", row, this.uniqueId)
		},
		/**
		 * 关闭dialog时使用  清除el-upload中上传的文件
		 */
		clearUpload() {
			this.fileList = []//用于清除上传文件的缓存
			this.$refs.upload.clearFiles()
			this.dataList = []
			this.dataListNew = []
			this.createBy = ''
		},
		/**
		 * 获取当前文件列表中的文件数据
		 */
		getDataList() {
			return this.dataListNew
		},
		/**
		 * 判断进度条是否结束，附件是否加载完成
		 * @returns {boolean}
		 */
		checkProgress() {
			if (this.progressFlag === true) {
				this.$message.warning('请等待附件上传完成再进行操作')
				return true
			}
			if (this.hasUploading === true) {
				this.$message.warning('请等待附件上传完成再进行操作')
				return true
			}
			if (this.fileLoading === false) {
				this.$message.warning('请等待附件加载完成再进行操作')
				if (this.dataListLength === this.dataListNew.length) {
					this.fileLoading = true
				}
				return true
			}
			return false
		},
		ifName(row) {
			if (this.commonJS.isEmpty(row.name)) {
				row.name = '---'
				return false
			}
			let suffix = row.name.substring(row.name.lastIndexOf('.') + 1)
			if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
				return true
			} else {
				return false
			}
		},
		fileLoadingFalse() {
			this.fileLoading = false
		},
		// 开启/关闭页面的加载中状态
		changeLoading(loading) {
			this.$emit('changeLoading', loading)
			this.loading = loading
		},
		getSummaries(param) {
			const { columns, data } = param;

			// 初始化汇总数组
			const sums = [];

			// 遍历列
			columns.forEach((column, index) => {
				if (index === 0) {
					// 第一列（通常是序号列），我们不需要进行汇总，直接设置为“汇总”
					sums[index] = '汇总';
				}
				if (column.property === 'amount') {
					// 如果当前列是 'amount'，进行汇总
					const values = data.map((item) => Number(item[column.property]));
					sums[index] = this.formatNumber(values.reduce((prev, curr) => {
						return prev + curr;  // 汇总价税合计列
					}, 0));
				}
				if (column.property === 'taxAmount') {
					// 如果当前列是 'amount'，进行汇总
					const values = data.map((item) => Number(item[column.property]));
					sums[index] = this.formatNumber(values.reduce((prev, curr) => {
						return prev + curr;  // 汇总价税合计列
					}, 0));
				}
				if (column.property === 'count') {
					// 如果当前列是 'amount'，进行汇总
					const values = data.map((item) => Number(item[column.property]));
					sums[index] = this.formatNumber(values.reduce((prev, curr) => {
						return prev + curr;  // 汇总价税合计列
					}, 0));
				}
			});

			return sums;
		},

		formatNumber(number) {
			return number.toFixed(2);  // 保留两位小数，返回字符串
		},
		changeStatus(row, status) {
			row.confirmStatus = status;
			this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
		},
		tableRowClassName({ row, rowIndex }) {
			if (this.isConfirm == 1 || this.isConfirm == 2) {
				if (row.confirmStatus == "1") {
					return 'warning-row';
				} else {
					return '';
				}
			} else {
				return '';
			}
		},
		allSelect(status) {
			this.dataListNew.forEach(item => {
				item.confirmStatus = status
			})
		}
	}
}
</script>
<style scoped lang="scss">
::v-deep .el-table {
	.warning-row {
		background: #ffe9c0 !important;
	}

	// 滚动条的宽度
	.el-scrollbar__bar {
		height: 16px; // 横向滚动条
	}


	.el-table__footer-wrapper tbody td.el-table__cell,
	.el-table__header-wrapper tbody td.el-table__cell {
		background-color: #fff;
		/* 设置背景颜色与表格一致 */

	}

	/* 设置汇总行的背景颜色与表格一致 */
	.el-table__footer {
		background-color: #fff;
		/* 设置背景颜色与表格一致 */

	}

	/* 让第一列的汇总居中 */
	.el-table__footer .el-table__cell:nth-child(1) {
		text-align: center;
		/* 让第一列居中 */
		font-weight: bold;
		/* 可以根据需要加粗 */
	}
}



.el-divider__text {
	font-size: 16px;
	font-weight: bold;
}
</style>
<style></style>
