costAudit.vue 57 KB

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