costAudit.vue 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. <template>
  2. <div class="app-container">
  3. <div class="audit-controls">
  4. <el-form
  5. ref="auditForm"
  6. :model="auditForm"
  7. :rules="rules"
  8. :disabled="auditForm.surveyTemplateId !== ''"
  9. >
  10. <el-row>
  11. <el-col :span="6">
  12. <el-form-item label="" prop="catalogId">
  13. <div
  14. style="display: flex; justify-self: start; align-items: center"
  15. >
  16. <div style="width: 120px">监审类别:</div>
  17. <el-cascader
  18. v-model="auditForm.catalogId"
  19. :options="catalogListOptions"
  20. v-bind="props"
  21. style="width: 200px"
  22. clearable
  23. ></el-cascader>
  24. </div>
  25. </el-form-item>
  26. </el-col>
  27. <el-col :span="6">
  28. <el-form-item label="核定模板名称:" prop="surveyTemplateName">
  29. <el-input
  30. v-model="auditForm.surveyTemplateName"
  31. style="width: 200px"
  32. clearable
  33. placeholder="请输入核定模板名称"
  34. ></el-input>
  35. </el-form-item>
  36. </el-col>
  37. </el-row>
  38. <el-row :gutter="20">
  39. <el-col :span="6">
  40. <el-form-item label="" prop="templateType">
  41. <div
  42. style="display: flex; justify-self: start; align-items: center"
  43. >
  44. <el-radio
  45. v-model="auditForm.templateType"
  46. label="1"
  47. @change="handleTemplateTypeChange"
  48. >
  49. 选择调查表修改核定表
  50. </el-radio>
  51. <el-select
  52. v-model="auditForm.dataTable"
  53. placeholder="请选择"
  54. :disabled="auditForm.templateType !== '1'"
  55. >
  56. <el-option
  57. v-for="item in surveyFormList"
  58. :key="item.id"
  59. :label="item.surveyTemplateName"
  60. :value="item.surveyTemplateId"
  61. ></el-option>
  62. </el-select>
  63. </div>
  64. </el-form-item>
  65. </el-col>
  66. <el-col :span="6">
  67. <el-form-item label="" prop="">
  68. <div
  69. style="display: flex; justify-self: start; align-items: center"
  70. >
  71. <el-radio
  72. v-model="auditForm.templateType"
  73. label="2"
  74. @change="handleTemplateTypeChange"
  75. >
  76. 选择核定表历史版本
  77. </el-radio>
  78. <el-select
  79. v-model="auditForm.historyTemplate"
  80. placeholder="请选择"
  81. :disabled="auditForm.templateType !== '2'"
  82. >
  83. <el-option
  84. v-for="item in auditFormList"
  85. :key="item.id"
  86. :label="item.surveyTemplateName"
  87. :value="item.surveyTemplateId"
  88. ></el-option>
  89. </el-select>
  90. </div>
  91. </el-form-item>
  92. </el-col>
  93. </el-row>
  94. </el-form>
  95. <el-button
  96. v-if="!auditForm.surveyTemplateId"
  97. type="primary"
  98. size="small"
  99. @click="handleGenerateTemplate"
  100. >
  101. 生成核定表
  102. </el-button>
  103. <el-button type="primary" size="small" @click="handleSaveTemplate">
  104. 保存核定模版
  105. </el-button>
  106. <el-button type="primary" size="small" @click="handleExportTemplate">
  107. 导出模版
  108. </el-button>
  109. <el-button type="primary" size="small" @click="handleImportData">
  110. 导入数据
  111. </el-button>
  112. <el-button type="primary" size="small" @click="handleSaveData">
  113. 保存核定数据
  114. </el-button>
  115. </div>
  116. <el-table :data="costAuditData" style="width: 100%" border>
  117. <el-table-column
  118. v-for="item in costAuditcolumn"
  119. :key="item.prop"
  120. :prop="item.prop"
  121. :label="item.label"
  122. :width="item.width"
  123. :min-width="item.minWidth"
  124. :align="item.align"
  125. :fixed="item.fixed"
  126. :show-overflow-tooltip="item.showOverflowTooltip"
  127. >
  128. <template slot-scope="scope">
  129. <span v-if="item.isDisplayOnly">{{ scope.row[item.prop] }}</span>
  130. <el-input
  131. v-else
  132. v-model="scope.row[item.prop]"
  133. :placeholder="item.label"
  134. :disabled="item.disabled"
  135. style="width: 100%"
  136. @input="handleCellInput(scope.row)"
  137. @change="handleCellInput(scope.row)"
  138. ></el-input>
  139. </template>
  140. </el-table-column>
  141. <el-table-column
  142. prop="action"
  143. label="操作"
  144. width="100"
  145. align="center"
  146. fixed="right"
  147. >
  148. <template slot-scope="scope">
  149. <el-button
  150. type="text"
  151. title="添加行"
  152. @click="handleAddItem(scope.row)"
  153. >
  154. <i class="el-icon el-icon-circle-plus"></i>
  155. </el-button>
  156. <el-button
  157. type="text"
  158. title="删除行"
  159. @click="handleDeleteItem(scope.row)"
  160. >
  161. <i class="el-icon el-icon-remove"></i>
  162. </el-button>
  163. </template>
  164. </el-table-column>
  165. </el-table>
  166. </div>
  167. </template>
  168. <script>
  169. import {
  170. generateCostVerifyForm,
  171. generateCostVerifyFormData,
  172. getActiveCostVerifyFormList,
  173. getActiveCostVerifyFormListByType,
  174. getCostFormVersionsByTemplateId,
  175. batchSaveOrUpdate,
  176. } from '@/api/costFormManage'
  177. import {
  178. getlistBySurveyTemplateId,
  179. getVerifyTemplateDetail,
  180. importExcel,
  181. exportExcel,
  182. } from '@/api/costVerifyManage'
  183. import { getDetail } from '@/api/auditInitiation'
  184. import { catalogMixin } from '@/mixins/useDict'
  185. import { saveSingleRecordSurvey, getSurveyDetail } from '@/api/audit/survey'
  186. export default {
  187. name: 'CostAudit',
  188. mixins: [catalogMixin],
  189. props: {
  190. id: {
  191. type: [String, Number],
  192. default: null,
  193. },
  194. selectedProject: {
  195. type: Object,
  196. default: () => {
  197. return {}
  198. },
  199. },
  200. currentNode: {
  201. type: String,
  202. default: '',
  203. },
  204. currentStatus: {
  205. type: String,
  206. default: '',
  207. },
  208. auditedUnitId: { type: String, default: '' },
  209. },
  210. data() {
  211. return {
  212. props: {
  213. filterable: true,
  214. placeholder: '请选择监审类别',
  215. style: 'width: 100%',
  216. showAllLevels: false,
  217. props: {
  218. multiple: false,
  219. children: 'children',
  220. checkStrictly: false,
  221. label: 'catalogName',
  222. value: 'id',
  223. emitPath: false,
  224. },
  225. },
  226. // 成本核定表模板列表
  227. auditFormList: [],
  228. // 成本调查表模板列表
  229. surveyFormList: [],
  230. auditForm: {
  231. surveyTemplateName: '',
  232. surveyTemplateId: '',
  233. templateType: '',
  234. dataTable: '',
  235. historyTemplate: '',
  236. catalogId: '',
  237. },
  238. rules: {
  239. catalogId: [
  240. { required: true, message: '请输选择监审类别', trigger: 'change' },
  241. ],
  242. surveyTemplateName: [
  243. { required: true, message: '请输入模版名称', trigger: 'blur' },
  244. ],
  245. },
  246. tableHeadersRes: [],
  247. tableDataRes: [],
  248. // 成本审核表格列配置
  249. costAuditcolumn: [],
  250. // 成本审核数据
  251. costAuditData: [],
  252. project: {},
  253. // 年份到各列prop的映射:{ '2025': { book: '...', audit: '...', approved: '...' } }
  254. yearPropMap: {},
  255. }
  256. },
  257. watch: {
  258. // 监听id变化
  259. // id(newVal) {
  260. // if (newVal) {
  261. // this.$nextTick(() => {
  262. // })
  263. // }
  264. // },
  265. // selectedProject(newVal) {
  266. // if (newVal) {
  267. // this.$nextTick(() => {
  268. // // 获取项目的详情数据
  269. // this.getDetail()
  270. // })
  271. // }
  272. // },
  273. },
  274. created() {
  275. // if (this.selectedProject && this.selectedProject.projectId) {
  276. // // 获取项目的详情数据
  277. // this.getDetail()
  278. // }
  279. // this.handleGenerateTemplate1()
  280. },
  281. methods: {
  282. getDetail() {
  283. this.getActiveCostVerifyFormListByType()
  284. this.getActiveCostVerifyFormList()
  285. // 获取项目的详情数据
  286. getDetail({ id: this.selectedProject.projectId }).then((res) => {
  287. if (res.code === 200) {
  288. this.project = res.value
  289. this.auditForm.catalogId = res.value.catalogId
  290. // this.auditForm.surveyTemplateId = '9368f1cf-77e7-49fe-8502-4a7a2da99668'
  291. this.loadTemplateData()
  292. }
  293. })
  294. },
  295. // 获取所有模板类型为固定表的所有启用成本调查表数据
  296. getActiveCostVerifyFormListByType() {
  297. getActiveCostVerifyFormListByType().then((res) => {
  298. if (res.code === 200) {
  299. this.surveyFormList = res.value
  300. }
  301. })
  302. },
  303. // 获取所有状态为启用的成本核定表模板数据
  304. getActiveCostVerifyFormList() {
  305. getActiveCostVerifyFormList().then((res) => {
  306. if (res.code === 200) {
  307. this.auditFormList = res.value
  308. }
  309. })
  310. },
  311. // TemplateTypeChange
  312. handleTemplateTypeChange(val) {
  313. if (this.auditForm.templateType == '1') {
  314. this.historyTemplate = ''
  315. } else if (this.auditForm.templateType == '2') {
  316. this.dataTable = ''
  317. }
  318. },
  319. // 模板生成操作
  320. handleGenerateTemplate() {
  321. // 提示生成后不能修改
  322. this.$confirm(
  323. '生成后不能修改根据调查表生成还是根据历史核定模板生成,确定生成模板吗?',
  324. '提示',
  325. {
  326. confirmButtonText: '确定',
  327. cancelButtonText: '取消',
  328. type: 'warning',
  329. }
  330. ).then(() => {
  331. // 校验表单
  332. this.$refs['auditForm'].validate((valid) => {
  333. if (valid) {
  334. if (this.auditForm.templateType == '1') {
  335. if (!this.auditForm.dataTable) {
  336. this.$message.error('请选择成本调查表模板')
  337. return
  338. }
  339. this.generateFromSurveyTemplate()
  340. } else if (this.auditForm.templateType == '2') {
  341. if (!this.auditForm.historyTemplate) {
  342. this.$message.error('请选择历史核定模板')
  343. return
  344. }
  345. this.generateFromHistoryTemplate()
  346. }
  347. // this.$message({ type: 'success', message: '模板生成成功' })
  348. } else {
  349. this.$message.error('请填写表单数据')
  350. return
  351. }
  352. })
  353. })
  354. },
  355. // 根据调查表生成模板
  356. async generateFromSurveyTemplate() {
  357. try {
  358. // 保存模板基本信息
  359. let data = await generateCostVerifyForm({
  360. catalogId: this.auditForm.catalogId,
  361. templatename: this.auditForm.surveyTemplateName,
  362. templateId: this.auditForm.dataTable,
  363. taskId: this.selectedProject.taskId,
  364. })
  365. this.auditForm.surveyTemplateId = data.value
  366. ? data.value.surveyTemplateId
  367. : ''
  368. // 设置uploadId
  369. if (data.value) {
  370. this.auditForm.uploadId =
  371. data.value.id || data.value.templateId || ''
  372. }
  373. this.loadTemplateDataForEdit(this.auditForm.surveyTemplateId)
  374. } catch (error) {
  375. console.error('生成模板失败:', error)
  376. } finally {
  377. }
  378. },
  379. // 根据历史核定模板生成
  380. async generateFromHistoryTemplate() {
  381. // 保存模板基本信息
  382. let data = await generateCostVerifyFormData({
  383. catalogId: this.auditForm.catalogId,
  384. templatename: this.auditForm.surveyTemplateName,
  385. templateId: this.auditForm.historyTemplate,
  386. taskId: this.selectedProject.taskId,
  387. })
  388. this.auditForm.surveyTemplateId = data.value
  389. ? data.value.surveyTemplateId
  390. : ''
  391. this.loadTemplateDataForEdit(this.auditForm.surveyTemplateId)
  392. },
  393. // 回显数据用
  394. async loadTemplateData(surveyTemplateId) {
  395. // 先获取表格数据
  396. const tableDataRes = await getCostFormVersionsByTemplateId({
  397. taskId: this.selectedProject.taskId,
  398. // surveyTemplateId: '',
  399. })
  400. // 处理表格数据
  401. if (tableDataRes.code == 200) {
  402. this.auditForm.surveyTemplateId =
  403. tableDataRes.value.itemlist[0].surveyTemplateId
  404. // 有数据后再获取表头数据
  405. const tableHeadersRes = await getlistBySurveyTemplateId({
  406. // taskId: this.selectedProject.taskId,
  407. surveyTemplateId: this.auditForm.surveyTemplateId,
  408. })
  409. getVerifyTemplateDetail({
  410. id: this.auditForm.surveyTemplateId,
  411. }).then((res) => {
  412. this.auditForm.surveyTemplateName = res.value.surveyTemplateName
  413. this.auditForm.catalogId = res.value.catalogId
  414. this.auditForm.templateType = res.value.createmode
  415. if (res.value.createmode == '1') {
  416. this.auditForm.dataTable = res.value.createtemplateid
  417. } else if (res.value.createmode == '2') {
  418. this.auditForm.historyTemplate = res.value.createtemplateid
  419. }
  420. // 设置uploadId以便数据回显
  421. this.auditForm.uploadId = res.value.id || res.value.templateId || ''
  422. })
  423. // 处理表头数据
  424. if (tableHeadersRes.code == 200) {
  425. this.parseAndDisplayTableHeaders(tableHeadersRes)
  426. this.parseAndDisplayTableData(tableDataRes)
  427. await this.tryEchoUploadData()
  428. }
  429. }
  430. },
  431. async loadTemplateDataForEdit(surveyTemplateId) {
  432. // 并行获取表头和表格数据
  433. const [tableHeadersRes, tableDataRes] = await Promise.all([
  434. getlistBySurveyTemplateId({
  435. taskId: this.selectedProject.taskId,
  436. surveyTemplateId: this.auditForm.surveyTemplateId,
  437. }),
  438. getCostFormVersionsByTemplateId({
  439. taskId: this.selectedProject.taskId,
  440. surveyTemplateId: this.auditForm.surveyTemplateId,
  441. }),
  442. ])
  443. // 处理表头数据
  444. if (tableHeadersRes.code == 200) {
  445. this.parseAndDisplayTableHeaders(tableHeadersRes)
  446. }
  447. // 处理表格数据
  448. if (tableDataRes.code == 200) {
  449. // 在这里也设置uploadId
  450. getVerifyTemplateDetail({
  451. id: this.auditForm.surveyTemplateId,
  452. }).then((res) => {
  453. if (res && res.code === 200 && res.value) {
  454. this.auditForm.uploadId =
  455. res.value.id || res.value.templateId || ''
  456. }
  457. })
  458. this.parseAndDisplayTableData(tableDataRes)
  459. await this.tryEchoUploadData()
  460. }
  461. },
  462. // 根据已存在的上传数据进行回显(若有)
  463. async tryEchoUploadData() {
  464. try {
  465. const uploadId = (this.auditForm && this.auditForm.uploadId) || ''
  466. const auditedUnitId = this.auditedUnitId || ''
  467. const taskId =
  468. (this.selectedProject && this.selectedProject.taskId) || ''
  469. // if (!uploadId || !auditedUnitId) return
  470. const params = {
  471. // uploadId,
  472. // auditedUnitId,
  473. type: '3',
  474. taskId: taskId,
  475. }
  476. const res = await getSurveyDetail(params)
  477. if (res && res.code === 200 && res.value) {
  478. const triplets = Array.isArray(res.value)
  479. ? res.value
  480. : res.value.items || res.value.records || []
  481. if (!Array.isArray(triplets) || triplets.length === 0) return
  482. // 建立字段名映射:rkey(中文列名) -> fieldEname(表格prop)
  483. const headerMap = {}
  484. ;(this.tableHeadersRes || []).forEach((h) => {
  485. if (h && h.fieldName && h.fieldEname)
  486. headerMap[h.fieldName] = h.fieldEname
  487. })
  488. // 行索引:rowid -> 行对象
  489. const rowMap = new Map()
  490. ;(this.costAuditData || []).forEach((row) => {
  491. if (row && row.rowid !== undefined && row.rowid !== null) {
  492. rowMap.set(String(row.rowid), row)
  493. }
  494. })
  495. // 应用回显
  496. triplets.forEach((item) => {
  497. const rowid = item.rowid || item.rowId || item.ROWID
  498. const rkey = item.rkey || item.rKey || item.RKEY
  499. const rvalue = item.rvalue || item.rValue || item.RVALUE
  500. if (!rowid || !rkey) return
  501. const row = rowMap.get(String(rowid))
  502. const prop = headerMap[rkey]
  503. if (row && prop) {
  504. row[prop] = rvalue != null ? String(rvalue) : ''
  505. }
  506. })
  507. // 强制刷新
  508. this.costAuditData = [...this.costAuditData]
  509. this.computeApprovedForAllRows()
  510. }
  511. } catch (e) {
  512. console.warn('回显上传数据失败:', e)
  513. }
  514. },
  515. // 单元格输入联动:当账面值或审核调整值变化时,自动计算核定值
  516. handleCellInput(row, item) {
  517. console.log(111)
  518. if (!row) return
  519. // 若未传入列信息,则对该行全部年份重算
  520. if (!item || !item.prop) {
  521. this.computeApprovedForRow(row)
  522. return
  523. }
  524. const m = String(item.prop).match(
  525. /^year(\d{4})(BookValue|Audit|ApprovedValue)$/
  526. )
  527. if (!m) {
  528. this.computeApprovedForRow(row)
  529. return
  530. }
  531. const year = m[1]
  532. const bookProp = `year${year}BookValue`
  533. const auditProp = `year${year}Audit`
  534. const approvedProp = `year${year}ApprovedValue`
  535. const a = parseFloat(row[bookProp])
  536. const b = parseFloat(row[auditProp])
  537. const aNum = isNaN(a) ? 0 : a
  538. const bNum = isNaN(b) ? 0 : b
  539. // 若两者皆为空字符串则清空核定值;否则计算和
  540. if (
  541. (row[bookProp] === '' || row[bookProp] === undefined) &&
  542. (row[auditProp] === '' || row[auditProp] === undefined)
  543. ) {
  544. this.$set(row, approvedProp, '')
  545. } else {
  546. this.$set(row, approvedProp, String(aNum + bNum))
  547. }
  548. },
  549. // 针对单行,遍历存在的年份字段进行重新计算
  550. computeApprovedForRow(row) {
  551. if (!row) return
  552. const map = this.yearPropMap || {}
  553. Object.keys(map).forEach((year) => {
  554. const bookProp = map[year].book
  555. const auditProp = map[year].audit
  556. const approvedProp = map[year].approved
  557. if (!bookProp || !auditProp || !approvedProp) return
  558. const a = parseFloat(row[bookProp])
  559. const b = parseFloat(row[auditProp])
  560. const aNum = isNaN(a) ? 0 : a
  561. const bNum = isNaN(b) ? 0 : b
  562. if (
  563. (row[bookProp] === '' || row[bookProp] === undefined) &&
  564. (row[auditProp] === '' || row[auditProp] === undefined)
  565. ) {
  566. this.$set(row, approvedProp, '')
  567. } else {
  568. this.$set(row, approvedProp, String(aNum + bNum))
  569. }
  570. })
  571. },
  572. // 针对全表,批量重新计算核定值
  573. computeApprovedForAllRows() {
  574. if (!Array.isArray(this.costAuditData)) return
  575. this.costAuditData.forEach((row) => this.computeApprovedForRow(row))
  576. },
  577. parseAndDisplayTableHeaders(res) {
  578. this.tableHeadersRes = Array.isArray(res.value) ? res.value : []
  579. if (this.tableHeadersRes.length > 0) {
  580. // 重置年份映射
  581. this.yearPropMap = {}
  582. this.auditForm.surveyTemplateId = res.value[0].surveyTemplateId
  583. // 表头按照orderNum重新排序
  584. this.tableHeadersRes.sort((a, b) => a.orderNum - b.orderNum)
  585. this.costAuditcolumn = [] // 清空现有列配置
  586. this.tableHeadersRes.forEach((item) => {
  587. let column = {
  588. ...item,
  589. prop: item.fieldEname,
  590. label: item.fieldName,
  591. // 自动宽度:仅"序号"使用固定宽,其余使用最小宽度并开启溢出提示
  592. width: item.fieldName == '序号' ? '80px' : undefined,
  593. minWidth: item.fieldName == '序号' ? undefined : '150px',
  594. align: 'center',
  595. showOverflowTooltip: item.fieldName == '序号' ? false : true,
  596. }
  597. this.costAuditcolumn.push(column)
  598. // 基于表头中文名构建年份映射
  599. const name = item.fieldName || item.label || ''
  600. const prop = item.fieldEname || item.prop || ''
  601. const m = String(name).match(
  602. /^(\d{4})年(账面值|审核调整值|核定值)$/
  603. )
  604. if (m && prop) {
  605. const year = m[1]
  606. const kind = m[2]
  607. if (!this.yearPropMap[year]) this.yearPropMap[year] = {}
  608. if (kind === '账面值') this.yearPropMap[year].book = prop
  609. else if (kind === '审核调整值')
  610. this.yearPropMap[year].audit = prop
  611. else if (kind === '核定值') this.yearPropMap[year].approved = prop
  612. }
  613. })
  614. // 若表头未包含“单位”列,则追加;已包含则不重复添加
  615. const hasUnitCol = this.costAuditcolumn.some(
  616. (c) => c && (c.label === '单位' || c.fieldName === '单位')
  617. )
  618. if (!hasUnitCol) {
  619. this.costAuditcolumn.push({
  620. prop: 'unit',
  621. label: '单位',
  622. width: '80px',
  623. align: 'center',
  624. })
  625. }
  626. // 检查tableHeadersRes数组是否包含年账面值
  627. const hasBookValueColumn = this.checkHasBookValueColumn()
  628. if (!hasBookValueColumn && this.selectedProject.auditPeriod) {
  629. // 获取审计期间并按年份排序
  630. let auditPeriod = this.selectedProject.auditPeriod
  631. .split(',')
  632. .map((year) => parseInt(year))
  633. .sort((a, b) => a - b)
  634. .map((year) => year.toString())
  635. let num = this.tableHeadersRes.length
  636. // 按年份顺序生成三个字段
  637. auditPeriod.forEach((item) => {
  638. // 账面价值字段
  639. let bookValueColumn = {
  640. fieldEname: 'year' + item + 'BookValue',
  641. prop: 'year' + item + 'BookValue',
  642. label: item + '年账面值',
  643. width: '120px',
  644. align: 'right',
  645. fieldName: item + '年账面值',
  646. fieldType: 'integer',
  647. format: '',
  648. fieldTypelen: '255',
  649. fieldTypenointlen: '',
  650. isAuditPeriod: 'true',
  651. isRequired: 'true',
  652. showVisible: '1',
  653. isDict: 'false',
  654. dictid: '',
  655. dictValue: '',
  656. tabtype: this.tableHeadersRes[0].tabtype,
  657. surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
  658. versionId: this.tableHeadersRes[0].versionId,
  659. orderNum: this.getMaxOrderNum() + 1,
  660. }
  661. this.costAuditcolumn.push(bookValueColumn)
  662. this.tableHeadersRes.push(bookValueColumn)
  663. // 映射
  664. if (!this.yearPropMap[item]) this.yearPropMap[item] = {}
  665. this.yearPropMap[item].book = bookValueColumn.prop
  666. // 审核字段
  667. let auditColumn = {
  668. fieldEname: 'year' + item + 'Audit',
  669. prop: 'year' + item + 'Audit',
  670. label: item + '年审核调整值',
  671. width: '150px',
  672. align: 'center',
  673. fieldName: item + '年审核调整值',
  674. fieldType: 'integer',
  675. format: '',
  676. fieldTypelen: '9',
  677. fieldTypenointlen: '',
  678. isRequired: 'true',
  679. isAuditPeriod: 'true',
  680. showVisible: '1',
  681. isDict: 'false',
  682. dictid: '',
  683. dictValue: '',
  684. tabtype: this.tableHeadersRes[0].tabtype,
  685. surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
  686. versionId: this.tableHeadersRes[0].versionId,
  687. orderNum: this.getMaxOrderNum() + num + 1,
  688. }
  689. this.costAuditcolumn.push(auditColumn)
  690. this.tableHeadersRes.push(auditColumn)
  691. this.yearPropMap[item].audit = auditColumn.prop
  692. // 核定值字段
  693. let approvedValueColumn = {
  694. fieldEname: 'year' + item + 'ApprovedValue',
  695. prop: 'year' + item + 'ApprovedValue',
  696. label: item + '年核定值',
  697. width: '120px',
  698. align: 'right',
  699. fieldName: item + '年核定值',
  700. fieldType: 'integer',
  701. format: '',
  702. fieldTypelen: '255',
  703. fieldTypenointlen: '',
  704. isRequired: 'true',
  705. isAuditPeriod: 'true',
  706. showVisible: '1',
  707. isDict: 'false',
  708. dictid: '',
  709. dictValue: '',
  710. tabtype: this.tableHeadersRes[0].tabtype,
  711. surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
  712. versionId: this.tableHeadersRes[0].versionId,
  713. orderNum: this.getMaxOrderNum() + num + 1,
  714. }
  715. this.costAuditcolumn.push(approvedValueColumn)
  716. this.tableHeadersRes.push(approvedValueColumn)
  717. this.yearPropMap[item].approved = approvedValueColumn.prop
  718. })
  719. }
  720. }
  721. },
  722. getMaxOrderNum() {
  723. if (!this.tableHeadersRes || this.tableHeadersRes.length === 0) {
  724. return 0
  725. }
  726. const maxOrderNum = Math.max(
  727. ...this.tableHeadersRes.map((item) => item.orderNum || 0)
  728. )
  729. return maxOrderNum
  730. },
  731. // 检查tableHeadersRes数组是否包含年账面值列
  732. checkHasBookValueColumn() {
  733. if (!this.tableHeadersRes || this.tableHeadersRes.length === 0) {
  734. return false
  735. }
  736. // 检查是否有列的label或fieldName包含'年账面值'字样
  737. return this.tableHeadersRes.some((item) => {
  738. return (
  739. (item.label && item.label.includes('年账面值')) ||
  740. (item.fieldName && item.fieldName.includes('年账面值'))
  741. )
  742. })
  743. },
  744. parseAndDisplayTableData(res) {
  745. // 清空现有数据
  746. this.costAuditData = []
  747. if (
  748. res &&
  749. res.value &&
  750. res.value.itemlist &&
  751. res.value.itemlist.length > 0
  752. ) {
  753. let headers = this.tableHeadersRes
  754. let itemlist = res.value.itemlist
  755. // 遍历每个数据项
  756. itemlist.forEach((item, index) => {
  757. // 为每个数据项创建一个完整的对象
  758. // 判断是否为子项(parentid不为-1且不为"-1")
  759. const isSubItem =
  760. item.parentid && item.parentid !== -1 && item.parentid !== '-1'
  761. let rowData = {
  762. ...item,
  763. isChild: isSubItem,
  764. isSubItem: isSubItem,
  765. }
  766. // 遍历表头,将字段值映射到对应的列
  767. headers.forEach((header) => {
  768. if (header && header.fieldEname && header.fieldName) {
  769. let fieldEname = header.fieldEname
  770. let fieldName = header.fieldName
  771. // 优先用中文列名取值,不存在则用英文prop取值
  772. let fieldValue =
  773. (item &&
  774. (item[fieldName] != null ? item[fieldName] : undefined)) !==
  775. undefined
  776. ? item[fieldName]
  777. : item[fieldEname] || ''
  778. // 将字段值添加到行数据中
  779. rowData[fieldEname] = fieldValue
  780. rowData.rkey = fieldName
  781. rowData.rvalue = fieldValue
  782. }
  783. })
  784. // if (this.selectedProject && this.selectedProject.auditPeriod) {
  785. // // 为审计期间的三个字段添加初始值
  786. // // 获取审计期间并按年份排序
  787. // let auditPeriod = this.selectedProject.auditPeriod
  788. // .split(',')
  789. // .map((year) => parseInt(year))
  790. // .sort((a, b) => a - b)
  791. // .map((year) => year.toString())
  792. // // 为每个年份添加三个字段的初始值,使用与表头定义一致的属性名
  793. // auditPeriod.forEach((year) => {
  794. // rowData[`year${year}BookValue`] = '' // 账面值
  795. // rowData[`year${year}Audit`] = '' // 审核调整值
  796. // rowData[`year${year}ApprovedValue`] = '' // 核定值
  797. // })
  798. // }
  799. // 添加完整的行数据到表格数据中
  800. this.costAuditData.push(rowData)
  801. })
  802. // 平铺顺序:父项在前、子项紧随其后
  803. const sortFn = (a, b) =>
  804. Number(a.orderNum || 0) - Number(b.orderNum || 0)
  805. const byRowId = new Map()
  806. const parents = []
  807. const childGroups = new Map()
  808. this.costAuditData.forEach((row) => {
  809. if (row && row.children) delete row.children
  810. const key = row.rowid != null ? String(row.rowid) : ''
  811. if (key) byRowId.set(key, row)
  812. const pid = row.parentid
  813. const isParent =
  814. pid === -1 || pid === '-1' || pid === null || pid === undefined
  815. if (isParent) {
  816. parents.push(row)
  817. } else {
  818. const pKey = pid != null ? String(pid) : ''
  819. if (!childGroups.has(pKey)) childGroups.set(pKey, [])
  820. childGroups.get(pKey).push(row)
  821. }
  822. })
  823. parents.sort(sortFn)
  824. const flat = []
  825. const seen = new Set()
  826. parents.forEach((p) => {
  827. flat.push(p)
  828. seen.add(p)
  829. const group = childGroups.get(String(p.rowid)) || []
  830. group.sort(sortFn).forEach((c) => {
  831. flat.push(c)
  832. seen.add(c)
  833. })
  834. })
  835. // 处理找不到父项的子项:放在末尾
  836. this.costAuditData.forEach((row) => {
  837. if (!seen.has(row)) flat.push(row)
  838. })
  839. this.costAuditData = flat
  840. // 平铺完成后统一计算核定值
  841. this.computeApprovedForAllRows()
  842. }
  843. },
  844. handleSaveTemplate(type) {
  845. // 显示加载状态
  846. this.$loading({
  847. lock: true,
  848. text: '保存数据中...',
  849. spinner: 'el-icon-loading',
  850. background: 'rgba(0, 0, 0, 0.7)',
  851. })
  852. // 加上遮罩层
  853. const headersList = this.tableHeadersRes.map((header, index) => ({
  854. ...header,
  855. orderNum: header.orderNum || index + 1,
  856. }))
  857. let splitData = this.splitFixedTableDataForSave(this.costAuditData)
  858. let data = {
  859. costVerifyTemplateId: this.auditForm.surveyTemplateId,
  860. headersList: headersList,
  861. itemsList: splitData,
  862. }
  863. batchSaveOrUpdate(data)
  864. .then((data) => {
  865. // 关闭加载状态
  866. this.$loading().close()
  867. if (type != 'delete') {
  868. this.$message.success('保存成功')
  869. this.loadTemplateData()
  870. }
  871. })
  872. .catch((err) => {
  873. // 关闭加载状态
  874. this.$loading().close()
  875. console.log(err)
  876. })
  877. },
  878. async handleSaveData() {
  879. const loading = this.$loading({
  880. lock: true,
  881. text: '保存数据中...',
  882. spinner: 'el-icon-loading',
  883. background: 'rgba(0, 0, 0, 0.7)',
  884. })
  885. try {
  886. // 1) 基于当前表格数据生成保存明细
  887. const rawItems =
  888. this.splitFixedTableDataForSave(this.costAuditData) || []
  889. const auditedUnitId =
  890. this.auditedUnitId || this.auditForm.auditedUnitId || ''
  891. const surveyTemplateId =
  892. this.auditForm.surveyTemplateId || this.auditForm.dataTable || ''
  893. const catalogId = this.auditForm.catalogId || ''
  894. const hasData = !!(this.auditForm && this.auditForm.uploadId)
  895. const taskId =
  896. (this.selectedProject && this.selectedProject.taskId) || ''
  897. console.log('rawItems', rawItems)
  898. const finalSaveData = rawItems.map((it) => {
  899. const base = {
  900. rowid: it.rowid,
  901. rkey: it.rkey,
  902. rvalue: it.rvalue != null ? String(it.rvalue) : '',
  903. auditedUnitId,
  904. surveyTemplateId,
  905. catalogId,
  906. taskId,
  907. // id: it.id,
  908. parentId: it.parentid || '-1',
  909. // refId: taskId,
  910. type: '3',
  911. // uploadId: '',
  912. }
  913. if (hasData) base.uploadId = this.auditForm.uploadId
  914. return base
  915. })
  916. // 2) 调用保存接口
  917. const res = await saveSingleRecordSurvey(finalSaveData)
  918. if (res && res.code === 200) {
  919. this.$message.success('保存成功')
  920. this.loadTemplateData && this.loadTemplateData()
  921. await this.tryEchoUploadData()
  922. } else {
  923. this.$message.error((res && res.message) || '保存失败')
  924. }
  925. } catch (err) {
  926. console.error(err)
  927. // this.$message.error('保存失败')
  928. } finally {
  929. loading.close()
  930. }
  931. },
  932. //分割字符串
  933. stringToObjects(str) {
  934. const items = str.split(',')
  935. return items.map((item) => ({
  936. rkey: item,
  937. rvalue: '',
  938. }))
  939. },
  940. splitFixedTableDataForSave(
  941. tables = this.costAuditData,
  942. headers = this.tableHeadersRes
  943. ) {
  944. let fixedHeaders = headers
  945. let fixedTables = tables
  946. let fixedFields = fixedHeaders
  947. .map((header) => header.fieldName)
  948. .join(',')
  949. let fixedTitles = this.stringToObjects(fixedFields || '')
  950. // 结果数组
  951. const result = []
  952. const processNode = (node, parentRowIndex = 0) => {
  953. // 确保node和fixedValues存在
  954. if (!node) {
  955. console.warn('遇到空节点,跳过处理')
  956. return
  957. }
  958. // 确保fixedValues属性存在,如果不存在则初始化为空对象
  959. if (!node.fixedValues) {
  960. node.fixedValues = {}
  961. }
  962. // 为每个固定列创建一条记录
  963. fixedTitles.forEach((title) => {
  964. // 找到对应的表头信息
  965. const correspondingHeader = fixedHeaders.find(
  966. (header) => header.fieldName === title.rkey
  967. )
  968. if (!correspondingHeader) {
  969. return
  970. }
  971. const newItem = {
  972. rkey: title.rkey,
  973. rvalue:
  974. node[correspondingHeader.prop] !== undefined &&
  975. node[correspondingHeader.prop] !== null
  976. ? node[correspondingHeader.prop]
  977. : node[correspondingHeader.fieldEname] !== undefined &&
  978. node[correspondingHeader.fieldEname] !== null
  979. ? node[correspondingHeader.fieldEname]
  980. : '',
  981. [correspondingHeader.fieldName]:
  982. node[correspondingHeader.fieldEname] !== undefined &&
  983. node[correspondingHeader.fieldEname] !== null
  984. ? node[correspondingHeader.fieldEname]
  985. : '',
  986. surveyTemplateId:
  987. node.surveyTemplateId || correspondingHeader.surveyTemplateId,
  988. versionId: node.versionId || correspondingHeader.versionId,
  989. tabtype: correspondingHeader.tabtype || node.tabtype,
  990. // 添加 headersId 字段(表头的id)
  991. headersId: correspondingHeader ? correspondingHeader.id : null,
  992. // 添加记录的id(itemlist中每条记录的id)
  993. id: node.id || null,
  994. // 添加父子关系字段
  995. parentid: node.parentid || -1, // 父项ID,默认为-1表示无父项
  996. isChild: node.isChild || false, // 是否为子项
  997. // 添加 rowid 字段
  998. rowid: node.rowid || null,
  999. // 添加计算公式相关字段
  1000. calculationFormula: node.calculationFormula || null,
  1001. jsonstr: node.jsonstr || null,
  1002. orderNum:
  1003. typeof node.orderNum === 'number'
  1004. ? node.orderNum
  1005. : parseInt(node.orderNum, 10) || 0,
  1006. // 添加用户需要的其他字段
  1007. orderText: node.orderText || '',
  1008. percentage: node.percentage || '',
  1009. unit: node.unit || '',
  1010. }
  1011. // 添加其他固定表特有的字段
  1012. if (!node.isSubItem) {
  1013. newItem.cellCode = node.cellCode || ''
  1014. newItem.unit = node.unit || ''
  1015. }
  1016. // 添加其他可能需要的字段,但排除特定字段
  1017. Object.keys(node).forEach((key) => {
  1018. if (
  1019. !(key in newItem) &&
  1020. key !== 'fixedValues' &&
  1021. key !== 'itemId' &&
  1022. key !== 'id' &&
  1023. key !== 'parentid' &&
  1024. key !== 'isChild' &&
  1025. key !== 'isSubItem' &&
  1026. key !== 'rowid' &&
  1027. key !== 'jsonstr' &&
  1028. key !== 'calculationFormula' &&
  1029. key !== 'children' // 排除children字段
  1030. ) {
  1031. newItem[key] = node[key]
  1032. }
  1033. })
  1034. result.push(newItem)
  1035. })
  1036. }
  1037. fixedTables.forEach((row) => {
  1038. processNode(row)
  1039. })
  1040. // 首先收集所有父节点的orderNum,确保不与子节点冲突
  1041. const parentOrderNums = new Set()
  1042. // 第一次遍历:识别父节点并收集它们的orderNum
  1043. result.forEach((item) => {
  1044. // 假设isChild为false或parentid为-1的是父节点
  1045. if (!item.isChild || item.parentid === -1) {
  1046. parentOrderNums.add(item.orderNum)
  1047. }
  1048. })
  1049. // 创建映射来跟踪已使用的orderNum
  1050. const usedOrderNums = new Set([...parentOrderNums])
  1051. let nextAvailableOrderNum = 1
  1052. // 找到当前最大的orderNum,作为新orderNum的起点
  1053. const allOrderNums = result
  1054. .map((item) => item.orderNum)
  1055. .filter((num) => typeof num === 'number' && !isNaN(num))
  1056. if (allOrderNums.length > 0) {
  1057. nextAvailableOrderNum = Math.max(...allOrderNums) + 1
  1058. }
  1059. // 第二次遍历:为子节点分配唯一的orderNum
  1060. result.forEach((item) => {
  1061. // 只为子节点重新分配orderNum
  1062. if (item.isChild && item.parentid !== -1) {
  1063. // 找到下一个未使用的orderNum
  1064. while (usedOrderNums.has(nextAvailableOrderNum)) {
  1065. nextAvailableOrderNum++
  1066. }
  1067. // 分配新的orderNum并标记为已使用(保持原有顺序,不修改行原始顺序号)
  1068. item.orderNum = item.orderNum
  1069. usedOrderNums.add(nextAvailableOrderNum)
  1070. nextAvailableOrderNum++
  1071. }
  1072. })
  1073. return result
  1074. },
  1075. //
  1076. handleImportData() {
  1077. let loading = null
  1078. // 第一步:创建文件选择器
  1079. const input = document.createElement('input')
  1080. input.type = 'file'
  1081. input.accept = '.xls,.xlsx,.csv' // 允许的文件类型
  1082. input.onchange = async (event) => {
  1083. const file = event.target.files[0]
  1084. if (!file) return
  1085. try {
  1086. // 校验文件大小(50MB)
  1087. const maxSize = 50 * 1024 * 1024 // 50MB
  1088. if (file.size > maxSize) {
  1089. this.$message.error('文件大小不能超过50MB!')
  1090. return
  1091. }
  1092. // 校验文件格式
  1093. const allowedFormats = ['.xls', '.xlsx', 'csv']
  1094. const fileName = file.name.toLowerCase()
  1095. const isValidFormat = allowedFormats.some((format) =>
  1096. fileName.endsWith(format)
  1097. )
  1098. if (!isValidFormat) {
  1099. this.$message.error('只允许上传.xls,.xlsx,.csv格式的文件!')
  1100. return
  1101. }
  1102. // 显示遮罩层
  1103. loading = this.$baseLoading(1, '文件上传中...')
  1104. // 第三步:创建FormData并上传文件
  1105. const formData = new FormData()
  1106. formData.append('file', file)
  1107. // 其他参数作为query参数传递
  1108. const queryParams = {
  1109. surveyTemplateId: this.auditForm.surveyTemplateId,
  1110. taskId: this.selectedProject.taskId,
  1111. materialId: '', // 根据API文档,此参数为必填,但当前没有值,保留空字符串
  1112. periodRecordId: '', // 非必填参数
  1113. }
  1114. // 先调用上传API,将参数作为query传递
  1115. const uploadRes = await importExcel(formData, queryParams)
  1116. // 第四步:检查上传结果
  1117. if (!uploadRes.state) {
  1118. this.$message.error('导入失败!')
  1119. return
  1120. }
  1121. this.$message.success('导入成功')
  1122. this.loadTemplateData()
  1123. // this.$emit('refresh', this.project.projectId) // 通知父组件刷新
  1124. } catch (error) {
  1125. // 错误处理
  1126. // this.$message.error('操作失败:' + (error.message || '未知错误'))
  1127. } finally {
  1128. // 关闭遮罩层
  1129. loading.close()
  1130. }
  1131. }
  1132. // 触发文件选择
  1133. input.click()
  1134. },
  1135. handleExportTemplate() {
  1136. if (this.costAuditData.length === 0) {
  1137. return
  1138. }
  1139. // 显示加载状态
  1140. const loading = this.$loading({
  1141. lock: true,
  1142. text: '文件下载中...',
  1143. spinner: 'el-icon-loading',
  1144. background: 'rgba(0, 0, 0, 0.7)',
  1145. })
  1146. // 调用导出API
  1147. exportExcel({
  1148. // surveyTemplateId: '1985224388517109760', // 测试用 1989165590455066624
  1149. surveyTemplateId: this.auditForm.surveyTemplateId,
  1150. versionId: this.tableHeadersRes[0].versionId || '',
  1151. })
  1152. .then((res) => {
  1153. // 从响应头获取文件名(如果有)
  1154. let fileName = `成本审核模板_${new Date()
  1155. .toLocaleString()
  1156. .replace(/[:\s]/g, '_')}.xlsx`
  1157. if (res.headers && res.headers['content-disposition']) {
  1158. const contentDisposition = res.headers['content-disposition']
  1159. const match = contentDisposition.match(/filename=([^;]+)/i)
  1160. if (match && match[1]) {
  1161. fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
  1162. }
  1163. }
  1164. // 使用a标签方式下载文件
  1165. const blobData = new Blob([res.data], {
  1166. type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  1167. })
  1168. // 创建URL对象
  1169. const url = window.URL.createObjectURL(blobData)
  1170. // 创建a标签
  1171. const a = document.createElement('a')
  1172. a.style.display = 'none'
  1173. a.href = url
  1174. a.download = fileName // 设置下载文件名
  1175. // 添加到DOM并触发点击
  1176. document.body.appendChild(a)
  1177. a.click()
  1178. // 关闭加载状态
  1179. loading.close()
  1180. // 清理
  1181. setTimeout(() => {
  1182. document.body.removeChild(a)
  1183. window.URL.revokeObjectURL(url) // 释放URL对象,避免内存泄漏
  1184. }, 100)
  1185. })
  1186. .catch((error) => {
  1187. // 关闭加载状态
  1188. loading.close()
  1189. console.error('文件下载失败:', error)
  1190. })
  1191. },
  1192. handleExportData() {
  1193. this.$message({ type: 'info', message: '导出数据' })
  1194. },
  1195. // handleSaveData() {
  1196. // this.$message({ type: 'success', message: '成本审核数据已保存' })
  1197. // },
  1198. handleRemark(row, field) {
  1199. this.$prompt('请输入说明', '提示', {
  1200. confirmButtonText: '确定',
  1201. cancelButtonText: '取消',
  1202. inputValue: row[field],
  1203. })
  1204. .then(({ value }) => {
  1205. row[field] = value
  1206. this.$message({ type: 'success', message: '说明已保存' })
  1207. })
  1208. .catch(() => {
  1209. this.$message({ type: 'info', message: '已取消' })
  1210. })
  1211. },
  1212. // 按层级关系排序表格数据,子项排在父项后面
  1213. sortItemsByHierarchy() {
  1214. if (!this.costAuditData || this.costAuditData.length === 0) {
  1215. return
  1216. }
  1217. // 构建父子关系映射
  1218. const itemMap = new Map()
  1219. const rootItems = []
  1220. const childrenMap = new Map()
  1221. const processedItems = new Set() // 用于避免循环引用
  1222. // 初始化映射和找出根节点
  1223. this.costAuditData.forEach((item) => {
  1224. const currentId = item.id || item.itemId
  1225. if (currentId !== undefined) {
  1226. itemMap.set(currentId, item)
  1227. }
  1228. // 检查是否有有效父ID
  1229. const parentId = item.parentId || item.parentItemId
  1230. const hasValidParent =
  1231. parentId !== undefined &&
  1232. parentId !== null &&
  1233. parentId !== '' &&
  1234. parentId !== -1
  1235. if (!hasValidParent) {
  1236. // 没有有效父ID的是根节点
  1237. rootItems.push(item)
  1238. } else {
  1239. // 有父ID的添加到子节点映射中
  1240. if (!childrenMap.has(parentId)) {
  1241. childrenMap.set(parentId, [])
  1242. }
  1243. childrenMap.get(parentId).push(item)
  1244. }
  1245. })
  1246. // 深度优先遍历生成排序后的数据
  1247. const sortedData = []
  1248. function traverse(item) {
  1249. const currentId = item.id || item.itemId
  1250. // 避免循环引用
  1251. if (processedItems.has(currentId)) {
  1252. return
  1253. }
  1254. // 标记为已处理
  1255. processedItems.add(currentId)
  1256. // 添加当前项
  1257. sortedData.push(item)
  1258. // 获取当前项的子项并递归遍历
  1259. const children = childrenMap.get(currentId) || []
  1260. // 对子项按照orderNum或id进行排序
  1261. children.sort((a, b) => {
  1262. if (a.orderNum !== undefined && b.orderNum !== undefined) {
  1263. return a.orderNum - b.orderNum
  1264. }
  1265. const aId = a.id || a.itemId || 0
  1266. const bId = b.id || b.itemId || 0
  1267. return aId - bId
  1268. })
  1269. // 递归处理每个子项
  1270. children.forEach((child) => {
  1271. traverse(child)
  1272. })
  1273. }
  1274. // 对根节点按照orderNum或id进行排序
  1275. rootItems.sort((a, b) => {
  1276. if (a.orderNum !== undefined && b.orderNum !== undefined) {
  1277. return a.orderNum - b.orderNum
  1278. }
  1279. const aId = a.id || a.itemId || 0
  1280. const bId = b.id || b.itemId || 0
  1281. return aId - bId
  1282. })
  1283. // 从根节点开始遍历
  1284. rootItems.forEach((root) => {
  1285. traverse(root)
  1286. })
  1287. // 如果有未被包含的项目(可能没有正确的父子关系),直接添加到末尾
  1288. if (sortedData.length < this.costAuditData.length) {
  1289. this.costAuditData.forEach((item) => {
  1290. const currentId = item.id || item.itemId
  1291. if (currentId !== undefined && !processedItems.has(currentId)) {
  1292. sortedData.push(item)
  1293. processedItems.add(currentId)
  1294. }
  1295. })
  1296. }
  1297. // 更新表格数据为排序后的数据
  1298. this.costAuditData = sortedData
  1299. // 更新序号字段而非覆盖原始ID
  1300. // this.costAuditData.forEach((item, index) => {
  1301. // // 创建或更新序号字段,保留原始ID不变
  1302. // item.index = index + 1
  1303. // })
  1304. },
  1305. handleAddItem(row) {
  1306. // 判断parentId是否为空,是就添加父项,否则添加子项
  1307. const rowIndex = this.costAuditData.indexOf(row)
  1308. if (rowIndex === -1) {
  1309. this.$message.error('未找到指定行')
  1310. return
  1311. }
  1312. // 确定新行的parentId
  1313. let parentId = row.parentId || '-1'
  1314. // 计算新行的orderNum(当前行的orderNum + 1)
  1315. const newOrderNum = row.orderNum + 1
  1316. // 整体后移逻辑:将所有orderNum大于等于新orderNum的行,其orderNum加1
  1317. // 根据父项和子项关系判断是否需要移动
  1318. this.costAuditData.forEach((item) => {
  1319. // 如果是相同父项的子项,或者都是父项(parentId为'-1'),则需要移动
  1320. if (
  1321. (item.parentId === parentId ||
  1322. (item.parentId === '-1' && parentId === '-1')) &&
  1323. item.orderNum >= newOrderNum
  1324. ) {
  1325. item.orderNum += 1
  1326. }
  1327. })
  1328. // 创建新元素
  1329. const newItem = {
  1330. ...row,
  1331. parentId,
  1332. orderNum: newOrderNum,
  1333. rowid: this.generateUUID(),
  1334. id: null,
  1335. rvalue: '',
  1336. }
  1337. // 循环表头,把值置空
  1338. this.costAuditcolumn.forEach((item) => {
  1339. newItem[item.label] = ''
  1340. newItem[item.prop] = ''
  1341. })
  1342. // 在当前行后面插入新元素
  1343. this.costAuditData.splice(rowIndex + 1, 0, newItem)
  1344. this.$message.success('行添加成功')
  1345. },
  1346. handleDeleteItem(row) {
  1347. // 显示确认对话框
  1348. this.$confirm(
  1349. '确定要删除此行数据吗?如果删除的是父项,将同时删除其所有子项。',
  1350. '确认删除',
  1351. {
  1352. confirmButtonText: '确定',
  1353. cancelButtonText: '取消',
  1354. type: 'warning',
  1355. }
  1356. )
  1357. .then(() => {
  1358. // 获取要删除的行ID
  1359. const rowId = row.rowId || row.id
  1360. // 收集要删除的行索引
  1361. const indicesToDelete = []
  1362. // 查找要删除的行及其子项
  1363. for (let i = 0; i < this.costAuditData.length; i++) {
  1364. const item = this.costAuditData[i]
  1365. // 如果是要删除的行本身,或者是其子项
  1366. if (
  1367. item.rowId === rowId ||
  1368. item.id === rowId ||
  1369. (item.parentId !== '-1' &&
  1370. (item.parentId === rowId || item.parentId === row.id))
  1371. ) {
  1372. indicesToDelete.push(i)
  1373. }
  1374. }
  1375. // 从后往前删除,避免索引偏移
  1376. indicesToDelete
  1377. .sort((a, b) => b - a)
  1378. .forEach((index) => {
  1379. this.costAuditData.splice(index, 1)
  1380. })
  1381. // 更新剩余行的orderNum
  1382. this.updateOrderNumbersAfterDelete(row)
  1383. // 删除行后调用保存模板方法
  1384. this.handleSaveTemplate('delete')
  1385. this.$message.success('行删除成功')
  1386. })
  1387. .catch(() => {
  1388. // 用户取消删除
  1389. this.$message.info('已取消删除操作')
  1390. })
  1391. },
  1392. // 删除行后更新orderNum的方法
  1393. updateOrderNumbersAfterDelete(deletedRow) {
  1394. const deletedOrderNum = deletedRow.orderNum
  1395. const deletedParentId = deletedRow.parentId || '-1'
  1396. // 遍历所有行,更新orderNum
  1397. this.costAuditData.forEach((item) => {
  1398. // 如果是相同父项的子项,或者都是父项(parentId为'-1'),且orderNum大于删除行的orderNum
  1399. if (
  1400. (item.parentId === deletedParentId ||
  1401. (item.parentId === '-1' && deletedParentId === '-1')) &&
  1402. item.orderNum > deletedOrderNum
  1403. ) {
  1404. // 将orderNum减1,保持连续性
  1405. item.orderNum -= 1
  1406. }
  1407. })
  1408. },
  1409. // 生成唯一ID
  1410. generateUUID() {
  1411. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
  1412. /[xy]/g,
  1413. function (c) {
  1414. const r = (Math.random() * 16) | 0,
  1415. v = c === 'x' ? r : (r & 0x3) | 0x8
  1416. return v.toString(16)
  1417. }
  1418. )
  1419. },
  1420. },
  1421. }
  1422. </script>
  1423. <style scoped>
  1424. /* .app-container {
  1425. padding: 20px;
  1426. } */
  1427. .audit-controls {
  1428. margin-bottom: 20px;
  1429. }
  1430. .audit-controls .el-select {
  1431. margin-right: 10px;
  1432. width: 150px;
  1433. }
  1434. .el-icon {
  1435. font-size: 24px;
  1436. }
  1437. </style>