NewDigitalInvoiceUploadComponentTest.vue 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. <!--文件上传组件-->
  2. <template>
  3. <div :key="uploadKey">
  4. <!-- <el-divider v-if="showDivider" content-position="left"><i class="el-icon-document"></i> {{ dividerName }} -->
  5. <el-upload ref="upload" style="display: inline-block; " :show-header="'status'" action="" :limit="999"
  6. :on-success="handleSuccessUpload" :http-request="httpRequest" multiple :on-exceed="(files, fileList) => {
  7. $message.warning(`当前限制选择 999 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
  8. }" :show-file-list="false" :before-upload="beforeUpload" :on-change="changes" :on-progress="uploadVideoProcess"
  9. :file-list="fileList">
  10. <template v-if="auth === 'view' && uploadFlag === false" #tip>
  11. <el-button v-show="false" :loading="loading" type="primary" size="default" :disabled="true"> 点击上传
  12. </el-button>
  13. </template>
  14. <template v-else #trigger>
  15. <el-button v-show="false" class="upload-btn" :loading="loading" type="primary" size="default"> 点击上传
  16. </el-button> <span v-show="false" style="margin-left: 20px;font-size:14px;font-weight:normal;color:red;"
  17. type="primary">
  18. 上传报销的数电发票xml文件</span>
  19. </template>
  20. </el-upload>
  21. <!-- </el-divider> -->
  22. <div style="height: calc(100% - 80px);margin-top: -20px;">
  23. <!-- 进度条 -->
  24. <el-progress style="margin-left: 5em" v-if="progressFlag" :percentage="loadProgress"></el-progress>
  25. <el-table :row-class-name="tableRowClassName" ref="uploadTable" v-loading="loading" :key="tableKey"
  26. :summary-method="getSummaries" show-summary :data="dataListNew">
  27. <el-table-column label="" width="80" />
  28. <el-table-column label="序号" type="index" width="80" />
  29. <!-- <el-table-column type="seq" width="40"></el-table-column>-->
  30. <el-table-column label="文件名称" prop="name" align="center" width="290">
  31. <template #default="scope">
  32. <div v-if="ifName(scope.row) === true">
  33. <el-image style="width: 30px; height: 30px;padding-top: 4px;" :src="scope.row.lsUrl"
  34. :preview-src-list="[scope.row.lsUrl]" :preview-teleported="true"></el-image>
  35. </div>
  36. <div v-else>
  37. <el-link type="primary" :underline="false" @click="showFile(scope.row)">{{ scope.row.name
  38. }}</el-link>
  39. </div>
  40. </template>
  41. </el-table-column>
  42. <el-table-column label="创建人" prop="createBy.name" align="center"></el-table-column>
  43. <el-table-column label="创建时间" prop="createTime" align="center" width="180"></el-table-column>
  44. <el-table-column label="文件大小" prop="size" align="center" width="110">
  45. <template #default="scope">
  46. {{ getSize(scope.row.size) }}
  47. </template>
  48. </el-table-column>
  49. <el-table-column prop="invoiceType" label="发票类型" align="center" show-overflow="title" width="110">
  50. <template #default="scope">
  51. {{
  52. $dictUtils.getDictLabel(
  53. "invoice_reimbursement_type",
  54. scope.row.invoiceType,
  55. "-"
  56. )
  57. }}
  58. </template>
  59. </el-table-column>
  60. <el-table-column prop="invoiceProjectName" label="发票项目名" align="center" width="200" :edit-render="{}"
  61. show-overflow="title">
  62. <template #edit="scope">
  63. <el-input maxlength="50" readonly="true" v-model="scope.row.invoiceProjectName"></el-input>
  64. </template>
  65. </el-table-column>
  66. <el-table-column prop="number" label="发票号" align="center" width="250" :edit-render="{}"
  67. show-overflow="title">
  68. <template #edit="scope">
  69. <el-input oninput="value=value.replace(/\D|^/g,'')" readonly="true" maxlength="30"
  70. @change="isExict(scope.row)" v-model="scope.row.number"></el-input>
  71. </template>
  72. </el-table-column>
  73. <el-table-column prop="invoiceDate" label="开票日期" align="center" width="110" :edit-render="{}"
  74. show-overflow="title">
  75. <template v-slot:edit="scope">
  76. <el-input v-model="scope.row.invoiceDate" readonly="true" type="date" transfer
  77. placeholder="请选择日期"></el-input>
  78. </template>
  79. </el-table-column>
  80. <el-table-column prop="invoiceUnit" label="开票单位" align="center" width="200" :edit-render="{}"
  81. show-overflow="title">
  82. <template #edit="scope">
  83. <el-input maxlength="50" readonly="true" v-model="scope.row.invoiceUnit"></el-input>
  84. </template>
  85. </el-table-column>
  86. <el-table-column prop="buyerName" label="购买方名称" align="center" width="200" :edit-render="{}"
  87. show-overflow="title">
  88. <template #edit="scope">
  89. <el-input maxlength="50" readonly="true" v-model="scope.row.buyerName"></el-input>
  90. </template>
  91. </el-table-column>
  92. <el-table-column prop="amount" label="金额" align="center" width="120" :edit-render="{}"
  93. show-overflow="title">
  94. <template #edit="scope">
  95. <el-input maxlength="15" readonly="true" v-model="scope.row.amount"
  96. @input="scope.row.amount = twoDecimalPlaces(scope.row.amount)"
  97. @change="countAmount(scope.row)"></el-input>
  98. </template>
  99. </el-table-column>
  100. <el-table-column prop="taxAmount" label="税额" align="center" width="120" :edit-render="{}"
  101. show-overflow="title">
  102. <template #edit="scope">
  103. <el-input maxlength="15" readonly="true" v-model="scope.row.taxAmount"
  104. @input="scope.row.taxAmount = twoDecimalPlaces(scope.row.taxAmount)"
  105. @change="countAmount(scope.row)"></el-input>
  106. </template>
  107. </el-table-column>
  108. <el-table-column prop="count" label="价税合计" align="center" width="120" :edit-render="{}"
  109. show-overflow="title">
  110. <template #edit="scope">
  111. <el-input disabled="true" v-model="scope.row.count"></el-input>
  112. </template>
  113. </el-table-column>
  114. <el-table-column v-if="isConfirm == 1 || isConfirm == 2" prop="confirmStatus" label="确认状态"
  115. align="center" width="120" :edit-render="{}" show-overflow="title">
  116. <template #default="scope">
  117. <el-tag v-if="scope.row.confirmStatus == '1'" type="success">已确认</el-tag>
  118. <el-tag v-if="!scope.row.confirmStatus || scope.row.confirmStatus == '0'"
  119. type="danger">未确认</el-tag>
  120. </template>
  121. </el-table-column>
  122. <el-table-column label="操作" width="200px" fixed="right" align="center">
  123. <template #default="scope">
  124. <el-form inline :disabled="false" style="display: inline-block;">
  125. <el-button
  126. v-if="isConfirm == 1 && (!scope.row.confirmStatus || scope.row.confirmStatus == '0')"
  127. text type="primary" key="btn01" icon="el-icon-check" size="small"
  128. @click="changeStatus(scope.row, '1')" style="margin-right: 12px;">确认</el-button>
  129. <el-button v-if="isConfirm == 1 && scope.row.confirmStatus == '1'" text type="danger"
  130. key="btn02" icon="el-icon-close" size="small"
  131. @click="changeStatus(scope.row, '0')">取消确认</el-button>
  132. <el-button style="margin-right: 12px;" text type="primary" key="01" icon="el-icon-download"
  133. size="small" @click="toHref(scope.row)">下载</el-button>
  134. </el-form>
  135. <el-button text type="primary" key="02" icon="el-icon-delete" size="small"
  136. @click="deleteFileById(scope.row, scope.$index, this.dataListNew)"
  137. :disabled="auth === 'view' && delFlag === false && createBy !== scope.row.createBy.name">删除</el-button>
  138. </template>
  139. </el-table-column>
  140. </el-table>
  141. </div>
  142. <!-- <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="[url]" :zIndex=9999></el-image-viewer>-->
  143. </div>
  144. </template>
  145. <script>
  146. // eslint-disable-next-line no-unused-vars
  147. import OSSSerivce, {
  148. httpRequest,
  149. // eslint-disable-next-line no-unused-vars
  150. handleRemove,
  151. fileNameInvoice,
  152. // eslint-disable-next-line no-unused-vars
  153. beforeAvatarUpload,
  154. exnameFix,
  155. // eslint-disable-next-line no-unused-vars
  156. openWindowOnUrl,
  157. // eslint-disable-next-line no-unused-vars
  158. toHref
  159. } from '@/api/sys/OSSService'
  160. // import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  161. import moment from 'moment'
  162. import Sortable from 'sortablejs';
  163. export default {
  164. data() {
  165. return {
  166. isConfirm: 0,//1:为主任审批,需要确认发票。2:为财务审批,无需确认
  167. uploadKey: '',
  168. progressFlag: false,
  169. loadProgress: 0,
  170. fileList: [],
  171. dataList: [],
  172. oldDataList: [],
  173. dataListNew: [],
  174. url: '',
  175. showViewer: false,
  176. ossService: null,
  177. auth: '',
  178. directory: 'public',
  179. maxValue: 300,
  180. tableKey: '',
  181. fileLoading: true,
  182. dividerName: '',
  183. uploadFlag: false,
  184. delFlag: false,
  185. createBy: '',
  186. showDivider: true,
  187. loading: false,
  188. dataListLength: '',
  189. uploadDelFlag: false,
  190. // reNumFiles: [], // 存储重复发票号
  191. toCompany: '', //用于区分属于哪个公司的数电发票,
  192. motorFileLabel: [
  193. "BasicInformationTotalTaxincludedAmount",
  194. "BasicInformationTotalTaxAm",
  195. "SpecificInformationMotorVehicleSalesVehicleModel"
  196. ],
  197. fileLabel: [
  198. "BasicInformationTotalTaxAm",//税额
  199. "IssueTime",//
  200. "IssuItemInformationTaxRate",//
  201. // "IssuItemInformationTaxClassificationCode",
  202. // "IssuItemInformationQuantity",
  203. "InherentLabelEInvoiceTypeLabelName",//
  204. // "InherentLabelInIssuTypeLabelName",
  205. "SellerInformationSellerName",//开票单位
  206. // "IssuItemInformationAmount",
  207. // "InherentLabelTaxpayerTypeLabelCode",
  208. "BuyerInformationBuyerIdNum",//
  209. "BasicInformationTotalTaxincludedAmount",//合计
  210. // "Version",
  211. "InherentLabelGeneralOrSpecialVATLabelName",//发票类型
  212. "BasicInformationRequestTime",//
  213. "BasicInformationTotalTaxincludedAmountInChinese",//
  214. // "UndefinedLabelLabelLabelName",
  215. "IssuItemInformationTotaltaxIncludedAmount",//
  216. "InvoiceNumber",// 发票号
  217. // "TaxBureauCode",
  218. "IssuItemInformationComTaxAm", //
  219. // "EIid",
  220. "IssuItemInformationItemName",//项目名
  221. //"SellerInformationSellerBankName",//
  222. "BasicInformationDrawer",//
  223. // "UndefinedLabelLabelLabelCode",
  224. // "IssuItemInformationUnPrice",
  225. "UndefinedLabelLabelLabelType",
  226. "BuyerInformationBuyerName",//购买方
  227. // "SellerInformationSellerAddr",
  228. "BasicInformationTotalAmWithoutTax",//金额
  229. //"SellerInformationSellerBankAccNum",//
  230. "InherentLabelEInvoiceTypeLabelCode",//
  231. "InherentLabelInIssuTypeLabelCode",
  232. //"SellerInformationSellerTelNum",//
  233. // "AdditionalInformationRemark",
  234. // "IssuItemInformationMeaUnits",
  235. // "EInvoiceTag",
  236. // "InherentLabelTaxpayerTypeLabelName",
  237. "InherentLabelGeneralOrSpecialVATLabelCode",//
  238. // "SellerInformationSellerIdNum",
  239. // "IssuItemInformationSpecMod",
  240. // "TaxBureauName"
  241. ],
  242. uniqueId: "",
  243. allFiles: [],
  244. hasUploading: false,
  245. invoiceNoSet: new Set(), // 已存在的发票号
  246. }
  247. },
  248. watch: {
  249. dataListNew: {
  250. handler(val) {
  251. },
  252. deep: true,
  253. immediate: true
  254. }
  255. },
  256. created() {
  257. this.ossService = new OSSSerivce()
  258. },
  259. computed: {
  260. allStatus() {
  261. return this.dataListNew.length > 0 && this.dataListNew.every(item => item.confirmStatus == 1);
  262. },
  263. },
  264. components: {
  265. // ElImageViewer
  266. },
  267. mounted() {
  268. window.onPreview = this.onPreview
  269. },
  270. methods: {
  271. /**
  272. * dividerName: 组件中divider的名称赋值
  273. * showDivider: ‘附件‘Divider是否展示
  274. * 注:值为空时,默认值为true
  275. * showDivider=false时 ‘附件‘Divider隐藏
  276. **/
  277. setDividerName(dividerName, showDivider) {
  278. if (this.commonJS.isNotEmpty(dividerName)) {
  279. this.dividerName = dividerName
  280. }
  281. if (this.commonJS.isNotEmpty(showDivider)) {
  282. if (showDivider === false) {
  283. this.showDivider = false
  284. } else {
  285. this.showDivider = true
  286. }
  287. } else {
  288. this.showDivider = true
  289. }
  290. },
  291. /**
  292. * 文件上传组件初始化
  293. * @param auth
  294. * auth的值为"view"时,不可上传/编辑文件
  295. * auth为其他值时,可上传/编辑文件
  296. * @param fileList 要显示到文件上传列表中的文件。
  297. * 注:文件必须要有url属性并且文件的url属性值必须是在oss中的路径值
  298. * 例:'/attachment-file/xxx/xxx/2022/9/08/xxx.jpg'
  299. * @param directory 要存放到oss的哪个文件夹下。
  300. * 注:值为空时,默认存放到"public"文件夹
  301. * @param maxValue 上传文件允许的最大值,单位:MB
  302. * 注:值为空时,默认值为300MB
  303. * @param dividerName 组件中divider的名称
  304. * 注:值为空时,默认值为‘附件’
  305. * @param uploadFlag ‘上传文件’按钮是否禁用
  306. * 注:值为空时,默认值为false
  307. * auth=view&&uploadFlag=false时 ‘上传文件’按钮禁用
  308. * @param delFlag ‘删除’按钮是否禁用
  309. * 注:值为空时,默认值为false
  310. * auth=view&&delFlag=false时 ‘删除’按钮禁用
  311. * @param showDivider ‘附件‘Divider是否展示
  312. * 注:值为空时,默认值为true
  313. * showDivider=false时 ‘附件‘Divider隐藏
  314. * * @param toCompany ‘动态区分属于那个公司
  315. * 注:值为空时,默认值为 '江苏兴光项目管理有限公司'
  316. *
  317. *
  318. */
  319. async newUpload(auth, fileList, directory, maxValue, dividerName, uploadFlag, delFlag, showDivider, toCompany, uniqueId) {
  320. this.loading = true
  321. this.$emit('changeLoading', true)
  322. this.uploadKey = Math.random()
  323. await this.fileLoadingFalse()
  324. if (this.commonJS.isEmpty(fileList)) {
  325. fileList = []
  326. this.fileLoading = true
  327. } else {
  328. const tempFiles = fileList.filter(item => item.remarks == uniqueId);
  329. this.dataListLength = tempFiles.length
  330. // this.allFiles = fileList
  331. }
  332. if (this.commonJS.isEmpty(dividerName)) {
  333. this.dividerName = '数电发票信息'
  334. } else {
  335. this.dividerName = dividerName
  336. }
  337. if (this.commonJS.isEmpty(toCompany)) {
  338. this.toCompany = '江苏兴光会计师事务所有限责任公司'
  339. } else {
  340. //对公司名中的括号进行转化,便于与附件中的公司名进行比较
  341. toCompany = toCompany
  342. .replace(/(/g, '(')
  343. .replace(/)/g, ')');
  344. this.toCompany = toCompany
  345. }
  346. if (directory !== undefined && directory !== null && directory !== '' && directory !== {}) {
  347. this.directory = directory
  348. } else {
  349. this.directory = 'public'
  350. }
  351. if (maxValue !== undefined && maxValue !== null && maxValue !== '' && maxValue !== 0) {
  352. this.maxValue = maxValue
  353. } else {
  354. this.maxValue = 300
  355. }
  356. this.auth = auth
  357. if (this.commonJS.isEmpty(uploadFlag)) {
  358. this.uploadFlag = false
  359. } else {
  360. if (uploadFlag !== true && uploadFlag !== false) {
  361. this.uploadFlag = false
  362. } else {
  363. this.uploadFlag = uploadFlag
  364. }
  365. }
  366. if (this.commonJS.isEmpty(delFlag)) {
  367. this.delFlag = false
  368. } else {
  369. if (delFlag !== true && delFlag !== false) {
  370. this.delFlag = false
  371. this.createBy = delFlag
  372. } else {
  373. this.delFlag = delFlag
  374. }
  375. }
  376. if (this.commonJS.isNotEmpty(uniqueId)) {
  377. this.uniqueId = uniqueId
  378. }
  379. this.oldDataList = []
  380. const filtered = fileList.filter(item => item.remarks === uniqueId)
  381. filtered.forEach(item => {
  382. this.invoiceNoSet.add(item.number)
  383. })
  384. this.dataList = filtered
  385. this.oldDataList = [...filtered]
  386. this.dataListNew = [...filtered]
  387. this.fileLoading = true
  388. // 防止数据未更新完成,用户操作上传
  389. this.loading = false
  390. this.$emit('changeLoading', false)
  391. // this.dataList = JSON.parse(JSON.stringify(fileList))
  392. // this.dataListNew = JSON.parse(JSON.stringify(fileList))
  393. if (this.commonJS.isEmpty(showDivider)) {
  394. this.showDivider = true
  395. } else {
  396. if (showDivider === false) {
  397. this.showDivider = false
  398. } else {
  399. this.showDivider = true
  400. }
  401. }
  402. // 如果是综合管理部主任或者发票上传本人,可以拖拽发票顺序
  403. if (this.isConfirm == 1 || this.isConfirm == 4) {
  404. const tbody = this.$refs.uploadTable.$el.querySelector('.el-table__body-wrapper tbody');
  405. Sortable.create(tbody, {
  406. group: 'shared',
  407. animation: 150,
  408. ghostClass: 'sortable-ghost', //拖拽样式
  409. easing: 'cubic-bezier(1, 0, 0, 1)',
  410. onStart: (item) => {
  411. console.log(item);
  412. },
  413. // 结束拖动事件
  414. onEnd: (item) => {
  415. this.setNodeSort(item.oldIndex, item.newIndex)
  416. },
  417. })
  418. }
  419. },
  420. setNodeSort(oldIndex, newIndex, type) {
  421. if (type == 'init') {
  422. // 初始化给sort
  423. this.dataListNew.forEach((item, index) => {
  424. item.sort = index + 1
  425. });
  426. return
  427. }
  428. // 使用arr复制一份表格数组数据
  429. const arr = this.dataListNew;
  430. const currentRow = arr.splice(oldIndex, 1)[0]
  431. arr.splice(newIndex, 0, currentRow)
  432. // 原数组置空
  433. this.dataListNew = [];
  434. this.$nextTick(async () => {
  435. this.dataListNew = arr;
  436. this.dataListNew.forEach((item, index) => {
  437. item.sort = index + 1
  438. });
  439. this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  440. });
  441. },
  442. async httpRequest(file) {
  443. await httpRequest(file, fileNameInvoice(file), this.directory, this.maxValue)
  444. },
  445. handleSuccessUpload(response, file, fileList) {
  446. },
  447. async beforeUpload(file) {
  448. this.changeLoading(true)
  449. if (this.uploadDelFlag) {
  450. this.$message.warning('该文件已上传,请勿重复上传');
  451. this.uploadKey = Math.random()
  452. return false; // 取消上传
  453. } else {
  454. // 文件大小检查
  455. if (!beforeAvatarUpload(file, this.dataListNew, this.maxValue)) {
  456. this.$message.error('文件大小不能超过 ' + this.maxValue + ' MB!');
  457. this.changeLoading(false)
  458. return false;
  459. }
  460. // 对文件进行判定
  461. const isXml = file.type === 'text/xml'; // 假设只接受 XML 文件
  462. if (!isXml) {
  463. this.$message.error('只能上传 XML 文件');
  464. this.changeLoading(false)
  465. return false; // 取消上传
  466. }
  467. const formBody = new FormData()
  468. formBody.append('file', file)
  469. let fileData
  470. try {
  471. // 后端解析
  472. fileData = await this.ossService.disposeXmlFile(formBody)
  473. } catch (e) {
  474. this.$message.error('发票文件解析失败')
  475. this.changeLoading(false)
  476. return false
  477. }
  478. //判断文件是否重复
  479. let fileIndex = this.dataList.findIndex(fileItem => {
  480. return fileItem.number == fileData.InvoiceNumber
  481. })
  482. if (fileIndex != -1) {
  483. if (JSON.stringify(fileData) === "{}") {
  484. this.$message.warning({ message: `数电发票:${file.name}格式错误` });
  485. this.changeLoading(false)
  486. return false
  487. }
  488. if (this.commonJS.isNotEmpty(fileData.InvoiceNumber)) {
  489. this.$message.warning({ message: `数电发票:${file.name + "<br/>发票号:" + fileData.InvoiceNumber}<br/>已经上传,请勿重复上传`, dangerouslyUseHTMLString: true });
  490. this.changeLoading(false)
  491. return false
  492. }
  493. }
  494. this.uploadKey = Math.random();
  495. const fileUrl = file.url;
  496. // 检查临时 URL 是否有效
  497. if (fileUrl && fileUrl.trim() !== '') {
  498. try {
  499. const temporaryUrl = await this.ossService.getTemporaryUrl(fileUrl);
  500. if (!temporaryUrl || temporaryUrl.trim() === '') {
  501. // 如果临时 URL 无效,则标记该文件为无效并删除
  502. this.$message.warning({ message: `数电发票:${file.name}获取失败,上传失败。` });
  503. this.changeLoading(false)
  504. return false
  505. } else {
  506. // 如果临时 URL 有效,继续添加文件到有效文件列表
  507. file.lsUrl = temporaryUrl;
  508. }
  509. } catch (error) {
  510. // 如果临时 URL 获取失败,也标记该文件为无效
  511. this.$message.warning({ message: `数电发票:${file.name}获取失败,上传失败。` });
  512. this.changeLoading(false)
  513. return false
  514. }
  515. }
  516. // 6. 给文件添加上传时间和上传人
  517. file.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  518. file.createBy = {
  519. id: this.$store.state.user.id,
  520. name: this.$store.state.user.name,
  521. };
  522. if (file !== undefined && file !== null && file !== {}) {
  523. // 设置文件的 URL
  524. // 仅处理 XML 文件
  525. if (file.name && file.name.toLowerCase().endsWith(".xml")) {
  526. if (JSON.stringify(fileData) === "{}") {
  527. this.$message.warning({ message: `数电发票:${file.name}格式错误` });
  528. this.changeLoading(false)
  529. return false
  530. }
  531. if (Object.keys(fileData).length > 0) {
  532. this.fieldComparison(fileData, this.fileLabel);
  533. // 检查 data 是否包含 BuyerInformationBuyerName 属性
  534. if (fileData && 'BuyerInformationBuyerName' in fileData) {
  535. // 验证是否有效,并进行替换操作
  536. if (typeof fileData.BuyerInformationBuyerName === 'string') {
  537. var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
  538. .replace(/(/g, '(')
  539. .replace(/)/g, ')');
  540. fileData.BuyerInformationBuyerName = buyerInformationBuyerName
  541. }
  542. }
  543. if (this.toCompany !== fileData.BuyerInformationBuyerName) {
  544. this.$message.warning({ message: `仅可上传${this.toCompany}的报销数电发票:<br/>${"文件名: " + file.name + "—— 发票号:" + fileData.InvoiceNumber}<br>上传失败 `, dangerouslyUseHTMLString: true });
  545. this.changeLoading(false)
  546. return false
  547. }
  548. if (this.commonJS.isNotEmpty(fileData.InvoiceNumber)) {
  549. var flag = this.invoiceReimbursementDispose(fileData)
  550. if (flag) {
  551. this.$message.warning({ message: `数电发票:${file.name + "-" + fileData.InvoiceNumber}<br/>已经上传,请勿重复上传`, dangerouslyUseHTMLString: true });
  552. this.changeLoading(false)
  553. return false
  554. }
  555. //查询当前发票号是否已经被报销
  556. let isUsed = await this.ossService.isUsedByInvoiceNumber(fileData.InvoiceNumber);
  557. if (isUsed) {
  558. this.$message.warning({ message: `数电发票:${file.name + "<br/> 发票号:" + fileData.InvoiceNumber}<br/>已经发起或已完成报销,无法重复报销`, dangerouslyUseHTMLString: true });
  559. this.changeLoading(false)
  560. return false
  561. }
  562. let inDate = this.formatDate(fileData.IssueTime)
  563. if (inDate.indexOf("NaN") != -1 && this.commonJS.isNotEmpty(inDate)) {
  564. this.$message.warning({ message: `数电发票:${file.name + "<br/> 发票号:" + fileData.InvoiceNumber}<br/>日期格式错误,上传失败。`, dangerouslyUseHTMLString: true });
  565. this.changeLoading(false)
  566. return false
  567. }
  568. }
  569. }
  570. }
  571. }
  572. file.fileData = fileData;
  573. return true
  574. }
  575. },
  576. uploadVideoProcess(event, file, fileList) {
  577. this.progressFlag = true // 显示进度条
  578. this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
  579. if (this.loadProgress >= 100) {
  580. this.loadProgress = 100
  581. setTimeout(() => {
  582. this.progressFlag = false
  583. }, 1000) // 一秒后关闭进度条
  584. }
  585. },
  586. invoiceReimbursementDisposeData(fileData, file) {
  587. var invoiceReimbursements = this.dataListNew;
  588. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  589. var includeFlag = false;
  590. if (!invoiceReimbursements) {
  591. invoiceReimbursements = [];
  592. }
  593. if (this.toCompany === fileData.BuyerInformationBuyerName) {
  594. // 生成个随机数
  595. // const fileBody = new FormData();
  596. // fileBody.append('file', file.raw);
  597. // const fileData = await this.ossService.disposeXmlFile(fileBody);
  598. // if (data.InvoiceNumber === fileData.InvoiceNumber) {
  599. file.invoiceType = fileData.InherentLabelGeneralOrSpecialVATLabelCode;
  600. file.invoiceProjectName = fileData.IssuItemInformationItemName;
  601. file.number = fileData.InvoiceNumber;
  602. file.invoiceDate = this.formatDate(fileData.IssueTime);
  603. file.invoiceUnit = fileData.SellerInformationSellerName;
  604. file.amount = fileData.BasicInformationTotalAmWithoutTax;
  605. file.taxAmount = fileData.BasicInformationTotalTaxAm;
  606. file.count = fileData.BasicInformationTotalTaxincludedAmount;
  607. file.buyerName = fileData.BuyerInformationBuyerName;
  608. // }
  609. this.$emit("handleCount", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  610. this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  611. }
  612. },
  613. formatDate(date) {
  614. // 正则表达式匹配 "xxx年x月x日" 格式的日期
  615. const regex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
  616. const matches = date.match(regex);
  617. const parts = date.split('/');
  618. if (matches) {
  619. const year = matches[1]; // 年
  620. const month = String(matches[2]).padStart(2, '0'); // 月,确保是两位数
  621. const day = String(matches[3]).padStart(2, '0'); // 日,确保是两位数
  622. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  623. } else if (parts.length === 3) {
  624. const year = parts[0]; // 年份
  625. const month = String(parts[1]).padStart(2, '0'); // 月,确保是两位数
  626. const day = String(parts[2]).padStart(2, '0'); // 日,确保是两位数
  627. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  628. } else {
  629. const d = new Date(date);
  630. const year = d.getFullYear();
  631. const month = String(d.getMonth() + 1).padStart(2, '0'); // 获取月份并确保是两位数
  632. const day = String(d.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
  633. return `${year}-${month}-${day}`;
  634. }
  635. },
  636. getSize(value) {
  637. if (this.commonJS.isEmpty(value)) {
  638. return '0 B'
  639. } else {
  640. let val = parseInt(value)
  641. if (this.commonJS.isEmpty(val)) {
  642. return '0 B'
  643. }
  644. if (isNaN(val)) {
  645. return '0 B'
  646. }
  647. if (val === 0) {
  648. return '0 B'
  649. }
  650. let k = 1024
  651. let sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
  652. let i = Math.floor(Math.log(val) / Math.log(k))
  653. let result = val / Math.pow(k, i);
  654. let kb = parseFloat(result.toPrecision(3));
  655. return kb + '' + sizes[i]
  656. }
  657. },
  658. async changes(file, fileList) {
  659. // 防止上传多次触发changes
  660. if (file.status == 'ready' || file.status == 'uploading') return //阻止上传多次触发changes
  661. // 检查是否有文件正在上传
  662. this.hasUploading = fileList.some(f =>
  663. f.status === 'ready' || f.status === 'uploading'
  664. )
  665. if (!this.hasUploading) {
  666. this.$emit('changeLoading', false)
  667. this.loading = false
  668. } else {
  669. this.$emit('changeLoading', this.hasUploading)
  670. this.loading = this.hasUploading
  671. }
  672. try {
  673. let fileData = file.raw.fileData
  674. // 6. 给文件添加上传时间和上传人
  675. file.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  676. file.createBy = {
  677. id: this.$store.state.user.id,
  678. name: this.$store.state.user.name,
  679. };
  680. let obj = this.dataList.find(tempFile => {
  681. return tempFile.number == fileData.InvoiceNumber
  682. })
  683. if (obj) {
  684. this.$message.warning({ message: `数电发票:${file.name}<br/>已经上传,请勿重复上传`, dangerouslyUseHTMLString: true });
  685. return
  686. }
  687. // 发票号赋值给文件
  688. file.remarks = this.uniqueId
  689. file.number = fileData.InvoiceNumber
  690. // 将新符合条件的文件追加到原文件列表上
  691. this.dataListNew.push(file)
  692. this.fileList.push(file)
  693. this.dataList = this.dataListNew
  694. if (fileData.InvoiceNumber == file.number) {
  695. // 如果 file.raw 存在且有效
  696. if (file.raw !== undefined && file.raw !== null && file.raw !== {}) {
  697. // 设置文件的 URL
  698. file.url = file.raw.url;
  699. // 仅处理 XML 文件
  700. if (file.raw.name && file.raw.name.toLowerCase().endsWith(".xml")) {
  701. // 创建 FormData 对象并发送文件
  702. try {
  703. // 调用后端接口解析 XML 文件
  704. if (fileData && 'BuyerInformationBuyerName' in fileData) {
  705. this.fieldComparison(fileData, this.fileLabel);
  706. // 验证是否有效,并进行替换操作
  707. if (typeof fileData.BuyerInformationBuyerName === 'string') {
  708. var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
  709. .replace(/(/g, '(')
  710. .replace(/)/g, ')');
  711. fileData.BuyerInformationBuyerName = buyerInformationBuyerName
  712. }
  713. }
  714. if (Object.keys(fileData).length > 0) {
  715. // 解析成功,更新数据行
  716. this.invoiceReimbursementDisposeData(fileData, file);
  717. }
  718. } catch (error) {
  719. this.$message.error('处理 XML 文件失败');
  720. console.log('XML 处理失败', error);
  721. }
  722. }
  723. }
  724. }
  725. // 清空 fileList,如果 fileList 不为空
  726. if (fileList && fileList.length > 0) {
  727. this.fileList = [];
  728. }
  729. // 综合管理部主任或者发票上传本人,可以拖拽发票顺序
  730. if (this.isConfirm == 1 || this.isConfirm == 4) {
  731. const tbody = this.$refs.uploadTable.$el.querySelector('.el-table__body-wrapper tbody');
  732. Sortable.create(tbody, {
  733. group: 'shared',
  734. animation: 150,
  735. ghostClass: 'sortable-ghost', //拖拽样式
  736. easing: 'cubic-bezier(1, 0, 0, 1)',
  737. onStart: (item) => {
  738. console.log(item);
  739. },
  740. // 结束拖动事件
  741. onEnd: (item) => {
  742. this.setNodeSort(item.oldIndex, item.newIndex)
  743. },
  744. })
  745. }
  746. // 👇 初始化时主动触发一次
  747. this.setNodeSort(null, null, 'init');
  748. // 在 changes 完成后,手动调用 handleUploadSuccess
  749. // await this.handleUploadSuccess(null, fileData, this.fileList); // 传入空参数或实际参数
  750. } catch (error) {
  751. this.$message.error({
  752. message: `上传出错,${error.message}`
  753. })
  754. }
  755. },
  756. // 处理返回结果字段大小写问题
  757. capitalizeKeys(obj) {
  758. return Object.entries(obj).reduce((acc, [key, value]) => {
  759. let newKey = key.charAt(0).toUpperCase() + key.slice(1);
  760. acc[newKey] = value;
  761. return acc;
  762. }, {});
  763. },
  764. fieldComparison(obj, fields) {
  765. let labelCode = obj["InherentLabelGeneralOrSpecialVATLabelCode"]
  766. // 处理机动车销售统一发票
  767. if (labelCode == '03') {
  768. obj.IssuItemInformationTaxRate = ""
  769. obj.IssuItemInformationTotaltaxIncludedAmount = obj.BasicInformationTotalTaxincludedAmount
  770. obj.IssuItemInformationComTaxAm = obj.BasicInformationTotalTaxAm
  771. obj.IssuItemInformationItemName = obj.SpecificInformationMotorVehicleSalesVehicleModel
  772. }
  773. //--------------------------
  774. if (labelCode == '02') {
  775. if (!obj.IssuItemInformationComTaxAm) {
  776. obj.IssuItemInformationComTaxAm = 0
  777. }
  778. }
  779. // 遍历字段数组,检查每个字段名是否在对象中存在
  780. for (let field of fields) {
  781. // 忽略大小写来匹配属性名
  782. const fieldPattern = new RegExp(`^${field}$`, 'i');
  783. const matchedKeys = Object.keys(obj).filter(key => fieldPattern.test(key));
  784. // 如果没有找到匹配的字段,抛出错误
  785. if (matchedKeys.length === 0) {
  786. if (!field.includes("UndefinedLabel")) {
  787. throw new Error(`未找到发票字段: ${field},请核对XML文件`)
  788. }
  789. }
  790. // 替换属性名
  791. for (let key of matchedKeys) {
  792. if (!field.includes("UndefinedLabel")) {
  793. if (key !== field) {
  794. obj[field] = obj[key];
  795. delete obj[key];
  796. }
  797. }
  798. }
  799. }
  800. },
  801. async handleUploadSuccess(response, fileData, fileList) {
  802. // 遍历当前的数据列表
  803. if (this.dataListNew.length > 0) {
  804. for (let item of this.dataListNew) {
  805. if (fileData.InvoiceNumber == item.number) {
  806. // 如果 item.raw 存在且有效
  807. if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
  808. // 设置文件的 URL
  809. item.url = item.raw.url;
  810. // 仅处理 XML 文件
  811. if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
  812. // 创建 FormData 对象并发送文件
  813. try {
  814. // 调用后端接口解析 XML 文件
  815. if (fileData && 'BuyerInformationBuyerName' in fileData) {
  816. this.fieldComparison(fileData, this.fileLabel);
  817. // 验证是否有效,并进行替换操作
  818. if (typeof fileData.BuyerInformationBuyerName === 'string') {
  819. var buyerInformationBuyerName = fileData.BuyerInformationBuyerName
  820. .replace(/(/g, '(')
  821. .replace(/)/g, ')');
  822. fileData.BuyerInformationBuyerName = buyerInformationBuyerName
  823. }
  824. }
  825. if (Object.keys(fileData).length > 0) {
  826. // 解析成功,更新数据行
  827. await this.invoiceReimbursementDisposeData(fileData, item);
  828. }
  829. } catch (error) {
  830. this.$message.error('处理 XML 文件失败');
  831. console.log('XML 处理失败', error);
  832. }
  833. }
  834. }
  835. }
  836. }
  837. // 更新表格数据
  838. this.$nextTick(() => {
  839. this.$forceUpdate(); // 强制更新表格
  840. });
  841. }
  842. },
  843. invoiceReimbursementDispose(data) {
  844. var invoiceReimbursements = this.dataList;
  845. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  846. var includeFlag = false;
  847. if (!invoiceReimbursements) {
  848. invoiceReimbursements = [];
  849. }
  850. invoiceReimbursements.forEach(item => {
  851. if (item.number === data.InvoiceNumber) {
  852. includeFlag = true;
  853. }
  854. })
  855. return includeFlag;
  856. },
  857. async showFile(row) {
  858. let res = await this.ossService.getFileSizeByUrl(row.url)
  859. if (res.url) {
  860. row.lsUrl = res.url
  861. row.size = res.size
  862. openWindowOnUrl(row)
  863. }
  864. },
  865. onPreview(url) {
  866. this.url = url
  867. this.showViewer = true
  868. },
  869. // 关闭查看器
  870. closeViewer() {
  871. this.url = ''
  872. this.showViewer = false
  873. },
  874. async toHref(row) {
  875. let res = await this.ossService.getFileSizeByUrl(row.url)
  876. if (res.url) {
  877. row.lsUrl = res.url
  878. row.size = res.size
  879. toHref(row)
  880. }
  881. },
  882. async deleteById(row, index, fileList) {
  883. // this.$refs.upload.handleRemove(this.dataListNew[index])
  884. await this.dataListNew.splice(index, 1)
  885. await this.dataList.splice(index, 1)
  886. // if (this.commonJS.isNotEmpty(row.id)) {
  887. // this.ossService.deleteMsgById(row.id)
  888. // }
  889. var newFileList = [];
  890. for (var i = 0; i < fileList.length; i++) {
  891. if (fileList[i].name !== row.name) {
  892. newFileList.push(fileList[i])
  893. }
  894. }
  895. this.fileList = newFileList;
  896. this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  897. },
  898. deleteFileById(row, index, fileList) {
  899. this.invoiceNoSet.delete(row.number)
  900. // this.$refs.upload.handleRemove(this.dataListNew[index])
  901. this.dataListNew.splice(index, 1)
  902. this.dataList = this.dataListNew
  903. // if (this.commonJS.isNotEmpty(row.id)) {
  904. // this.ossService.deleteMsgById(row.id)
  905. // }
  906. // var newFileList = [];
  907. // for (var i = 0; i < this.dataListNew.length; i++) {
  908. // if (this.dataListNew[i].name !== row.name) {
  909. // newFileList.push(this.dataListNew[i])
  910. // }
  911. // }
  912. // this.fileList = newFileList;
  913. // 更新表格数据
  914. this.$nextTick(() => {
  915. this.$forceUpdate(); // 强制更新表格
  916. });
  917. this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  918. this.$emit("handleDelete", row, this.uniqueId)
  919. },
  920. /**
  921. * 关闭dialog时使用 清除el-upload中上传的文件
  922. */
  923. clearUpload() {
  924. this.fileList = []//用于清除上传文件的缓存
  925. this.$refs.upload.clearFiles()
  926. this.dataList = []
  927. this.dataListNew = []
  928. this.createBy = ''
  929. },
  930. /**
  931. * 获取当前文件列表中的文件数据
  932. */
  933. getDataList() {
  934. return this.dataListNew
  935. },
  936. /**
  937. * 判断进度条是否结束,附件是否加载完成
  938. * @returns {boolean}
  939. */
  940. checkProgress() {
  941. if (this.progressFlag === true) {
  942. this.$message.warning('请等待附件上传完成再进行操作')
  943. return true
  944. }
  945. if (this.hasUploading === true) {
  946. this.$message.warning('请等待附件上传完成再进行操作')
  947. return true
  948. }
  949. if (this.fileLoading === false) {
  950. this.$message.warning('请等待附件加载完成再进行操作')
  951. if (this.dataListLength === this.dataListNew.length) {
  952. this.fileLoading = true
  953. }
  954. return true
  955. }
  956. return false
  957. },
  958. ifName(row) {
  959. if (this.commonJS.isEmpty(row.name)) {
  960. row.name = '---'
  961. return false
  962. }
  963. let suffix = row.name.substring(row.name.lastIndexOf('.') + 1)
  964. if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
  965. return true
  966. } else {
  967. return false
  968. }
  969. },
  970. fileLoadingFalse() {
  971. this.fileLoading = false
  972. },
  973. // 开启/关闭页面的加载中状态
  974. changeLoading(loading) {
  975. this.$emit('changeLoading', loading)
  976. this.loading = loading
  977. },
  978. getSummaries(param) {
  979. const { columns, data } = param;
  980. // 初始化汇总数组
  981. const sums = [];
  982. // 遍历列
  983. columns.forEach((column, index) => {
  984. if (index === 0) {
  985. // 第一列(通常是序号列),我们不需要进行汇总,直接设置为“汇总”
  986. sums[index] = '汇总';
  987. }
  988. if (column.property === 'amount') {
  989. // 如果当前列是 'amount',进行汇总
  990. const values = data.map((item) => Number(item[column.property]));
  991. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  992. return prev + curr; // 汇总价税合计列
  993. }, 0));
  994. }
  995. if (column.property === 'taxAmount') {
  996. // 如果当前列是 'amount',进行汇总
  997. const values = data.map((item) => Number(item[column.property]));
  998. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  999. return prev + curr; // 汇总价税合计列
  1000. }, 0));
  1001. }
  1002. if (column.property === 'count') {
  1003. // 如果当前列是 'amount',进行汇总
  1004. const values = data.map((item) => Number(item[column.property]));
  1005. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  1006. return prev + curr; // 汇总价税合计列
  1007. }, 0));
  1008. }
  1009. });
  1010. return sums;
  1011. },
  1012. formatNumber(number) {
  1013. return number.toFixed(2); // 保留两位小数,返回字符串
  1014. },
  1015. changeStatus(row, status) {
  1016. row.confirmStatus = status;
  1017. this.$emit("handleUploadSuccess", JSON.parse(JSON.stringify(this.dataListNew)), this.uniqueId)
  1018. },
  1019. tableRowClassName({ row, rowIndex }) {
  1020. if (this.isConfirm == 1 || this.isConfirm == 2) {
  1021. if (row.confirmStatus == "1") {
  1022. return 'warning-row';
  1023. } else {
  1024. return '';
  1025. }
  1026. } else {
  1027. return '';
  1028. }
  1029. },
  1030. allSelect(status) {
  1031. this.dataListNew.forEach(item => {
  1032. item.confirmStatus = status
  1033. })
  1034. }
  1035. }
  1036. }
  1037. </script>
  1038. <style scoped lang="scss">
  1039. ::v-deep .el-table {
  1040. .warning-row {
  1041. background: #ffe9c0 !important;
  1042. }
  1043. // 滚动条的宽度
  1044. .el-scrollbar__bar {
  1045. height: 16px; // 横向滚动条
  1046. }
  1047. .el-table__footer-wrapper tbody td.el-table__cell,
  1048. .el-table__header-wrapper tbody td.el-table__cell {
  1049. background-color: #fff;
  1050. /* 设置背景颜色与表格一致 */
  1051. }
  1052. /* 设置汇总行的背景颜色与表格一致 */
  1053. .el-table__footer {
  1054. background-color: #fff;
  1055. /* 设置背景颜色与表格一致 */
  1056. }
  1057. /* 让第一列的汇总居中 */
  1058. .el-table__footer .el-table__cell:nth-child(1) {
  1059. text-align: center;
  1060. /* 让第一列居中 */
  1061. font-weight: bold;
  1062. /* 可以根据需要加粗 */
  1063. }
  1064. }
  1065. .el-divider__text {
  1066. font-size: 16px;
  1067. font-weight: bold;
  1068. }
  1069. </style>
  1070. <style></style>