| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646 |
- <template>
- <div class="app-container">
- <div class="audit-controls">
- <el-form
- ref="auditForm"
- :model="auditForm"
- :rules="rules"
- :disabled="auditForm.surveyTemplateId !== ''"
- >
- <el-row>
- <el-col :span="6">
- <el-form-item label="" prop="catalogId">
- <div
- style="display: flex; justify-self: start; align-items: center"
- >
- <div style="width: 120px">监审类别:</div>
- <el-cascader
- v-model="auditForm.catalogId"
- :options="catalogListOptions"
- v-bind="props"
- style="width: 200px"
- clearable
- ></el-cascader>
- </div>
- </el-form-item>
- </el-col>
- <el-col :span="6">
- <el-form-item label="核定模板名称:" prop="surveyTemplateName">
- <el-input
- v-model="auditForm.surveyTemplateName"
- style="width: 200px"
- clearable
- placeholder="请输入核定模板名称"
- ></el-input>
- </el-form-item>
- </el-col>
- </el-row>
- <el-row :gutter="20">
- <el-col :span="6">
- <el-form-item label="" prop="templateType">
- <div
- style="display: flex; justify-self: start; align-items: center"
- >
- <el-radio
- v-model="auditForm.templateType"
- label="1"
- @change="handleTemplateTypeChange"
- >
- 选择调查表修改核定表
- </el-radio>
- <el-select
- v-model="auditForm.dataTable"
- placeholder="请选择"
- :disabled="auditForm.templateType !== '1'"
- >
- <el-option
- v-for="item in surveyFormList"
- :key="item.id"
- :label="item.surveyTemplateName"
- :value="item.surveyTemplateId"
- ></el-option>
- </el-select>
- </div>
- </el-form-item>
- </el-col>
- <el-col :span="6">
- <el-form-item label="" prop="">
- <div
- style="display: flex; justify-self: start; align-items: center"
- >
- <el-radio
- v-model="auditForm.templateType"
- label="2"
- @change="handleTemplateTypeChange"
- >
- 选择核定表历史版本
- </el-radio>
- <el-select
- v-model="auditForm.historyTemplate"
- placeholder="请选择"
- :disabled="auditForm.templateType !== '2'"
- >
- <el-option
- v-for="item in auditFormList"
- :key="item.id"
- :label="item.surveyTemplateName"
- :value="item.surveyTemplateId"
- ></el-option>
- </el-select>
- </div>
- </el-form-item>
- </el-col>
- </el-row>
- </el-form>
- <el-button
- v-if="!auditForm.surveyTemplateId"
- type="primary"
- size="small"
- @click="handleGenerateTemplate"
- >
- 生成核定表
- </el-button>
- <el-button type="primary" size="small" @click="handleSaveTemplate">
- 保存核定模版
- </el-button>
- <el-button type="primary" size="small" @click="handleExportTemplate">
- 导出模版
- </el-button>
- <el-button type="primary" size="small" @click="handleImportData">
- 导入数据
- </el-button>
- <el-button type="primary" size="small" @click="handleSaveData">
- 保存核定数据
- </el-button>
- </div>
- <el-table :data="costAuditData" style="width: 100%" border>
- <el-table-column
- v-for="item in costAuditcolumn"
- :key="item.prop"
- :prop="item.prop"
- :label="item.label"
- :width="item.width"
- :min-width="item.minWidth"
- :align="item.align"
- :fixed="item.fixed"
- :show-overflow-tooltip="item.showOverflowTooltip"
- >
- <template slot-scope="scope">
- <span v-if="item.isDisplayOnly">{{ scope.row[item.prop] }}</span>
- <!-- 字符串类型输入框 -->
- <el-input
- v-else-if="item.fieldType === 'string'"
- v-model="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- :maxlength="item.fieldTypelen ? parseInt(item.fieldTypelen) : null"
- show-word-limit
- style="width: 100%"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- ></el-input>
- <!-- 整数类型输入框 -->
- <el-input
- v-else-if="item.fieldType === 'integer'"
- v-model.number="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- :maxlength="item.fieldTypelen ? parseInt(item.fieldTypelen) : null"
- show-word-limit
- style="width: 100%"
- type="number"
- step="1"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- ></el-input>
- <!-- 小数类型输入框 -->
- <el-input
- v-else-if="item.fieldType === 'double'"
- v-model.number="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- :maxlength="item.fieldTypelen ? parseInt(item.fieldTypelen) : null"
- show-word-limit
- style="width: 100%"
- type="number"
- step="0.01"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- ></el-input>
- <!-- 日期类型输入框 -->
- <el-date-picker
- v-else-if="item.fieldType === 'datetime'"
- v-model="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- style="width: 100%"
- type="date"
- value-format="yyyy-MM-dd"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- ></el-date-picker>
- <!-- 字典类型下拉框 -->
- <el-select
- v-else-if="item.isDict === 'true'"
- v-model="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- style="width: 100%"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- >
- <el-option
- v-for="dict in getDictOptions(item.dictCode)"
- :key="dict.value"
- :label="dict.label"
- :value="dict.value"
- ></el-option>
- </el-select>
- <!-- 默认输入框 -->
- <el-input
- v-else
- v-model="scope.row[item.prop]"
- :placeholder="item.label"
- :disabled="item.disabled"
- :maxlength="item.fieldTypelen ? parseInt(item.fieldTypelen) : null"
- show-word-limit
- style="width: 100%"
- @input="handleCellInput(scope.row, item)"
- @change="handleCellInput(scope.row, item)"
- ></el-input>
- </template>
- </el-table-column>
- <el-table-column
- prop="action"
- label="操作"
- width="100"
- align="center"
- fixed="right"
- >
- <template slot-scope="scope">
- <el-button
- v-if="scope.row.parentid == '-1'"
- type="text"
- title="添加行"
- @click="handleAddItem(scope.row)"
- >
- <i class="el-icon el-icon-circle-plus"></i>
- </el-button>
- <el-button
- type="text"
- title="删除行"
- @click="handleDeleteItem(scope.row)"
- >
- <i class="el-icon el-icon-remove"></i>
- </el-button>
- </template>
- </el-table-column>
- </el-table>
- </div>
- </template>
- <script>
- import {
- generateCostVerifyForm,
- generateCostVerifyFormData,
- getActiveCostVerifyFormList,
- getActiveCostVerifyFormListByType,
- getCostFormVersionsByTemplateId,
- batchSaveOrUpdate,
- } from '@/api/costFormManage'
- import {
- getlistBySurveyTemplateId,
- getVerifyTemplateDetail,
- } from '@/api/costVerifyManage'
- import { getDetail } from '@/api/auditInitiation'
- import { catalogMixin } from '@/mixins/useDict'
- import { getByTypeKey } from '@/api/dictionaryManage'
- import {
- saveSingleRecordSurvey,
- getSurveyDetail,
- downloadTemplate,
- importData,
- } from '@/api/audit/survey'
- export default {
- name: 'CostAudit',
- mixins: [catalogMixin],
- props: {
- id: {
- type: [String, Number],
- default: null,
- },
- selectedProject: {
- type: Object,
- default: () => {
- return {}
- },
- },
- currentNode: {
- type: String,
- default: '',
- },
- currentStatus: {
- type: String,
- default: '',
- },
- auditedUnitId: { type: String, default: '' },
- },
- data() {
- return {
- props: {
- filterable: true,
- placeholder: '请选择监审类别',
- style: 'width: 100%',
- showAllLevels: false,
- props: {
- multiple: false,
- children: 'children',
- checkStrictly: false,
- label: 'catalogName',
- value: 'id',
- emitPath: false,
- },
- },
- // 成本核定表模板列表
- auditFormList: [],
- // 成本调查表模板列表
- surveyFormList: [],
- auditForm: {
- surveyTemplateName: '',
- surveyTemplateId: '',
- templateType: '',
- dataTable: '',
- historyTemplate: '',
- catalogId: '',
- },
- rules: {
- catalogId: [
- { required: true, message: '请输选择监审类别', trigger: 'change' },
- ],
- surveyTemplateName: [
- { required: true, message: '请输入模版名称', trigger: 'blur' },
- ],
- },
- tableHeadersRes: [],
- tableDataRes: [],
- // 成本审核表格列配置
- costAuditcolumn: [],
- // 成本审核数据
- costAuditData: [],
- project: {},
- // 年份到各列prop的映射:{ '2025': { book: '...', audit: '...', approved: '...' } }
- yearPropMap: {},
- // 字典缓存
- dictCache: {},
- }
- },
- watch: {
- // 监听id变化
- // id(newVal) {
- // if (newVal) {
- // this.$nextTick(() => {
- // })
- // }
- // },
- // selectedProject(newVal) {
- // if (newVal) {
- // this.$nextTick(() => {
- // // 获取项目的详情数据
- // this.getDetail()
- // })
- // }
- // },
- },
- created() {
- // if (this.selectedProject && this.selectedProject.projectId) {
- // // 获取项目的详情数据
- // this.getDetail()
- // }
- // this.handleGenerateTemplate1()
- },
- methods: {
- getDetail() {
- this.getActiveCostVerifyFormListByType()
- this.getActiveCostVerifyFormList()
- // 获取项目的详情数据
- getDetail({ id: this.selectedProject.projectId }).then((res) => {
- if (res.code === 200) {
- this.project = res.value
- this.auditForm.catalogId = res.value.catalogId
- // this.auditForm.surveyTemplateId = '9368f1cf-77e7-49fe-8502-4a7a2da99668'
- this.loadTemplateData()
- }
- })
- },
- // 获取所有模板类型为固定表的所有启用成本调查表数据
- getActiveCostVerifyFormListByType() {
- getActiveCostVerifyFormListByType().then((res) => {
- if (res.code === 200) {
- this.surveyFormList = res.value
- }
- })
- },
- // 获取所有状态为启用的成本核定表模板数据
- getActiveCostVerifyFormList() {
- getActiveCostVerifyFormList().then((res) => {
- if (res.code === 200) {
- this.auditFormList = res.value
- }
- })
- },
- // TemplateTypeChange
- handleTemplateTypeChange(val) {
- if (this.auditForm.templateType == '1') {
- this.historyTemplate = ''
- } else if (this.auditForm.templateType == '2') {
- this.dataTable = ''
- }
- },
- // 模板生成操作
- handleGenerateTemplate() {
- // 提示生成后不能修改
- this.$confirm(
- '生成后不能修改根据调查表生成还是根据历史核定模板生成,确定生成模板吗?',
- '提示',
- {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- type: 'warning',
- }
- ).then(() => {
- // 校验表单
- this.$refs['auditForm'].validate((valid) => {
- if (valid) {
- if (this.auditForm.templateType == '1') {
- if (!this.auditForm.dataTable) {
- this.$message.error('请选择成本调查表模板')
- return
- }
- this.generateFromSurveyTemplate()
- } else if (this.auditForm.templateType == '2') {
- if (!this.auditForm.historyTemplate) {
- this.$message.error('请选择历史核定模板')
- return
- }
- this.generateFromHistoryTemplate()
- }
- // this.$message({ type: 'success', message: '模板生成成功' })
- } else {
- this.$message.error('请填写表单数据')
- return
- }
- })
- })
- },
- // 根据调查表生成模板
- async generateFromSurveyTemplate() {
- try {
- // 保存模板基本信息
- let data = await generateCostVerifyForm({
- catalogId: this.auditForm.catalogId,
- templatename: this.auditForm.surveyTemplateName,
- templateId: this.auditForm.dataTable,
- taskId: this.selectedProject.taskId,
- })
- this.auditForm.surveyTemplateId = data.value
- ? data.value.surveyTemplateId
- : ''
- // 设置uploadId
- if (data.value) {
- this.auditForm.uploadId =
- data.value.id || data.value.templateId || ''
- }
- this.loadTemplateDataForEdit(this.auditForm.surveyTemplateId)
- } catch (error) {
- console.error('生成模板失败:', error)
- } finally {
- }
- },
- // 根据历史核定模板生成
- async generateFromHistoryTemplate() {
- // 保存模板基本信息
- let data = await generateCostVerifyFormData({
- catalogId: this.auditForm.catalogId,
- templatename: this.auditForm.surveyTemplateName,
- templateId: this.auditForm.historyTemplate,
- taskId: this.selectedProject.taskId,
- })
- this.auditForm.surveyTemplateId = data.value
- ? data.value.surveyTemplateId
- : ''
- this.loadTemplateDataForEdit(this.auditForm.surveyTemplateId)
- },
- // 回显数据用
- async loadTemplateData(surveyTemplateId) {
- // 先获取表格数据
- const tableDataRes = await getCostFormVersionsByTemplateId({
- taskId: this.selectedProject.taskId,
- // surveyTemplateId: '',
- })
- // 处理表格数据
- if (tableDataRes.code == 200) {
- this.auditForm.surveyTemplateId =
- tableDataRes.value.itemlist[0].surveyTemplateId
- // 有数据后再获取表头数据
- const tableHeadersRes = await getlistBySurveyTemplateId({
- // taskId: this.selectedProject.taskId,
- surveyTemplateId: this.auditForm.surveyTemplateId,
- })
- getVerifyTemplateDetail({
- id: this.auditForm.surveyTemplateId,
- }).then((res) => {
- this.auditForm.surveyTemplateName = res.value.surveyTemplateName
- this.auditForm.catalogId = res.value.catalogId
- this.auditForm.templateType = res.value.createmode
- if (res.value.createmode == '1') {
- this.auditForm.dataTable = res.value.createtemplateid
- } else if (res.value.createmode == '2') {
- this.auditForm.historyTemplate = res.value.createtemplateid
- }
- // 设置uploadId以便数据回显
- this.auditForm.uploadId = res.value.id || res.value.templateId || ''
- })
- // 处理表头数据
- if (tableHeadersRes.code == 200) {
- this.parseAndDisplayTableHeaders(tableHeadersRes)
- this.parseAndDisplayTableData(tableDataRes)
- await this.tryEchoUploadData()
- }
- }
- },
- async loadTemplateDataForEdit(surveyTemplateId) {
- // 并行获取表头和表格数据
- const [tableHeadersRes, tableDataRes] = await Promise.all([
- getlistBySurveyTemplateId({
- taskId: this.selectedProject.taskId,
- surveyTemplateId: this.auditForm.surveyTemplateId,
- }),
- getCostFormVersionsByTemplateId({
- taskId: this.selectedProject.taskId,
- surveyTemplateId: this.auditForm.surveyTemplateId,
- }),
- ])
- // 处理表头数据
- if (tableHeadersRes.code == 200) {
- this.parseAndDisplayTableHeaders(tableHeadersRes)
- }
- // 处理表格数据
- if (tableDataRes.code == 200) {
- // 在这里也设置uploadId
- getVerifyTemplateDetail({
- id: this.auditForm.surveyTemplateId,
- }).then((res) => {
- if (res && res.code === 200 && res.value) {
- this.auditForm.uploadId =
- res.value.id || res.value.templateId || ''
- }
- })
- this.parseAndDisplayTableData(tableDataRes)
- await this.tryEchoUploadData()
- }
- },
- // 根据已存在的上传数据进行回显(若有)
- async tryEchoUploadData() {
- try {
- const uploadId = (this.auditForm && this.auditForm.uploadId) || ''
- const auditedUnitId = this.auditedUnitId || ''
- const taskId =
- (this.selectedProject && this.selectedProject.taskId) || ''
- // if (!uploadId || !auditedUnitId) return
- const params = {
- // uploadId,
- // auditedUnitId,
- type: '3',
- taskId: taskId,
- }
- const res = await getSurveyDetail(params)
- if (res && res.code === 200 && res.value) {
- const triplets = Array.isArray(res.value)
- ? res.value
- : res.value.items || res.value.records || []
- if (!Array.isArray(triplets) || triplets.length === 0) return
- // 建立字段名映射:rkey(中文列名) -> fieldEname(表格prop)
- const headerMap = {}
- ;(this.tableHeadersRes || []).forEach((h) => {
- if (h && h.fieldName && h.fieldEname)
- headerMap[h.fieldName] = h.fieldEname
- })
- // 行索引:rowid -> 行对象
- const rowMap = new Map()
- ;(this.costAuditData || []).forEach((row) => {
- if (row && row.rowid !== undefined && row.rowid !== null) {
- rowMap.set(String(row.rowid), row)
- }
- })
- // 应用回显
- triplets.forEach((item) => {
- const rowid = item.rowid || item.rowId || item.ROWID
- const rkey = item.rkey || item.rKey || item.RKEY
- const rvalue = item.rvalue || item.rValue || item.RVALUE
- if (!rowid || !rkey) return
- const row = rowMap.get(String(rowid))
- const prop = headerMap[rkey]
- if (row && prop) {
- row[prop] = rvalue != null ? String(rvalue) : ''
- }
- })
- // 强制刷新
- this.costAuditData = [...this.costAuditData]
- this.computeApprovedForAllRows()
- }
- } catch (e) {
- console.warn('回显上传数据失败:', e)
- }
- },
- // 单元格输入联动:当账面值或审核调整值变化时,自动计算核定值
- handleCellInput(row, item) {
- if (!row) return
- // 若未传入列信息,则对该行全部年份重算
- if (!item || !item.prop) {
- this.computeApprovedForRow(row)
- return
- }
- const m = String(item.prop).match(
- /^year(\d{4})(BookValue|Audit|ApprovedValue)$/
- )
- if (!m) {
- this.computeApprovedForRow(row)
- return
- }
- const year = m[1]
- const bookProp = `year${year}BookValue`
- const auditProp = `year${year}Audit`
- const approvedProp = `year${year}ApprovedValue`
- const a = parseFloat(row[bookProp])
- const b = parseFloat(row[auditProp])
- const aNum = isNaN(a) ? 0 : a
- const bNum = isNaN(b) ? 0 : b
- // 若两者皆为空字符串则清空核定值;否则计算和
- if (
- (row[bookProp] === '' || row[bookProp] === undefined) &&
- (row[auditProp] === '' || row[auditProp] === undefined)
- ) {
- this.$set(row, approvedProp, '')
- } else {
- this.$set(row, approvedProp, String(aNum + bNum))
- }
- },
- // 针对单行,遍历存在的年份字段进行重新计算
- computeApprovedForRow(row) {
- if (!row) return
- const map = this.yearPropMap || {}
- Object.keys(map).forEach((year) => {
- const bookProp = map[year].book
- const auditProp = map[year].audit
- const approvedProp = map[year].approved
- if (!bookProp || !auditProp || !approvedProp) return
- const a = parseFloat(row[bookProp])
- const b = parseFloat(row[auditProp])
- const aNum = isNaN(a) ? 0 : a
- const bNum = isNaN(b) ? 0 : b
- if (
- (row[bookProp] === '' || row[bookProp] === undefined) &&
- (row[auditProp] === '' || row[auditProp] === undefined)
- ) {
- this.$set(row, approvedProp, '')
- } else {
- this.$set(row, approvedProp, String(aNum + bNum))
- }
- })
- },
- // 针对全表,批量重新计算核定值
- computeApprovedForAllRows() {
- if (!Array.isArray(this.costAuditData)) return
- this.costAuditData.forEach((row) => this.computeApprovedForRow(row))
- },
- parseAndDisplayTableHeaders(res) {
- this.tableHeadersRes = Array.isArray(res.value) ? res.value : []
- if (this.tableHeadersRes.length > 0) {
- // 重置年份映射
- this.yearPropMap = {}
- this.auditForm.surveyTemplateId = res.value[0].surveyTemplateId
- // 表头按照orderNum重新排序
- this.tableHeadersRes.sort((a, b) => a.orderNum - b.orderNum)
- this.costAuditcolumn = [] // 清空现有列配置
- this.tableHeadersRes.forEach((item) => {
- let column = {
- ...item,
- prop: item.fieldEname,
- label: item.fieldName,
- // 自动宽度:仅"序号"使用固定宽,其余使用最小宽度并开启溢出提示
- width: item.fieldName == '序号' ? '80px' : undefined,
- minWidth: item.fieldName == '序号' ? undefined : '150px',
- align: 'center',
- fieldType: item.fieldType,
- fieldTypelen: item.fieldTypelen,
- isDict: item.isDict,
- dictCode: item.dictCode,
- showOverflowTooltip: item.fieldName == '序号' ? false : true,
- }
- this.costAuditcolumn.push(column)
- // 基于表头中文名构建年份映射
- const name = item.fieldName || item.label || ''
- const prop = item.fieldEname || item.prop || ''
- const m = String(name).match(
- /^(\d{4})年(账面值|审核调整值|核定值)$/
- )
- if (m && prop) {
- const year = m[1]
- const kind = m[2]
- if (!this.yearPropMap[year]) this.yearPropMap[year] = {}
- if (kind === '账面值') this.yearPropMap[year].book = prop
- else if (kind === '审核调整值')
- this.yearPropMap[year].audit = prop
- else if (kind === '核定值') this.yearPropMap[year].approved = prop
- }
- })
- // 若表头未包含“单位”列,则追加;已包含则不重复添加
- const hasUnitCol = this.costAuditcolumn.some(
- (c) => c && (c.label === '单位' || c.fieldName === '单位')
- )
- if (!hasUnitCol) {
- this.costAuditcolumn.push({
- prop: 'unit',
- label: '单位',
- width: '80px',
- align: 'center',
- })
- }
- // 检查tableHeadersRes数组是否包含年账面值
- const hasBookValueColumn = this.checkHasBookValueColumn()
- if (!hasBookValueColumn && this.selectedProject.auditPeriod) {
- // 获取审计期间并按年份排序
- let auditPeriod = this.selectedProject.auditPeriod
- .split(',')
- .map((year) => parseInt(year))
- .sort((a, b) => a - b)
- .map((year) => year.toString())
- let num = this.tableHeadersRes.length
- // 按年份顺序生成三个字段
- auditPeriod.forEach((item) => {
- // 账面价值字段
- let bookValueColumn = {
- fieldEname: 'year' + item + 'BookValue',
- prop: 'year' + item + 'BookValue',
- label: item + '年账面值',
- width: '120px',
- align: 'right',
- fieldName: item + '年账面值',
- fieldType: 'integer',
- format: '',
- fieldTypelen: '255',
- fieldTypenointlen: '',
- isAuditPeriod: 'true',
- isRequired: 'true',
- showVisible: '1',
- isDict: 'false',
- dictid: '',
- dictValue: '',
- tabtype: this.tableHeadersRes[0].tabtype,
- surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
- versionId: this.tableHeadersRes[0].versionId,
- orderNum: this.getMaxOrderNum() + 1,
- }
- this.costAuditcolumn.push(bookValueColumn)
- this.tableHeadersRes.push(bookValueColumn)
- // 映射
- if (!this.yearPropMap[item]) this.yearPropMap[item] = {}
- this.yearPropMap[item].book = bookValueColumn.prop
- // 审核字段
- let auditColumn = {
- fieldEname: 'year' + item + 'Audit',
- prop: 'year' + item + 'Audit',
- label: item + '年审核调整值',
- width: '150px',
- align: 'center',
- fieldName: item + '年审核调整值',
- fieldType: 'integer',
- format: '',
- fieldTypelen: '9',
- fieldTypenointlen: '',
- isRequired: 'true',
- isAuditPeriod: 'true',
- showVisible: '1',
- isDict: 'false',
- dictid: '',
- dictValue: '',
- tabtype: this.tableHeadersRes[0].tabtype,
- surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
- versionId: this.tableHeadersRes[0].versionId,
- orderNum: this.getMaxOrderNum() + num + 1,
- }
- this.costAuditcolumn.push(auditColumn)
- this.tableHeadersRes.push(auditColumn)
- this.yearPropMap[item].audit = auditColumn.prop
- // 核定值字段
- let approvedValueColumn = {
- fieldEname: 'year' + item + 'ApprovedValue',
- prop: 'year' + item + 'ApprovedValue',
- label: item + '年核定值',
- width: '120px',
- align: 'right',
- fieldName: item + '年核定值',
- fieldType: 'integer',
- format: '',
- fieldTypelen: '255',
- fieldTypenointlen: '',
- isRequired: 'true',
- isAuditPeriod: 'true',
- showVisible: '1',
- isDict: 'false',
- dictid: '',
- dictValue: '',
- tabtype: this.tableHeadersRes[0].tabtype,
- surveyTemplateId: this.tableHeadersRes[0].surveyTemplateId,
- versionId: this.tableHeadersRes[0].versionId,
- orderNum: this.getMaxOrderNum() + num + 1,
- }
- this.costAuditcolumn.push(approvedValueColumn)
- this.tableHeadersRes.push(approvedValueColumn)
- this.yearPropMap[item].approved = approvedValueColumn.prop
- })
- }
- }
- },
- getMaxOrderNum() {
- if (!this.tableHeadersRes || this.tableHeadersRes.length === 0) {
- return 0
- }
- const maxOrderNum = Math.max(
- ...this.tableHeadersRes.map((item) => item.orderNum || 0)
- )
- return maxOrderNum
- },
- // 检查tableHeadersRes数组是否包含年账面值列
- checkHasBookValueColumn() {
- if (!this.tableHeadersRes || this.tableHeadersRes.length === 0) {
- return false
- }
- // 检查是否有列的label或fieldName包含'年账面值'字样
- return this.tableHeadersRes.some((item) => {
- return (
- (item.label && item.label.includes('年账面值')) ||
- (item.fieldName && item.fieldName.includes('年账面值'))
- )
- })
- },
- parseAndDisplayTableData(res) {
- // 清空现有数据
- this.costAuditData = []
- if (
- res &&
- res.value &&
- res.value.itemlist &&
- res.value.itemlist.length > 0
- ) {
- let headers = this.tableHeadersRes
- let itemlist = res.value.itemlist
- // 遍历每个数据项
- itemlist.forEach((item, index) => {
- // 为每个数据项创建一个完整的对象
- // 判断是否为子项(parentid不为-1且不为"-1")
- const isSubItem =
- item.parentid && item.parentid !== -1 && item.parentid !== '-1'
- let rowData = {
- ...item,
- isChild: isSubItem,
- isSubItem: isSubItem,
- }
- // 遍历表头,将字段值映射到对应的列
- headers.forEach((header) => {
- if (header && header.fieldEname && header.fieldName) {
- let fieldEname = header.fieldEname
- let fieldName = header.fieldName
- // 优先用中文列名取值,不存在则用英文prop取值
- let fieldValue =
- (item &&
- (item[fieldName] != null ? item[fieldName] : undefined)) !==
- undefined
- ? item[fieldName]
- : item[fieldEname] || ''
- // 将字段值添加到行数据中
- rowData[fieldEname] = fieldValue
- rowData.rkey = fieldName
- rowData.rvalue = fieldValue
- }
- })
- // if (this.selectedProject && this.selectedProject.auditPeriod) {
- // // 为审计期间的三个字段添加初始值
- // // 获取审计期间并按年份排序
- // let auditPeriod = this.selectedProject.auditPeriod
- // .split(',')
- // .map((year) => parseInt(year))
- // .sort((a, b) => a - b)
- // .map((year) => year.toString())
- // // 为每个年份添加三个字段的初始值,使用与表头定义一致的属性名
- // auditPeriod.forEach((year) => {
- // rowData[`year${year}BookValue`] = '' // 账面值
- // rowData[`year${year}Audit`] = '' // 审核调整值
- // rowData[`year${year}ApprovedValue`] = '' // 核定值
- // })
- // }
- // 添加完整的行数据到表格数据中
- this.costAuditData.push(rowData)
- })
- // 平铺顺序:父项在前、子项紧随其后
- const sortFn = (a, b) =>
- Number(a.orderNum || 0) - Number(b.orderNum || 0)
- const byRowId = new Map()
- const parents = []
- const childGroups = new Map()
- this.costAuditData.forEach((row) => {
- if (row && row.children) delete row.children
- const key = row.rowid != null ? String(row.rowid) : ''
- if (key) byRowId.set(key, row)
- const pid = row.parentid
- const isParent =
- pid === -1 || pid === '-1' || pid === null || pid === undefined
- if (isParent) {
- parents.push(row)
- } else {
- const pKey = pid != null ? String(pid) : ''
- if (!childGroups.has(pKey)) childGroups.set(pKey, [])
- childGroups.get(pKey).push(row)
- }
- })
- parents.sort(sortFn)
- const flat = []
- const seen = new Set()
- parents.forEach((p) => {
- flat.push(p)
- seen.add(p)
- const group = childGroups.get(String(p.rowid)) || []
- group.sort(sortFn).forEach((c) => {
- flat.push(c)
- seen.add(c)
- })
- })
- // 处理找不到父项的子项:放在末尾
- this.costAuditData.forEach((row) => {
- if (!seen.has(row)) flat.push(row)
- })
- this.costAuditData = flat
- // 平铺完成后统一计算核定值
- this.computeApprovedForAllRows()
- }
- },
- handleSaveTemplate(type) {
- // 显示加载状态
- this.$loading({
- lock: true,
- text: '保存数据中...',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)',
- })
- // 加上遮罩层
- const headersList = this.tableHeadersRes.map((header, index) => ({
- ...header,
- orderNum: header.orderNum || index + 1,
- }))
- let splitData = this.splitFixedTableDataForSave(this.costAuditData)
- let data = {
- costVerifyTemplateId: this.auditForm.surveyTemplateId,
- headersList: headersList,
- itemsList: splitData,
- }
- batchSaveOrUpdate(data)
- .then((data) => {
- // 关闭加载状态
- this.$loading().close()
- if (type != 'delete') {
- this.$message.success('保存成功')
- this.loadTemplateData()
- }
- })
- .catch((err) => {
- // 关闭加载状态
- this.$loading().close()
- console.log(err)
- })
- },
- async handleSaveData() {
- const loading = this.$loading({
- lock: true,
- text: '保存数据中...',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)',
- })
- try {
- // 1) 基于当前表格数据生成保存明细
- const rawItems =
- this.splitFixedTableDataForSave(this.costAuditData) || []
- const auditedUnitId =
- this.auditedUnitId || this.auditForm.auditedUnitId || ''
- const surveyTemplateId =
- this.auditForm.surveyTemplateId || this.auditForm.dataTable || ''
- const catalogId = this.auditForm.catalogId || ''
- const hasData = !!(this.auditForm && this.auditForm.uploadId)
- const taskId =
- (this.selectedProject && this.selectedProject.taskId) || ''
- console.log('rawItems', rawItems)
- const finalSaveData = rawItems.map((it) => {
- const base = {
- rowid: it.rowid,
- rkey: it.rkey,
- rvalue: it.rvalue != null ? String(it.rvalue) : '',
- auditedUnitId,
- surveyTemplateId,
- catalogId,
- taskId,
- // id: it.id,
- parentId: it.parentid || '-1',
- // refId: taskId,
- type: '3',
- // uploadId: '',
- }
- if (hasData) base.uploadId = this.auditForm.uploadId
- return base
- })
- // 2) 调用保存接口
- const res = await saveSingleRecordSurvey(finalSaveData)
- if (res && res.code === 200) {
- this.$message.success('保存成功')
- this.loadTemplateData && this.loadTemplateData()
- await this.tryEchoUploadData()
- } else {
- this.$message.error((res && res.message) || '保存失败')
- }
- } catch (err) {
- console.error(err)
- // this.$message.error('保存失败')
- } finally {
- loading.close()
- }
- },
- //分割字符串
- stringToObjects(str) {
- const items = str.split(',')
- return items.map((item) => ({
- rkey: item,
- rvalue: '',
- }))
- },
- splitFixedTableDataForSave(
- tables = this.costAuditData,
- headers = this.tableHeadersRes
- ) {
- let fixedHeaders = headers
- let fixedTables = tables
- let fixedFields = fixedHeaders
- .map((header) => header.fieldName)
- .join(',')
- let fixedTitles = this.stringToObjects(fixedFields || '')
- // 结果数组
- const result = []
- const processNode = (node, parentRowIndex = 0) => {
- // 确保node和fixedValues存在
- if (!node) {
- console.warn('遇到空节点,跳过处理')
- return
- }
- // 确保fixedValues属性存在,如果不存在则初始化为空对象
- if (!node.fixedValues) {
- node.fixedValues = {}
- }
- // 为每个固定列创建一条记录
- fixedTitles.forEach((title) => {
- // 找到对应的表头信息
- const correspondingHeader = fixedHeaders.find(
- (header) => header.fieldName === title.rkey
- )
- if (!correspondingHeader) {
- return
- }
- const newItem = {
- rkey: title.rkey,
- rvalue:
- node[correspondingHeader.prop] !== undefined &&
- node[correspondingHeader.prop] !== null
- ? node[correspondingHeader.prop]
- : node[correspondingHeader.fieldEname] !== undefined &&
- node[correspondingHeader.fieldEname] !== null
- ? node[correspondingHeader.fieldEname]
- : '',
- [correspondingHeader.fieldName]:
- node[correspondingHeader.fieldEname] !== undefined &&
- node[correspondingHeader.fieldEname] !== null
- ? node[correspondingHeader.fieldEname]
- : '',
- surveyTemplateId:
- node.surveyTemplateId || correspondingHeader.surveyTemplateId,
- versionId: node.versionId || correspondingHeader.versionId,
- tabtype: correspondingHeader.tabtype || node.tabtype,
- // 添加 headersId 字段(表头的id)
- headersId: correspondingHeader ? correspondingHeader.id : null,
- // 添加记录的id(itemlist中每条记录的id)
- id: node.id || null,
- // 添加父子关系字段
- parentid: node.parentid || -1, // 父项ID,默认为-1表示无父项
- isChild: node.isChild || false, // 是否为子项
- // 添加 rowid 字段
- rowid: node.rowid || null,
- // 添加计算公式相关字段
- calculationFormula: node.calculationFormula || null,
- jsonstr: node.jsonstr || null,
- orderNum:
- typeof node.orderNum === 'number'
- ? node.orderNum
- : parseInt(node.orderNum, 10) || 0,
- // 添加用户需要的其他字段
- orderText: node.orderText || '',
- percentage: node.percentage || '',
- unit: node.unit || '',
- }
- // 添加其他固定表特有的字段
- if (!node.isSubItem) {
- newItem.cellCode = node.cellCode || ''
- newItem.unit = node.unit || ''
- }
- // 添加其他可能需要的字段,但排除特定字段
- Object.keys(node).forEach((key) => {
- if (
- !(key in newItem) &&
- key !== 'fixedValues' &&
- key !== 'itemId' &&
- key !== 'id' &&
- key !== 'parentid' &&
- key !== 'isChild' &&
- key !== 'isSubItem' &&
- key !== 'rowid' &&
- key !== 'jsonstr' &&
- key !== 'calculationFormula' &&
- key !== 'children' // 排除children字段
- ) {
- newItem[key] = node[key]
- }
- })
- result.push(newItem)
- })
- }
- fixedTables.forEach((row) => {
- processNode(row)
- })
- // 首先收集所有父节点的orderNum,确保不与子节点冲突
- const parentOrderNums = new Set()
- // 第一次遍历:识别父节点并收集它们的orderNum
- result.forEach((item) => {
- // 假设isChild为false或parentid为-1的是父节点
- if (!item.isChild || item.parentid === -1) {
- parentOrderNums.add(item.orderNum)
- }
- })
- // 创建映射来跟踪已使用的orderNum
- const usedOrderNums = new Set([...parentOrderNums])
- let nextAvailableOrderNum = 1
- // 找到当前最大的orderNum,作为新orderNum的起点
- const allOrderNums = result
- .map((item) => item.orderNum)
- .filter((num) => typeof num === 'number' && !isNaN(num))
- if (allOrderNums.length > 0) {
- nextAvailableOrderNum = Math.max(...allOrderNums) + 1
- }
- // 第二次遍历:为子节点分配唯一的orderNum
- result.forEach((item) => {
- // 只为子节点重新分配orderNum
- if (item.isChild && item.parentid !== -1) {
- // 找到下一个未使用的orderNum
- while (usedOrderNums.has(nextAvailableOrderNum)) {
- nextAvailableOrderNum++
- }
- // 分配新的orderNum并标记为已使用(保持原有顺序,不修改行原始顺序号)
- item.orderNum = item.orderNum
- usedOrderNums.add(nextAvailableOrderNum)
- nextAvailableOrderNum++
- }
- })
- return result
- },
- //
- handleImportData() {
- let loading = null
- // 第一步:创建文件选择器
- const input = document.createElement('input')
- input.type = 'file'
- input.accept = '.xls,.xlsx,.csv' // 允许的文件类型
- input.onchange = async (event) => {
- const file = event.target.files[0]
- if (!file) return
- try {
- // 校验文件大小(50MB)
- const maxSize = 50 * 1024 * 1024 // 50MB
- if (file.size > maxSize) {
- this.$message.error('文件大小不能超过50MB!')
- return
- }
- // 校验文件格式
- const allowedFormats = ['.xls', '.xlsx', 'csv']
- const fileName = file.name.toLowerCase()
- const isValidFormat = allowedFormats.some((format) =>
- fileName.endsWith(format)
- )
- if (!isValidFormat) {
- this.$message.error('只允许上传.xls,.xlsx,.csv格式的文件!')
- return
- }
- // 显示遮罩层
- loading = this.$baseLoading(1, '文件上传中...')
- // 第三步:创建FormData并上传文件
- const formData = new FormData()
- formData.append('file', file)
- // 其他参数作为表单字段传递
- formData.append('surveyTemplateId', this.auditForm.surveyTemplateId)
- formData.append('taskId', this.selectedProject.taskId)
- formData.append('materialId', '')
- formData.append('periodRecordId', '')
- formData.append('type', 3)
- // 调用新的导入接口
- const uploadRes = await importData(formData)
- // 第四步:检查上传结果
- if (!uploadRes.state) {
- this.$message.error('导入失败!')
- return
- }
- this.$message.success('导入成功')
- this.loadTemplateData()
- // this.$emit('refresh', this.project.projectId) // 通知父组件刷新
- } catch (error) {
- // 错误处理
- // this.$message.error('操作失败:' + (error.message || '未知错误'))
- } finally {
- // 关闭遮罩层
- loading.close()
- }
- }
- // 触发文件选择
- input.click()
- },
- handleExportTemplate() {
- if (this.costAuditData.length === 0) {
- return
- }
- // 显示加载状态
- const loading = this.$loading({
- lock: true,
- text: '文件下载中...',
- spinner: 'el-icon-loading',
- background: 'rgba(0, 0, 0, 0.7)',
- })
- // 调用新的导出API
- downloadTemplate({
- surveyTemplateId: this.auditForm.surveyTemplateId,
- versionId: this.tableHeadersRes[0].versionId || '',
- type: 3,
- })
- .then((res) => {
- // 从响应头获取文件名(如果有)
- let fileName = `成本审核模板_${new Date()
- .toLocaleString()
- .replace(/[:\s]/g, '_')}.xlsx`
- if (res.headers && res.headers['content-disposition']) {
- const contentDisposition = res.headers['content-disposition']
- const match = contentDisposition.match(/filename=([^;]+)/i)
- if (match && match[1]) {
- fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
- }
- }
- // 使用a标签方式下载文件
- const blobData = new Blob([res.data], {
- type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- })
- // 创建URL对象
- const url = window.URL.createObjectURL(blobData)
- // 创建a标签
- const a = document.createElement('a')
- a.style.display = 'none'
- a.href = url
- a.download = fileName // 设置下载文件名
- // 添加到DOM并触发点击
- document.body.appendChild(a)
- a.click()
- // 关闭加载状态
- loading.close()
- // 清理
- setTimeout(() => {
- document.body.removeChild(a)
- window.URL.revokeObjectURL(url) // 释放URL对象,避免内存泄漏
- }, 100)
- })
- .catch((error) => {
- // 关闭加载状态
- loading.close()
- console.error('文件下载失败:', error)
- })
- },
- handleExportData() {
- this.$message({ type: 'info', message: '导出数据' })
- },
- // handleSaveData() {
- // this.$message({ type: 'success', message: '成本审核数据已保存' })
- // },
- handleRemark(row, field) {
- this.$prompt('请输入说明', '提示', {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- inputValue: row[field],
- })
- .then(({ value }) => {
- row[field] = value
- this.$message({ type: 'success', message: '说明已保存' })
- })
- .catch(() => {
- this.$message({ type: 'info', message: '已取消' })
- })
- },
- // 按层级关系排序表格数据,子项排在父项后面
- sortItemsByHierarchy() {
- if (!this.costAuditData || this.costAuditData.length === 0) {
- return
- }
- // 构建父子关系映射
- const itemMap = new Map()
- const rootItems = []
- const childrenMap = new Map()
- const processedItems = new Set() // 用于避免循环引用
- // 初始化映射和找出根节点
- this.costAuditData.forEach((item) => {
- const currentId = item.id || item.itemId
- if (currentId !== undefined) {
- itemMap.set(currentId, item)
- }
- // 检查是否有有效父ID
- const parentId = item.parentId || item.parentItemId
- const hasValidParent =
- parentId !== undefined &&
- parentId !== null &&
- parentId !== '' &&
- parentId !== -1
- if (!hasValidParent) {
- // 没有有效父ID的是根节点
- rootItems.push(item)
- } else {
- // 有父ID的添加到子节点映射中
- if (!childrenMap.has(parentId)) {
- childrenMap.set(parentId, [])
- }
- childrenMap.get(parentId).push(item)
- }
- })
- // 深度优先遍历生成排序后的数据
- const sortedData = []
- function traverse(item) {
- const currentId = item.id || item.itemId
- // 避免循环引用
- if (processedItems.has(currentId)) {
- return
- }
- // 标记为已处理
- processedItems.add(currentId)
- // 添加当前项
- sortedData.push(item)
- // 获取当前项的子项并递归遍历
- const children = childrenMap.get(currentId) || []
- // 对子项按照orderNum或id进行排序
- children.sort((a, b) => {
- if (a.orderNum !== undefined && b.orderNum !== undefined) {
- return a.orderNum - b.orderNum
- }
- const aId = a.id || a.itemId || 0
- const bId = b.id || b.itemId || 0
- return aId - bId
- })
- // 递归处理每个子项
- children.forEach((child) => {
- traverse(child)
- })
- }
- // 对根节点按照orderNum或id进行排序
- rootItems.sort((a, b) => {
- if (a.orderNum !== undefined && b.orderNum !== undefined) {
- return a.orderNum - b.orderNum
- }
- const aId = a.id || a.itemId || 0
- const bId = b.id || b.itemId || 0
- return aId - bId
- })
- // 从根节点开始遍历
- rootItems.forEach((root) => {
- traverse(root)
- })
- // 如果有未被包含的项目(可能没有正确的父子关系),直接添加到末尾
- if (sortedData.length < this.costAuditData.length) {
- this.costAuditData.forEach((item) => {
- const currentId = item.id || item.itemId
- if (currentId !== undefined && !processedItems.has(currentId)) {
- sortedData.push(item)
- processedItems.add(currentId)
- }
- })
- }
- // 更新表格数据为排序后的数据
- this.costAuditData = sortedData
- // 更新序号字段而非覆盖原始ID
- // this.costAuditData.forEach((item, index) => {
- // // 创建或更新序号字段,保留原始ID不变
- // item.index = index + 1
- // })
- },
- handleAddItem(row) {
- // 判断是否为父项(可添加子项)
- if (row.parentid !== '-1') {
- this.$message.error('只能在父项上添加子项')
- return
- }
- // 获取当前父项的所有子项
- const parentRowId = row.rowid // 使用当前行的rowid作为父ID
- const children = this.costAuditData.filter(
- (item) => item.parentid === parentRowId
- )
- // 找到当前父项的最后一个子项的 orderNum
- let maxOrderNum = 0
- children.forEach((child) => {
- if (child.orderNum > maxOrderNum) {
- maxOrderNum = child.orderNum
- }
- })
- // 新行的 orderNum 为最大子项 orderNum + 1
- const newOrderNum = maxOrderNum + 1
- // 创建新行:作为当前父项的子项
- const newItem = {
- ...row,
- parentId: parentRowId,
- parentid: parentRowId,
- orderNum: newOrderNum,
- rowid: this.generateUUID(),
- id: null,
- rvalue: '',
- }
- console.log('children.length', children.length)
- // 清空字段值
- this.costAuditcolumn.forEach((col) => {
- if (col.label === '序号') {
- newItem[col.prop] = children.length + 1
- } else {
- newItem[col.label] = ''
- newItem[col.prop] = ''
- }
- })
- // 找到父项的最后一个子项在数组中的位置
- let insertIndex = this.costAuditData.length // 默认插入到末尾
- // 遍历数组,找到父项的最后一个子项的位置
- for (let i = 0; i < this.costAuditData.length; i++) {
- // 如果是当前父项的子项,更新插入位置为该子项后一位
- if (this.costAuditData[i].parentid === row.rowid) {
- insertIndex = i + 1
- }
- }
- // 在最后一个子项后面插入新数据
- this.costAuditData.splice(insertIndex, 0, newItem)
- this.$message.success('子项添加成功')
- },
- handleDeleteItem(row) {
- // 显示确认对话框
- this.$confirm(
- '确定要删除此行数据吗?如果删除的是父项,将同时删除其所有子项。',
- '确认删除',
- {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- type: 'warning',
- }
- )
- .then(() => {
- // 获取要删除的行ID
- const rowId = row.rowId || row.id
- // 收集要删除的行索引
- const indicesToDelete = []
- // 查找要删除的行及其子项
- for (let i = 0; i < this.costAuditData.length; i++) {
- const item = this.costAuditData[i]
- // 如果是要删除的行本身,或者是其子项
- if (
- item.rowId === rowId ||
- item.id === rowId ||
- (item.parentId !== '-1' &&
- (item.parentId === rowId || item.parentId === row.id))
- ) {
- indicesToDelete.push(i)
- }
- }
- // 从后往前删除,避免索引偏移
- indicesToDelete
- .sort((a, b) => b - a)
- .forEach((index) => {
- this.costAuditData.splice(index, 1)
- })
- // 更新剩余行的orderNum
- this.updateOrderNumbersAfterDelete(row)
- // 删除行后调用保存模板方法
- this.handleSaveTemplate('delete')
- this.$message.success('行删除成功')
- })
- .catch(() => {
- // 用户取消删除
- this.$message.info('已取消删除操作')
- })
- },
- // 删除行后更新orderNum的方法
- updateOrderNumbersAfterDelete(deletedRow) {
- const deletedOrderNum = deletedRow.orderNum
- const deletedParentId = deletedRow.parentId || '-1'
- // 遍历所有行,更新orderNum
- this.costAuditData.forEach((item) => {
- // 如果是相同父项的子项,或者都是父项(parentId为'-1'),且orderNum大于删除行的orderNum
- if (
- (item.parentId === deletedParentId ||
- (item.parentId === '-1' && deletedParentId === '-1')) &&
- item.orderNum > deletedOrderNum
- ) {
- // 将orderNum减1,保持连续性
- item.orderNum -= 1
- }
- })
- },
- // 生成唯一ID
- generateUUID() {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
- /[xy]/g,
- function (c) {
- const r = (Math.random() * 16) | 0,
- v = c === 'x' ? r : (r & 0x3) | 0x8
- return v.toString(16)
- }
- )
- },
- // 获取字典选项
- async getDictOptions(dictCode) {
- // 如果没有字典代码,返回空数组
- if (!dictCode) {
- return []
- }
- // 检查是否已经缓存了该字典数据
- if (this.dictCache && this.dictCache[dictCode]) {
- return this.dictCache[dictCode]
- }
- try {
- // 从后端获取字典数据
- const response = await getByTypeKey({ typeKey: dictCode })
- let dictOptions = []
- // 处理响应数据
- if (response && Array.isArray(response)) {
- dictOptions = response.map((item) => ({
- value: item.dictValue || item.key || item.value,
- label: item.dictLabel || item.name || item.label,
- }))
- }
- // 缓存字典数据
- if (!this.dictCache) {
- this.dictCache = {}
- }
- this.dictCache[dictCode] = dictOptions
- return dictOptions
- } catch (error) {
- console.error('获取字典数据失败:', error)
- return []
- }
- },
- },
- }
- </script>
- <style scoped>
- /* .app-container {
- padding: 20px;
- } */
- .audit-controls {
- margin-bottom: 20px;
- }
- .audit-controls .el-select {
- margin-right: 10px;
- width: 150px;
- }
- .el-icon {
- font-size: 24px;
- }
- </style>
|