<!--文件上传组件-->
<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" :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-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
        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 label="操作" width="200px" fixed="right" align="center">
          <template  #default="scope">
            <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 {
		  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,
		  uploadingCount: 0, // 记录当前正在上传的文件数量
		  totalCount: 0, // 记录总的文件数量
		  duplicateFileNames: [], // 存储重复文件名
		  noXmlFiles: [], // 存储非当前公司的文件名
		  // reNumFiles: [], // 存储重复发票号
		  toCompany:'', //用于区分属于哪个公司的数电发票,
      }
    },
    watch: {
    },
    created () {
      this.ossService = new OSSSerivce()
    },
    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)
      },
		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) {
			this.uploadKey = Math.random();

			// 用来存放没有重复且有有效URL的文件，准备上传
			let filesToUpload = [];
			let validFiles = [];

			// 用于存储已经上传的文件 `lastModified` + `size` 作为唯一标识
			let uploadedFileIdentifiers = new Set();
			for (let existingFile of this.dataListNew) {
				const existingFileName = existingFile.name; // 假设每个文件有 `name` 属性
				uploadedFileIdentifiers.add(existingFileName); // 将已有文件的名称添加到 Set 中
			}

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

			// 3. 验证文件是否重复（使用 `lastModified` 和 `size` 来判断）
			for (let item of fileList) {
				const fileName = item.raw ? item.raw.name : item.name;
				const fileIdentifier = fileName; // 唯一标识：文件大小 + 修改时间

				// 检查该文件标识是否已存在
				if (uploadedFileIdentifiers.has(fileIdentifier)) {
					// 记录重复文件名
					const formBody = new FormData();
					formBody.append('file', item.raw);
					const data = await this.ossService.disposeXmlFile(formBody);
					if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
						this.duplicateFileNames.push("文件名: "+fileName +"—— 发票号："+data.InvoiceNumber);
						console.log('222',data.InvoiceNumber)
						console.log('this.duplicateFileNames',this.duplicateFileNames)
					}
				} else {
					// 文件没有重复，加入上传列表
					filesToUpload.push(item);
					uploadedFileIdentifiers.add(fileIdentifier); // 将文件标识加入已上传集合
				}
			}

			// 4. 如果没有文件需要上传，则直接返回
			// if (filesToUpload.length === 0) return;

			// 5. 删除无效URL的文件
			let invalidFiles = []; // 用于存储需要删除的文件

			// 使用异步操作来判断文件URL的有效性
			for (let item of filesToUpload) {
				const fileUrl = item.raw ? item.raw.url : item.url;

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

						if (!temporaryUrl || temporaryUrl.trim() === '') {
							// 如果临时 URL 无效，则标记该文件为无效并删除
							invalidFiles.push(item);
						} else {
							// 如果临时 URL 有效，继续添加文件到有效文件列表
							validFiles.push(item);
							item.lsUrl = temporaryUrl;
						}
					} catch (error) {
						// 如果临时 URL 获取失败，也标记该文件为无效
						invalidFiles.push(item);
					}
				}
			}

			filesToUpload = validFiles; // 只保留有效的文件

			// 6. 给文件添加上传时间和上传人
			for (let item of filesToUpload) {
				item.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
				item.createBy = {
					id: this.$store.state.user.id,
					name: this.$store.state.user.name,
				};
			}

			const validCompanyFiles = [];//存放符合公司的文件
			let errorFiles = [];//存放数据格式错误的文件
			let errorDateFiles = [];//存放日期格式错误的文件
			let isUsedFiles = [];//存放已经被报销的文件
			for (let i = 0; i < filesToUpload.length; i++) {
				const item = filesToUpload[i];
				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);
						// 调用后端接口解析 XML 文件
						const data = await this.ossService.disposeXmlFile(formBody);
						if (Object.keys(data).length > 0) {
							// 如果文件的公司名称与this.toCompany不一致，则删除该文件

							// 检查 data 是否包含 BuyerInformationBuyerName 属性
							if (data && 'BuyerInformationBuyerName' in data) {
								// 验证是否有效，并进行替换操作
								if (typeof data.BuyerInformationBuyerName === 'string') {
									var buyerInformationBuyerName = data.BuyerInformationBuyerName
										.replace(/（/g, '(')
										.replace(/）/g, ')');
									data.BuyerInformationBuyerName = buyerInformationBuyerName
								}
							}

							if (this.toCompany !== data.BuyerInformationBuyerName) {
								this.noXmlFiles.push("文件名: "+item.raw.name +"—— 发票号："+data.InvoiceNumber)
								// this.$message.warning("仅可上传江苏兴光项目管理有限公司的报销数电发票");
								continue;
							}
							if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
								var flag = this.invoiceReimbursementDispose(data)
								if (flag){
										this.duplicateFileNames.push(item.raw.name +"-"+data.InvoiceNumber)
										continue;
								}
								//查询当前发票号是否已经被报销
								let isUsed = await this.ossService.isUsedByInvoiceNumber(data.InvoiceNumber);
								if (isUsed){
									isUsedFiles.push("文件名: "+item.raw.name +"—— 发票号："+data.InvoiceNumber)
									continue;
								}
								let inDate = this.formatDate(data.IssueTime)
								if (inDate.indexOf("NaN") != -1 && this.commonJS.isNotEmpty(inDate)){
									errorDateFiles.push("文件名: "+item.raw.name +"—— 发票号："+data.InvoiceNumber);
									continue;
								}
								validCompanyFiles.push(item);  // 符合条件的文件
							}

						}
					}
				}
			}
			filesToUpload = validCompanyFiles;
			// 将新符合条件的文件追加到原文件列表上
			this.dataListNew = [...this.dataList, ...filesToUpload];
			this.fileList = [...filesToUpload];
			// 记录上传文件的数量
			this.totalCount = fileList.length;
			//记录changes方法执行了多少次,此处加判定是为了处理防抖,change方法会对每一个文件执行两次,此处判定后只会增加一次
			if (file.status !== 'ready'){
				this.uploadingCount++
			}

			// 9. 检查是否是最后一个文件上传，如果是，执行一次去重和提示
			if (this.uploadingCount === this.totalCount) {
				this.duplicateFileNames = [...new Set(this.duplicateFileNames)];
				this.noXmlFiles = [...new Set(this.noXmlFiles)];
				// this.reNumFiles = [...new Set(this.reNumFiles)];
				errorFiles = [...new Set(errorFiles)];
				invalidFiles = [...new Set(invalidFiles)];
				errorDateFiles = [...new Set(errorDateFiles)];
				isUsedFiles = [...new Set(isUsedFiles)];
				// 提示重复文件
				if (this.duplicateFileNames.length > 0) {
					this.$message.warning({message:`以下文件已经上传，请勿重复上传：<br>${this.duplicateFileNames.join('<br>')} `,dangerouslyUseHTMLString: true});
				}
				// 提示xml文件不是当前公司报销的文件
				if (this.noXmlFiles.length > 0) {
					this.$message.warning({message:`仅可上传${this.toCompany}的报销数电发票：<br>${this.noXmlFiles.join('<br>')}<br>上传失败 `,dangerouslyUseHTMLString: true});
				}
				// 提示发票号重复文件
				// if (this.reNumFiles.length > 0) {
				// 	this.$message.error(`发票号:\n${this.reNumFiles.join('\n')}已上传,请勿重复上传`);
				// }
				//数电发票格式错误的文件
				if (errorFiles.length > 0){
					this.$message.warning({message:`上传的数电发票格式错误:<br>${errorFiles.join('<br>')}`,dangerouslyUseHTMLString: true});
				}
				//临时路径错误的文件
				if (invalidFiles.length > 0){
					this.$message.warning({message:`数电发票: <br>${invalidFiles.join('<br>')}<br>获取失败，上传失败。`,dangerouslyUseHTMLString: true});
				}
				//临时路径错误的文件
				if (errorDateFiles.length > 0){
					this.$message.warning({message:`数电发票: <br>${errorDateFiles.join('<br>')}<br>日期格式错误，上传失败。`,dangerouslyUseHTMLString: true});
				}
				//已经被报销的文件
				if (isUsedFiles.length > 0){
					this.$message.warning({message:`数电发票: <br>${isUsedFiles.join('<br>')}<br>已经发起或已完成报销,无法重复报销`,dangerouslyUseHTMLString: true});
				}
				// 重置计数器
				this.uploadingCount = 0;
				this.totalCount = 0; // 可以根据需求来重置
				this.duplicateFileNames = []; // 清空记录
				this.noXmlFiles = []; // 清空记录
				this.reNumFiles = []; // 清空记录
				this.dataList = this.dataListNew
			}
			// 清空 fileList，如果 fileList 不为空
			if (fileList && fileList.length > 0) {
				this.fileList = [];
			}
			// 在 changes 完成后，手动调用 handleUploadSuccess
			await this.handleUploadSuccess(null, null, this.fileList);  // 传入空参数或实际参数
		},


		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 文件
								const data = await this.ossService.disposeXmlFile(formBody);
								console.log(data)
								// 检查 data 是否包含 BuyerInformationBuyerName 属性
								if (data && 'BuyerInformationBuyerName' in data) {
									// 验证是否有效，并进行替换操作
									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);  // 保留两位小数，返回字符串
		},
    }
  }
</script>
<style scoped lang="scss">
	::v-deep .el-table{
		.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>
