<!--文件上传组件-->
<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 :loading="loading" type="primary" size="default" :disabled="true"> 点击上传 </el-button>
				</template>
				<template v-else #trigger>
					<el-button :loading="loading" type="primary" size="default"> 点击上传 </el-button> <span
						style="margin-left: 20px;font-size:14px;font-weight:normal;color:red;" type="primary">
						上传报销的数电发票xml文件</span>
				</template>
			</el-upload>
			<!-- <el-button v-if="this.allStatus && this.isConfirm" type="primary" size="default" style="margin-left: 10px;"
				@click="allSelect('0')">全部取消</el-button>
			<el-button v-if="!this.allStatus && this.isConfirm" type="primary" size="default" style="margin-left: 10px;"
				@click="allSelect('1')">全部确认</el-button> -->
		</el-divider>

		<div style="height: calc(100% - 80px);margin-top: 10px">
			<!-- 进度条 -->
			<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 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="110"></el-table-column>
				<el-table-column label="文件大小" prop="size" align="center">
					<template #default="scope">
						{{ getSize(scope.row.size) }}
					</template>
				</el-table-column>
				<el-table-column prop="invoiceType" label="发票类型" align="center" show-overflow="title">
					<template #default="scope">
						{{
							$dictUtils.getDictLabel(
								"invoice_reimbursement_type",
								scope.row.invoiceType,
								"-"
							)
						}}
					</template>
				</el-table-column>
				<el-table-column prop="invoiceProjectName" label="发票项目名" align="center" width="150" :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="150" :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-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')">确认</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 text type="primary" key="01" icon="el-icon-download" size="small"
							@click="toHref(scope.row)">下载</el-button>
						<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'
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"

			]
		}
	},
	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) {
			this.uploadKey = Math.random()
			await this.fileLoadingFalse()
			if (this.commonJS.isEmpty(fileList)) {
				fileList = []
				this.fileLoading = true
			} else {
				this.dataListLength = fileList.length
			}
			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
				}
			}
			this.oldDataList = []
			for await (let item of fileList) {
				await this.ossService.getFileSizeByUrl(item.url).then((data) => {
					item.lsUrl = data.url
					item.size = data.size
					this.dataList.push(item)
					this.oldDataList.push(item)
					this.dataListNew.push(item)
					if (this.dataListNew.length === fileList.length) {
						this.fileLoading = true
					}
				})
			}
			// 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
				}
			}
		},
		async httpRequest(file) {
			await httpRequest(file, fileNameInvoice(file), this.directory, this.maxValue)
		},
		handleSuccessUpload(response, file, fileList) {
			// console.log(response, file, fileList);


		},
		async beforeUpload(file) {
			if (this.uploadDelFlag) {
				this.$message.warning('该文件已上传，请勿重复上传');
				this.uploadKey = Math.random()

				return false; // 取消上传
			} else {
				// 对文件进行判定
				const isXml = file.type === 'text/xml'; // 假设只接受 XML 文件
				if (!isXml) {
					this.$message.error('只能上传 XML 文件');
					return false; // 取消上传
				}
				// else {
				// try {
				//对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
				// const formBody = new FormData()
				// formBody.append('file', file)
				// await this.ossService.disposeXmlFile(formBody).then((data) => {
				// 	if (JSON.stringify(data) === "{}") {
				// 		this.$message.warning('数电发票:' + file.name + '格式错误');
				// 		this.loading = false;
				// 		// 在验证失败时删除已经添加的行
				// 		const index = this.fileList.findIndex(item => item.name === file.name);
				// 		if (index !== -1) {
				// 			this.deleteFileById(this.fileList[index], index, this.fileList);
				// 		}
				// 	}
				// })
				// } catch (error) {
				// 	console.error(error);
				// }
				// }
				// 其他判定逻辑...
				return true; // 允许上传
			}
		},
		uploadVideoProcess(event, file, fileList) {
			this.progressFlag = true // 显示进度条
			this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
			if (this.loadProgress >= 100) {
				this.loadProgress = 100
				// var fileName = file.raw.name;
				//
				// const spliceLength2 = fileName.lastIndexOf(".");
				// var fileNameSuffix = fileName.slice(spliceLength2 + 1);
				// let lowerFileNameSuffix = fileNameSuffix.toLowerCase();
				// if(lowerFileNameSuffix === "xml" ) {
				// 	//对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
				// 	const formBody = new FormData()
				// 	formBody.append('file', file.raw)
				// 	this.ossService.disposeXmlFile(formBody).then((data) => {
				// 		if(Object.keys(data).length > 0){
				// 			this.invoiceReimbursementDisposeData(data,file)
				// 		} else{
				// 			this.$message.warning('上传的数电发票格式错误')
				// 			this.loading = false;
				// 			// 在验证失败时删除已经添加的行
				// 			const index = this.fileList.findIndex(item => item.name === file.name);
				// 			if (index !== -1) {
				// 				this.deleteFileById(this.fileList[index], index, this.fileList);
				// 			}
				// 		}
				// 	})
				// }
				setTimeout(() => {
					this.progressFlag = false
				}, 1000) // 一秒后关闭进度条
			}
		},
		invoiceReimbursementDisposeData: function (data, file) {
			var invoiceReimbursements = this.dataListNew;
			//创建判断值，若行信息存在相同的发票号，则进行数据检查调整，若不存在发票号，则新增行，并将信息写入
			var includeFlag = false;
			if (!invoiceReimbursements) {
				invoiceReimbursements = [];
			}
			if (this.toCompany === data.BuyerInformationBuyerName) {
				invoiceReimbursements.forEach(item => {
					if (file.name === item.name) {

						item.invoiceType = data.InherentLabelGeneralOrSpecialVATLabelCode;
						item.invoiceProjectName = data.IssuItemInformationItemName;
						item.number = data.InvoiceNumber;
						item.invoiceDate = this.formatDate(data.IssueTime);
						item.invoiceUnit = data.SellerInformationSellerName;
						item.amount = data.BasicInformationTotalAmWithoutTax;
						item.taxAmount = data.BasicInformationTotalTaxAm;
						item.count = data.BasicInformationTotalTaxincludedAmount;
						item.buyerName = data.BuyerInformationBuyerName;
					}

				})
			}
		},
		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) {
			if (file.status == 'ready') return //阻止上传多次触发changes

			try {
				this.uploadKey = Math.random();
				// 2. 文件大小检查
				if (!beforeAvatarUpload(file, fileList, this.maxValue)) {
					this.$message.error('文件大小不能超过 ' + this.maxValue + ' MB!');
					return;
				}

				const fileName = file.raw ? file.raw.name : file.name;
				//判断文件是否重复
				let fileIndex = this.dataList.findIndex(fileItem => {
					return fileItem.name == file.name
				})
				if (fileIndex != -1) {
					// 记录重复文件名
					const formBody = new FormData();
					formBody.append('file', file.raw);
					const data1 = await this.ossService.disposeXmlFile(formBody);

					if (JSON.stringify(data1) === "{}") {
						this.$message.warning({ message: `数电发票:${file.raw.name}格式错误` });
						return
					}

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

				const fileUrl = file.raw ? file.raw.url : 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}获取失败，上传失败。` });
							return
						} else {
							// 如果临时 URL 有效，继续添加文件到有效文件列表
							file.lsUrl = temporaryUrl;
						}
					} catch (error) {
						// 如果临时 URL 获取失败，也标记该文件为无效
						this.$message.warning({ message: `数电发票:${file.name}获取失败，上传失败。` });
						return
					}
				}

				// 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.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 对象并发送文件
						const formBody = new FormData();
						formBody.append('file', file.raw);
						// 调用后端接口解析 XML 文件
						let data2 = await this.ossService.disposeXmlFile(formBody);
						if (JSON.stringify(data2) === "{}") {
							this.$message.warning({ message: `数电发票:${file.raw.name}格式错误` });
							return
						}
						if (Object.keys(data2).length > 0) {
							this.fieldComparison(data2, this.fileLabel);
							// 检查 data 是否包含 BuyerInformationBuyerName 属性
							if (data2 && 'BuyerInformationBuyerName' in data2) {
								// 验证是否有效，并进行替换操作
								if (typeof data2.BuyerInformationBuyerName === 'string') {
									var buyerInformationBuyerName = data2.BuyerInformationBuyerName
										.replace(/（/g, '(')
										.replace(/）/g, ')');
									data2.BuyerInformationBuyerName = buyerInformationBuyerName
								}
							}

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

						}
					}
				}
				// 将新符合条件的文件追加到原文件列表上
				this.dataListNew.push(file)
				this.fileList.push(file)
				this.dataList = this.dataListNew

				// 清空 fileList，如果 fileList 不为空
				if (fileList && fileList.length > 0) {
					this.fileList = [];
				}
				// 在 changes 完成后，手动调用 handleUploadSuccess
				await this.handleUploadSuccess(null, null, 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
			}
			//--------------------------

			// 遍历字段数组，检查每个字段名是否在对象中存在
			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) {
					throw new Error(`未找到发票字段: ${field}，请核对XML文件`)
				}
				// 替换属性名
				for (let key of matchedKeys) {
					if (key !== field) {
						obj[field] = obj[key];
						delete obj[key];
					}
				}

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

			// 遍历当前的数据列表
			if (this.dataListNew.length > 0) {
				for (let item of this.dataListNew) {

					// 如果 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 对象并发送文件
							const formBody = new FormData();
							formBody.append('file', item.raw);

							try {
								// 调用后端接口解析 XML 文件
								let data = await this.ossService.disposeXmlFile(formBody);
								// 检查 data 是否包含 BuyerInformationBuyerName 属性
								if (data && 'BuyerInformationBuyerName' in data) {
									this.fieldComparison(data, this.fileLabel);
									// 验证是否有效，并进行替换操作
									if (typeof data.BuyerInformationBuyerName === 'string') {
										var buyerInformationBuyerName = data.BuyerInformationBuyerName
											.replace(/（/g, '(')
											.replace(/）/g, ')');
										data.BuyerInformationBuyerName = buyerInformationBuyerName
									}
								}

								if (Object.keys(data).length > 0) {
									// 解析成功，更新数据行
									await this.invoiceReimbursementDisposeData(data, item);
								}
								// else {
								// 	// XML 格式错误，删除文件
								// 	this.$message.warning('上传的数电发票格式错误');
								// 	const index = this.fileList.findIndex(f => f.name === item.name);
								// 	if (index !== -1) {
								// 		this.deleteFileById(this.fileList[index], index, this.fileList);
								// 	}
								// }
							} 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;
		},
		showFile(row) {
			openWindowOnUrl(row)
		},
		onPreview(url) {
			this.url = url
			this.showViewer = true
		},
		// 关闭查看器
		closeViewer() {
			this.url = ''
			this.showViewer = false
		},
		toHref(row) {
			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;
		},
		deleteFileById(row, index, fileList) {
			// 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(); // 强制更新表格
			});
		},
		/**
		 * 关闭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.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) {
			if (this.commonJS.isNotEmpty(loading)) {
				this.loading = loading
			} else {
				this.loading = false
			}
		},
		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;
		},
		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>
