DataRequirementsTab.vue 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  1. <template>
  2. <div>
  3. <!-- 在线填报弹窗(单记录类型,可编辑/只读由 isViewMode/viewModeForDialog 控制) -->
  4. <survey-form-dialog
  5. :visible.sync="surveyFormDialogVisible"
  6. :survey-data="{ ...(currentTemplateRow || {}), ...surveyDetailData }"
  7. :form-fields="formFields"
  8. :is-view-mode="viewModeForDialog"
  9. :audited-unit-id="auditedUnitId"
  10. :request-type="2"
  11. :upload-id="
  12. (currentTemplateRow &&
  13. (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
  14. ''
  15. "
  16. :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
  17. :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
  18. @save="
  19. $emit('handle-survey-form-save', {
  20. row: currentTemplateRow,
  21. formData: $event,
  22. })
  23. "
  24. @refresh="
  25. $emit('handle-survey-form-save', {
  26. row: currentTemplateRow,
  27. formData: {},
  28. })
  29. "
  30. />
  31. <!-- 固定表填报弹窗(可编辑/只读由 isViewMode/viewModeForDialog 控制) -->
  32. <fixed-table-dialog
  33. :visible.sync="fixedTableDialogVisible"
  34. :survey-data="{ ...currentSurveyRow, fixedHeaders }"
  35. :fixed-fields="fixedFields || ''"
  36. :fixed-fieldids="fixedFieldids || ''"
  37. :columns-meta="columnsMeta"
  38. :table-items="tableItems"
  39. :audit-periods="auditPeriods"
  40. :project-audit-periods="auditPeriod"
  41. :project-audit-period="auditPeriod"
  42. :project-id="projectId"
  43. :is-view-mode="viewModeForDialog"
  44. :request-type="2"
  45. :audited-unit-id="auditedUnitId"
  46. :upload-id="
  47. currentSurveyRow && currentSurveyRow.id ? currentSurveyRow.id : uploadId
  48. "
  49. :survey-template-id="
  50. currentSurveyRow && currentSurveyRow.surveyTemplateId
  51. ? currentSurveyRow.surveyTemplateId
  52. : surveyTemplateId
  53. "
  54. :catalog-id="catalogId"
  55. :task-id="taskId"
  56. :cross-table-info="crossTableInfo"
  57. @save="handleFixedTableSave"
  58. @refresh="handleRefresh"
  59. />
  60. <!-- 动态表填报弹窗(可编辑/只读由 isViewMode/viewModeForDialog 控制) -->
  61. <dynamic-table-dialog
  62. :key="dynamicDialogKey"
  63. :visible.sync="dynamicTableDialogVisible"
  64. :survey-data="currentSurveyRow"
  65. :table-data="dynamicTableData"
  66. :table-items="tableItems"
  67. :is-view-mode="viewModeForDialog"
  68. :request-type="2"
  69. :audited-unit-id="auditedUnitId"
  70. :upload-id="
  71. currentSurveyRow && (currentSurveyRow.uploadId || currentSurveyRow.id)
  72. ? currentSurveyRow.uploadId || currentSurveyRow.id
  73. : uploadId
  74. "
  75. :catalog-id="catalogId"
  76. :survey-template-id="
  77. getSurveyTemplateId(currentSurveyRow) || surveyTemplateId
  78. "
  79. @save="handleDynamicTableSave"
  80. @refresh="handleRefresh"
  81. />
  82. <el-button
  83. type="primary"
  84. :disabled="isViewMode"
  85. @click="$emit('handleAddMaterial')"
  86. >
  87. 补充材料
  88. </el-button>
  89. <el-table
  90. style="margin-top: 20px"
  91. border
  92. :data="dataRequirements"
  93. size="mini"
  94. :show-header="true"
  95. :row-class-name="getRowClassName"
  96. >
  97. <el-table-column prop="seq" label="序号" width="80" align="center">
  98. <template slot-scope="scope">
  99. <span v-if="!scope.row.isCategoryHeader">
  100. {{ scope.row.seq || scope.row.index }}
  101. </span>
  102. </template>
  103. </el-table-column>
  104. <el-table-column
  105. prop="informationName"
  106. label="报送资料"
  107. min-width="280"
  108. header-align="center"
  109. align="left"
  110. >
  111. <template slot-scope="scope">
  112. <div v-if="scope.row.isCategoryHeader" class="category-header-cell">
  113. {{ scope.row.categoryName }}
  114. </div>
  115. <span v-else>{{ scope.row.informationName || '-' }}</span>
  116. </template>
  117. </el-table-column>
  118. <el-table-column
  119. prop="formatRequired"
  120. label="资料类型"
  121. width="130"
  122. align="center"
  123. >
  124. <template slot-scope="scope">
  125. <span v-if="!scope.row.isCategoryHeader">
  126. <span
  127. v-if="
  128. scope.row.formatRequired !== null &&
  129. scope.row.formatRequired !== undefined
  130. "
  131. >
  132. {{
  133. getDictName('formatAsk', String(scope.row.formatRequired)) ||
  134. scope.row.formatRequired
  135. }}
  136. </span>
  137. <span v-else>-</span>
  138. </span>
  139. </template>
  140. </el-table-column>
  141. <el-table-column
  142. prop="isRequired"
  143. label="是否必填"
  144. width="110"
  145. align="center"
  146. >
  147. <template slot-scope="scope">
  148. <span v-if="!scope.row.isCategoryHeader">
  149. {{ scope.row.isRequired === '1' ? '是' : '否' }}
  150. </span>
  151. </template>
  152. </el-table-column>
  153. <el-table-column
  154. prop="isUpload"
  155. label="是否上传"
  156. width="110"
  157. align="center"
  158. >
  159. <template slot-scope="scope">
  160. <span v-if="!scope.row.isCategoryHeader">
  161. <span v-if="scope.row.informationName == '动态表'">
  162. <span
  163. v-if="uploadStatusMap[scope.row.id] === '已上传'"
  164. style="color: #67c23a"
  165. >
  166. {{ uploadStatusMap[scope.row.id] || '-' }}
  167. </span>
  168. <span
  169. v-else-if="uploadStatusMap[scope.row.id] === '未上传'"
  170. class="text-danger"
  171. >
  172. {{ uploadStatusMap[scope.row.id] }}
  173. </span>
  174. <span v-else>-</span>
  175. </span>
  176. <span v-else>
  177. <span
  178. v-if="scope.row.isUpload === 1 || scope.row.isUpload === '1'"
  179. style="color: #67c23a"
  180. >
  181. 已上传
  182. </span>
  183. <span v-else class="text-danger">未上传</span>
  184. </span>
  185. </span>
  186. </template>
  187. </el-table-column>
  188. <el-table-column
  189. prop="isRequired"
  190. label="审核状态"
  191. width="110"
  192. align="center"
  193. >
  194. <template slot-scope="scope">
  195. <span v-if="!scope.row.isCategoryHeader">
  196. <span
  197. v-if="
  198. scope.row.auditedStatus !== null &&
  199. scope.row.auditedStatus !== undefined
  200. "
  201. >
  202. {{
  203. getDictName('clshzt', String(scope.row.auditedStatus)) ||
  204. scope.row.auditedStatus
  205. }}
  206. </span>
  207. <span v-else>-</span>
  208. </span>
  209. </template>
  210. </el-table-column>
  211. <el-table-column prop="operation" label="操作" width="220" align="center">
  212. <template slot-scope="scope">
  213. <template v-if="!scope.row.isCategoryHeader">
  214. <template v-if="String(scope.row.formatRequired) !== '3'">
  215. <!-- 固定表:也支持在线填报(templateType=2) -->
  216. <template v-if="String(scope.row.templateType) === '2'">
  217. <el-button
  218. v-if="scope.row.isUpload === 1 || scope.row.isUpload === '1'"
  219. type="text"
  220. size="small"
  221. @click="handleViewTemplate(scope.row)"
  222. >
  223. 查看
  224. </el-button>
  225. <el-button
  226. type="text"
  227. size="small"
  228. :disabled="isViewMode"
  229. @click="handleOnlineSubmission(scope.row)"
  230. >
  231. 在线填报
  232. </el-button>
  233. </template>
  234. <el-button
  235. v-if="
  236. (scope.row.isUpload === 1 || scope.row.isUpload === '1') &&
  237. String(scope.row.templateType) !== '2'
  238. "
  239. type="text"
  240. size="small"
  241. @click="handleFileView(scope.row)"
  242. >
  243. 查看
  244. </el-button>
  245. <el-button
  246. v-if="
  247. (scope.row.isUpload === 1 || scope.row.isUpload === '1') &&
  248. String(scope.row.templateType) !== '2'
  249. "
  250. type="text"
  251. size="small"
  252. @click="$emit('handleFileDownload', scope.row)"
  253. >
  254. 下载
  255. </el-button>
  256. <el-button
  257. v-if="
  258. scope.row.auditedStatus !== '1' &&
  259. (currentNode === 'clcs' || currentNode === 'tjcl') &&
  260. String(scope.row.templateType) !== '2'
  261. "
  262. type="text"
  263. size="small"
  264. :disabled="isViewMode"
  265. @click="
  266. $emit(
  267. 'handleFileUpload',
  268. scope.row,
  269. getUploadAccept(scope.row)
  270. )
  271. "
  272. >
  273. 上传
  274. </el-button>
  275. </template>
  276. <template v-else>
  277. <!-- v-if="scope.row.isUpload === 1 || scope.row.isUpload === '1'" -->
  278. <el-button
  279. v-if="scope.row.isUpload === 1 || scope.row.isUpload === '1'"
  280. type="text"
  281. size="small"
  282. @click="handleViewTemplate(scope.row)"
  283. >
  284. 查看
  285. </el-button>
  286. <el-button
  287. v-if="scope.row.formatRequired === '3'"
  288. type="text"
  289. size="small"
  290. @click="handleOnlineSubmission(scope.row)"
  291. >
  292. 在线填报
  293. </el-button>
  294. <el-button
  295. v-if="
  296. scope.row.formatRequired === '3' &&
  297. scope.row.templateType !== '1'
  298. "
  299. type="text"
  300. size="small"
  301. @click="handleTemplateDownload(scope.row)"
  302. >
  303. 模版下载
  304. </el-button>
  305. <el-button
  306. v-if="
  307. scope.row.auditedStatus !== '1' &&
  308. (currentNode === 'clcs' || currentNode === 'tjcl') &&
  309. scope.row.formatRequired === '3' &&
  310. scope.row.templateType !== '1' &&
  311. scope.row.informationName !== '动态表' &&
  312. scope.row.templateType !== '3'
  313. "
  314. type="text"
  315. size="small"
  316. :disabled="isViewMode"
  317. @click="triggerDataUpload(scope.row)"
  318. >
  319. 数据上传
  320. </el-button>
  321. </template>
  322. </template>
  323. </template>
  324. </el-table-column>
  325. </el-table>
  326. <input
  327. ref="dataUploadInput"
  328. type="file"
  329. :accept="dataUploadAccept"
  330. style="display: none"
  331. @change="handleDataFileChange"
  332. />
  333. <!-- 单记录弹窗(查看模式) -->
  334. <survey-form-dialog
  335. :visible.sync="singleDialogVisible"
  336. :survey-data="{}"
  337. :is-view-mode="true"
  338. :request-type="2"
  339. :audited-unit-id="auditedUnitId"
  340. :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
  341. :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
  342. :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
  343. />
  344. <!-- 固定表弹窗(查看模式) -->
  345. <fixed-table-dialog
  346. :visible.sync="fixedDialogVisible"
  347. :is-view-mode="true"
  348. :request-type="2"
  349. :project-id="projectId"
  350. :audited-unit-id="auditedUnitId"
  351. :audit-periods="auditPeriods"
  352. :project-audit-periods="auditPeriod"
  353. :project-audit-period="auditPeriod"
  354. :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
  355. :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
  356. :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
  357. :cross-table-info="crossTableInfo"
  358. />
  359. <!-- 动态表弹窗(查看模式) -->
  360. <dynamic-table-dialog
  361. :visible.sync="dynamicDialogVisible"
  362. :is-view-mode="true"
  363. :request-type="2"
  364. :audited-unit-id="auditedUnitId"
  365. :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
  366. :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
  367. :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
  368. />
  369. </div>
  370. </template>
  371. <script>
  372. import { uploadPresetTemplate } from '@/api/auditTaskProcessing'
  373. import {
  374. getSingleRecordSurveyList,
  375. getSurveyDetail,
  376. getDynamicTableData,
  377. downloadTemplate,
  378. importData,
  379. getCrossTableData,
  380. } from '@/api/audit/survey'
  381. import { getListBySurveyTemplateIdAndVersion } from '@/api/costSurveyTemplateHeaders'
  382. import SurveyFormDialog from '@/views/EntDeclaration/auditTaskManagement/components/SurveyFormDialog.vue'
  383. import FixedTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/FixedTableDialog.vue'
  384. import DynamicTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/DynamicTableDialog.vue'
  385. export default {
  386. name: 'DataRequirementsTab',
  387. components: {
  388. SurveyFormDialog,
  389. FixedTableDialog,
  390. DynamicTableDialog,
  391. },
  392. props: {
  393. dataRequirements: {
  394. type: Array,
  395. default: () => [],
  396. },
  397. isViewMode: {
  398. type: Boolean,
  399. default: false,
  400. },
  401. dictData: {
  402. type: Object,
  403. default: () => ({}),
  404. },
  405. currentNode: {
  406. type: String,
  407. default: '',
  408. },
  409. auditedUnitId: {
  410. type: [String, Number],
  411. default: '',
  412. },
  413. // 任务ID(用于上传等场景)
  414. taskId: {
  415. type: [String, Number],
  416. default: '',
  417. },
  418. // 监审期间(与 CostSurveyTab 对齐,便于统一传递给子组件)
  419. auditPeriod: {
  420. type: [String, Array],
  421. default: null,
  422. },
  423. // 以下三个用于与 CostSurveyTab 一致的透传参数
  424. uploadId: {
  425. type: [String, Number],
  426. default: '',
  427. },
  428. surveyTemplateId: {
  429. type: [String, Number],
  430. default: '',
  431. },
  432. catalogId: {
  433. type: [String, Number],
  434. default: '',
  435. },
  436. // 立项信息ID(用于 FixedTableDialog 优先用接口 auditPeriod 渲染年份)
  437. projectId: {
  438. type: [String, Number],
  439. default: '',
  440. },
  441. },
  442. data() {
  443. return {
  444. pendingUploadRow: null,
  445. dataUploadAccept: '.xls,.xlsx',
  446. // 模板查看相关
  447. currentTemplateRow: null,
  448. currentSurveyRow: null,
  449. singleDialogVisible: false,
  450. fixedDialogVisible: false,
  451. dynamicDialogVisible: false,
  452. // 在线填报/查看共用弹窗的只读控制
  453. viewModeForDialog: false,
  454. // 在线填报(编辑)相关
  455. surveyFormDialogVisible: false,
  456. fixedTableDialogVisible: false,
  457. dynamicTableDialogVisible: false,
  458. formFields: [],
  459. surveyDetailData: {},
  460. tableItems: [],
  461. auditPeriods: [],
  462. dynamicTableData: [],
  463. dynamicDialogKey: 0,
  464. fixedDialogKey: 0,
  465. fixedHeaders: null,
  466. // 与 CostSurveyTab 对齐的固定表头派生字段
  467. fixedFields: '',
  468. fixedFieldids: '',
  469. columnsMeta: [],
  470. uploadStatusMap: {},
  471. // 跨表引用数据(与 CostSurveyTab 对齐:按年份分组)
  472. crossTableInfo: {
  473. isCrossTable: false,
  474. crossTableName: '',
  475. data: {},
  476. years: [],
  477. getValue: () => undefined,
  478. },
  479. }
  480. },
  481. // ...
  482. watch: {
  483. auditPeriod: {
  484. immediate: true,
  485. deep: true,
  486. handler(val) {
  487. if (!val) return
  488. if (Array.isArray(val)) {
  489. this.auditPeriods = val.map((p) => String(p))
  490. } else {
  491. const str = String(val).trim()
  492. if (!str) return
  493. if (str.includes(',')) {
  494. this.auditPeriods = str
  495. .split(',')
  496. .map((s) => s.trim())
  497. .filter(Boolean)
  498. } else if (str.includes('-')) {
  499. const parts = str.split('-')
  500. if (parts.length === 2) {
  501. const start = parseInt(parts[0].trim())
  502. const end = parseInt(parts[1].trim())
  503. const years = []
  504. if (!isNaN(start) && !isNaN(end) && end >= start) {
  505. for (let y = start; y <= end; y++) years.push(String(y))
  506. }
  507. this.auditPeriods = years
  508. }
  509. } else {
  510. this.auditPeriods = [str]
  511. }
  512. }
  513. },
  514. },
  515. // 监听dataRequirements变化,预加载所有动态表上传状态
  516. dataRequirements: {
  517. immediate: true,
  518. deep: true,
  519. handler(newVal, oldVal) {
  520. if (newVal && newVal.length > 0) {
  521. this.preloadAllDynamicTableStatus()
  522. }
  523. },
  524. },
  525. },
  526. methods: {
  527. // 异步获取上传状态并直接更新row属性
  528. async fetchUploadStatus(row) {
  529. try {
  530. const uploadId = row.uploadId || row.id || ''
  531. const auditedUnitId = this.auditedUnitId || row.auditedUnitId || ''
  532. const catalogId = row.catalogId || ''
  533. const surveyTemplateId = this.getSurveyTemplateId(row)
  534. const params = {
  535. uploadId,
  536. auditedUnitId,
  537. catalogId,
  538. surveyTemplateId,
  539. type: 2,
  540. }
  541. const res = await getDynamicTableData(params)
  542. // 直接更新row的uploadStatus属性
  543. if (res && res.code === 200) {
  544. const records = res.value?.records || res.value || []
  545. this.$set(
  546. this.uploadStatusMap,
  547. uploadId,
  548. records.length > 0 ? '已上传' : '未上传'
  549. )
  550. } else {
  551. this.uploadStatusMap[uploadId] = ''
  552. }
  553. // 触发表格更新
  554. this.$nextTick(() => {
  555. this.$forceUpdate()
  556. })
  557. } catch (error) {
  558. console.error('获取上传状态失败:', error)
  559. // 错误情况下更新为未上传状态
  560. row.uploadStatus = '未上传'
  561. // 确保表格更新
  562. this.$nextTick(() => {
  563. this.$forceUpdate()
  564. })
  565. }
  566. },
  567. // 预加载所有动态表上传状态
  568. async preloadAllDynamicTableStatus() {
  569. if (!this.dataRequirements || this.dataRequirements.length === 0) return
  570. const dynamicTableRows = this.dataRequirements.filter(
  571. (row) => !row.isCategoryHeader && row.informationName === '动态表'
  572. )
  573. // 并行请求所有动态表的上传状态,不设置初始加载状态
  574. const promises = dynamicTableRows.map((row) => {
  575. return this.fetchUploadStatus(row)
  576. })
  577. try {
  578. await Promise.all(promises)
  579. } catch (error) {
  580. console.error('预加载上传状态失败:', error)
  581. } finally {
  582. // 确保表格更新
  583. this.$nextTick(() => {
  584. this.$forceUpdate()
  585. })
  586. }
  587. },
  588. // 加载跨表引用数据(固定表/动态表使用,type=2=报送资料)
  589. async loadCrossTableInfo(row) {
  590. const surveyTemplateId = this.getSurveyTemplateId(row)
  591. const taskId = (row && (row.taskId || row.taskID)) || this.taskId || ''
  592. if (!surveyTemplateId || !taskId) {
  593. this.crossTableInfo = {
  594. isCrossTable: false,
  595. crossTableName: '',
  596. data: {},
  597. years: [],
  598. getValue: () => undefined,
  599. }
  600. return true
  601. }
  602. try {
  603. const res = await getCrossTableData({
  604. taskId,
  605. surveyTemplateId,
  606. type: 2,
  607. })
  608. const wrapper = res || {}
  609. const wrappedValue = wrapper.value || wrapper.data || wrapper
  610. const code =
  611. wrapper.code !== undefined && wrapper.code !== null
  612. ? wrapper.code
  613. : wrappedValue && wrappedValue.code
  614. if (!(code === 0 || code === 200)) {
  615. this.crossTableInfo = {
  616. isCrossTable: false,
  617. crossTableName: '',
  618. data: {},
  619. years: [],
  620. getValue: () => undefined,
  621. }
  622. return true
  623. }
  624. const d = wrappedValue || {}
  625. const dataByYearRaw = d && d.data
  626. const isEmptyArray =
  627. Array.isArray(dataByYearRaw) && dataByYearRaw.length === 0
  628. const dataByYear =
  629. !dataByYearRaw || Array.isArray(dataByYearRaw) ? {} : dataByYearRaw
  630. const years = Object.keys(dataByYear)
  631. .map((y) => String(y))
  632. .filter(Boolean)
  633. .sort()
  634. // 若标记为跨表但未返回任何跨表数据:提示 + 阻止打开弹窗
  635. if (d && d.isCrossTable && (isEmptyArray || years.length === 0)) {
  636. this.$message &&
  637. this.$message.warning &&
  638. this.$message.warning(
  639. `跨表引用数据为空,请先完善【${
  640. d.crossTableName || '跨表'
  641. }】后再试`
  642. )
  643. this.crossTableInfo = {
  644. isCrossTable: !!d.isCrossTable,
  645. crossTableName: d.crossTableName || '',
  646. data: {},
  647. years: [],
  648. getValue: () => undefined,
  649. }
  650. return false
  651. }
  652. this.crossTableInfo = {
  653. isCrossTable: !!d.isCrossTable,
  654. crossTableName: d.crossTableName || '',
  655. data: dataByYear,
  656. years,
  657. getValue: (year, key) => {
  658. const y = year === undefined || year === null ? '' : String(year)
  659. const k = key === undefined || key === null ? '' : String(key)
  660. if (!y || !k) return undefined
  661. return dataByYear && dataByYear[y] ? dataByYear[y][k] : undefined
  662. },
  663. }
  664. return true
  665. } catch (e) {
  666. console.error('获取跨表引用数据失败:', e)
  667. this.crossTableInfo = {
  668. isCrossTable: false,
  669. crossTableName: '',
  670. data: {},
  671. years: [],
  672. getValue: () => undefined,
  673. }
  674. return true
  675. }
  676. },
  677. // 在线填报入口:与 CostSurveyTab 一致
  678. async handleOnlineSubmission(row) {
  679. if (!row) return
  680. this.currentTemplateRow = row
  681. this.currentSurveyRow = row
  682. this.surveyDetailData = {}
  683. // 在线填报时使用页面传入的 isViewMode,不强制只读
  684. this.viewModeForDialog = false
  685. const t = String(row.templateType || row.templatetype || '').trim()
  686. // 1=单记录,2=固定表,3=动态表
  687. if (t === '1') {
  688. // 只要有 uploadId/id 就尝试回显数据
  689. if (row.uploadId || row.id) {
  690. try {
  691. const params = {
  692. uploadId: row.uploadId || row.id,
  693. auditedUnitId: this.auditedUnitId,
  694. type: 2,
  695. }
  696. const res = await getSurveyDetail(params)
  697. if (res && res.code === 200 && res.value) {
  698. console.log(res, 'getUploadData')
  699. const detailData = {}
  700. if (Array.isArray(res.value)) {
  701. res.value.forEach((item) => {
  702. if (item.rowid && item.rvalue !== undefined) {
  703. detailData[item.rowid] = item.rvalue
  704. }
  705. })
  706. } else if (res.value && typeof res.value === 'object') {
  707. Object.assign(detailData, res.value)
  708. }
  709. this.surveyDetailData = detailData
  710. }
  711. } catch (err) {
  712. console.error('获取单记录详情失败', err)
  713. }
  714. }
  715. await this.initFormFields()
  716. } else if (t === '2') {
  717. const ok = await this.loadCrossTableInfo(row)
  718. if (!ok) return
  719. await this.initFixedTableData()
  720. } else if (t === '3') {
  721. this.resetDynamicDialogState()
  722. await this.initDynamicTableData()
  723. }
  724. },
  725. // 处理固定表保存(与 CostSurveyTab 对齐)
  726. handleFixedTableSave(tableData) {
  727. this.$emit('handle-fixed-table-save', {
  728. row: this.currentSurveyRow || this.currentTemplateRow,
  729. tableData,
  730. })
  731. },
  732. // 处理刷新(与 CostSurveyTab 对齐)
  733. handleRefresh() {
  734. this.$emit('handle-survey-form-save', {
  735. row: this.currentSurveyRow || this.currentTemplateRow,
  736. formData: {},
  737. })
  738. },
  739. // 处理动态表保存(与 CostSurveyTab 对齐)
  740. handleDynamicTableSave(tableData) {
  741. this.$emit('handle-dynamic-table-save', {
  742. row: this.currentSurveyRow || this.currentTemplateRow,
  743. tableData,
  744. })
  745. this.handleRefresh()
  746. },
  747. // 预览:与 UploadComponent.vue 的 handlePreview 一致
  748. handleFileView(row) {
  749. console.log(row, '这一行数据')
  750. try {
  751. const filePath =
  752. row?.filePath ||
  753. row?.filepath ||
  754. row?.fileUrl ||
  755. row?.url ||
  756. row?.path ||
  757. ''
  758. if (!filePath) {
  759. this.$message &&
  760. this.$message.warning &&
  761. this.$message.warning('未找到可预览的文件路径')
  762. return
  763. }
  764. const encodedUrl = encodeURIComponent(
  765. Base64.encode((window.context && window.context.form) + filePath)
  766. )
  767. window.open(`${host}:8012/onlinePreview?url=${encodedUrl}`)
  768. // 兼容保留:通知父组件
  769. this.$emit('handleFileView', row)
  770. } catch (e) {
  771. console.error('文件预览失败: ', e)
  772. this.$message &&
  773. this.$message.error &&
  774. this.$message.error('文件预览失败')
  775. }
  776. },
  777. // 模版查看:与 submitData.vue 的 handleViewTemplate 保持一致
  778. async handleViewTemplate(row) {
  779. this.currentTemplateRow = row || null
  780. this.currentSurveyRow = row || null
  781. const t = String(
  782. (row && (row.templateType || row.templatetype)) || ''
  783. ).trim()
  784. // 点击“查看”时,复用在线填报的弹窗和数据加载逻辑,但强制只读
  785. this.viewModeForDialog = true
  786. if (t === '1' || t === '2' || t === '3') {
  787. if (!row) return
  788. this.currentTemplateRow = row
  789. this.surveyDetailData = {}
  790. // 在线填报时使用页面传入的 isViewMode,不强制只读
  791. this.viewModeForDialog = true
  792. const t = String(row.templateType || row.templatetype || '').trim()
  793. // 1=单记录,2=固定表,3=动态表
  794. if (t === '1') {
  795. // 只要有 uploadId/id 就尝试回显数据
  796. if (row.uploadId || row.id) {
  797. try {
  798. const params = {
  799. uploadId: row.uploadId || row.id,
  800. auditedUnitId: this.auditedUnitId,
  801. type: 2,
  802. }
  803. const res = await getSurveyDetail(params)
  804. if (res && res.code === 200 && res.value) {
  805. console.log(res, 'getUploadData')
  806. const detailData = {}
  807. if (Array.isArray(res.value)) {
  808. res.value.forEach((item) => {
  809. if (item.rowid && item.rvalue !== undefined) {
  810. detailData[item.rowid] = item.rvalue
  811. }
  812. })
  813. } else if (res.value && typeof res.value === 'object') {
  814. Object.assign(detailData, res.value)
  815. }
  816. this.surveyDetailData = detailData
  817. }
  818. } catch (err) {
  819. console.error('获取单记录详情失败', err)
  820. }
  821. }
  822. await this.initFormFields()
  823. } else if (t === '2') {
  824. const ok = await this.loadCrossTableInfo(row)
  825. if (!ok) return
  826. await this.initFixedTableData()
  827. } else if (t === '3') {
  828. this.resetDynamicDialogState()
  829. await this.initDynamicTableData()
  830. }
  831. } else {
  832. this.$message &&
  833. this.$message.warning &&
  834. this.$message.warning('未知的模板类型,无法打开预置模板')
  835. }
  836. },
  837. // 根据资料类型返回上传accept白名单
  838. getUploadAccept(row) {
  839. const fmt = row && row.formatRequired
  840. const fmtStr = fmt != null ? String(fmt).toLowerCase() : ''
  841. if (
  842. fmtStr === '1' ||
  843. fmtStr.includes('doc') ||
  844. fmtStr.includes('word') ||
  845. fmtStr.includes('pdf') ||
  846. fmtStr.includes('文档')
  847. ) {
  848. return '.pdf,.doc,.docx'
  849. }
  850. if (
  851. fmtStr === '2' ||
  852. fmtStr.includes('excel') ||
  853. fmtStr.includes('xls') ||
  854. fmtStr.includes('xlsx') ||
  855. fmtStr.includes('表格')
  856. ) {
  857. return '.xls,.xlsx'
  858. }
  859. return '.pdf,.doc,.docx,.xls,.xlsx'
  860. },
  861. getDataUploadAccept(row) {
  862. const fmt = row && row.formatRequired
  863. const fmtStr = fmt != null ? String(fmt).toLowerCase() : ''
  864. if (
  865. fmtStr === '3' ||
  866. fmtStr.includes('模版') ||
  867. fmtStr.includes('模板')
  868. ) {
  869. return '.xls,.xlsx'
  870. }
  871. return '.xls,.xlsx'
  872. },
  873. getRowClassName(data) {
  874. if (data.row.isCategoryHeader) {
  875. return 'category-header-row'
  876. }
  877. return ''
  878. },
  879. getDictName(dictType, dictKey) {
  880. const list = (this.dictData && this.dictData[dictType]) || []
  881. if (!Array.isArray(list) || dictKey === undefined || dictKey === null) {
  882. return ''
  883. }
  884. const item = list.find(
  885. (it) =>
  886. String(it.key) === String(dictKey) ||
  887. String(it.value) === String(dictKey)
  888. )
  889. return item ? item.name : ''
  890. },
  891. getSurveyTemplateId(row) {
  892. return (
  893. row?.surveyTemplateId ||
  894. row?.templateId ||
  895. row?.surveyTemplateID ||
  896. row?.templateID ||
  897. ''
  898. )
  899. },
  900. getMaterialId(row) {
  901. return row?.materialId || row?.id || row?.materialID || ''
  902. },
  903. resetDataUploadState() {
  904. const input = this.$refs.dataUploadInput
  905. if (input) {
  906. input.value = ''
  907. }
  908. this.pendingUploadRow = null
  909. },
  910. triggerDataUpload(row) {
  911. console.log(row)
  912. if (!row || this.isViewMode) {
  913. return
  914. }
  915. const surveyTemplateId = this.getSurveyTemplateId(row)
  916. if (!surveyTemplateId) {
  917. this.$message.warning('缺少模板信息,无法上传数据')
  918. return
  919. }
  920. this.pendingUploadRow = row
  921. this.dataUploadAccept = this.getDataUploadAccept(row)
  922. this.$nextTick(() => {
  923. const input = this.$refs.dataUploadInput
  924. if (input) {
  925. input.value = ''
  926. input.click()
  927. }
  928. })
  929. },
  930. async handleDataFileChange(event) {
  931. const files = event?.target?.files
  932. if (!this.pendingUploadRow || !files || !files.length) {
  933. this.resetDataUploadState()
  934. return
  935. }
  936. const file = files[0]
  937. if (!file) {
  938. this.$message.warning('请选择需要上传的文件')
  939. this.resetDataUploadState()
  940. return
  941. }
  942. const surveyTemplateId = this.getSurveyTemplateId(this.pendingUploadRow)
  943. const materialId = this.getMaterialId(this.pendingUploadRow)
  944. if (!surveyTemplateId) {
  945. this.$message.warning('缺少模板信息,无法上传数据')
  946. this.resetDataUploadState()
  947. return
  948. }
  949. if (!materialId) {
  950. this.$message.warning('缺少资料标识,无法上传数据')
  951. this.resetDataUploadState()
  952. return
  953. }
  954. const formData = new FormData()
  955. formData.append('file', file)
  956. formData.append('surveyTemplateId', surveyTemplateId)
  957. formData.append('materialId', materialId)
  958. // const auditedUnitId =this.pendingUploadRow.auditedUnitId
  959. const taskId = this.pendingUploadRow.taskId || this.taskId
  960. // formData.append('auditedUnitId', auditedUnitId)
  961. formData.append('taskId', taskId)
  962. formData.append('type', '2')
  963. const loading = this.$loading({
  964. lock: true,
  965. text: '数据上传中...',
  966. spinner: 'el-icon-loading',
  967. background: 'rgba(0, 0, 0, 0.7)',
  968. })
  969. try {
  970. const response = await importData(formData)
  971. loading.close()
  972. const success =
  973. response &&
  974. (response.code === 200 ||
  975. response.success === true ||
  976. response.status === 200)
  977. if (success) {
  978. this.$message.success('数据上传成功')
  979. this.$emit('data-upload-success', {
  980. row: this.pendingUploadRow,
  981. response,
  982. })
  983. } else {
  984. const message =
  985. response?.message ||
  986. response?.msg ||
  987. response?.data?.message ||
  988. '数据上传失败,请稍后重试'
  989. this.$message.error(message)
  990. }
  991. } catch (error) {
  992. loading.close()
  993. console.error('数据上传失败:', error)
  994. // this.$message.error(error.message || '数据上传失败,请稍后重试')
  995. } finally {
  996. this.resetDataUploadState()
  997. }
  998. },
  999. // 处理模板下载
  1000. async handleTemplateDownload(row) {
  1001. console.log(row)
  1002. let loading
  1003. try {
  1004. // 显示加载提示
  1005. loading = this.$loading({
  1006. lock: true,
  1007. text: '模板下载中...',
  1008. spinner: 'el-icon-loading',
  1009. background: 'rgba(0, 0, 0, 0.7)',
  1010. })
  1011. // 构建请求参数
  1012. const params = { type: 2 }
  1013. const surveyTemplateId = this.getSurveyTemplateId(row)
  1014. if (surveyTemplateId) {
  1015. params.surveyTemplateId = surveyTemplateId
  1016. }
  1017. // 追加 taskId(来自行或页面 props)
  1018. const taskId = row && (row.taskId || row.taskID)
  1019. if (taskId || this.taskId) {
  1020. params.taskId = taskId || this.taskId
  1021. }
  1022. const response = await downloadTemplate(params)
  1023. // 下载接口可能返回两类数据:
  1024. // 1) 正常:Blob(xlsx)
  1025. // 2) 异常:JSON({code:500,state:false,message:'...'}),但由于 responseType=blob,前端拿到的可能仍是 Blob
  1026. const getJsonFromBlobIfPossible = async (blob) => {
  1027. if (!(blob instanceof Blob)) return null
  1028. try {
  1029. const text = await blob.text()
  1030. if (!text) return null
  1031. return JSON.parse(text)
  1032. } catch (e) {
  1033. return null
  1034. }
  1035. }
  1036. let maybeJson = null
  1037. if (
  1038. response &&
  1039. response.data &&
  1040. typeof response.data === 'object' &&
  1041. !(response.data instanceof Blob)
  1042. ) {
  1043. maybeJson = response.data
  1044. } else if (
  1045. response &&
  1046. typeof response === 'object' &&
  1047. !(response instanceof Blob) &&
  1048. !(response.data instanceof Blob)
  1049. ) {
  1050. maybeJson = response
  1051. } else if (response && response.data instanceof Blob) {
  1052. maybeJson = await getJsonFromBlobIfPossible(response.data)
  1053. } else if (response instanceof Blob) {
  1054. maybeJson = await getJsonFromBlobIfPossible(response)
  1055. }
  1056. console.log('下载模板接口返回数据:', maybeJson)
  1057. if (
  1058. maybeJson &&
  1059. (maybeJson.state === false ||
  1060. (maybeJson.code !== undefined &&
  1061. maybeJson.code !== null &&
  1062. ![0, 200].includes(Number(maybeJson.code))))
  1063. ) {
  1064. const msg =
  1065. maybeJson.message ||
  1066. maybeJson.msg ||
  1067. '导出失败:该表存在跨表引用且部分年份数据缺失,请先完善后再下载'
  1068. this.$message && this.$message.warning && this.$message.warning(msg)
  1069. return
  1070. }
  1071. // 处理响应数据
  1072. // response 可能是 { data, headers } 格式,也可能是直接的 Blob
  1073. const blobData = (response && response.data) || response
  1074. const blob =
  1075. blobData instanceof Blob ? blobData : new Blob([blobData])
  1076. // 文件名:优先从响应头获取
  1077. let fileName = ''
  1078. const headers = (response && response.headers) || {}
  1079. const contentDisposition =
  1080. headers['content-disposition'] || headers['Content-Disposition']
  1081. if (contentDisposition) {
  1082. const fileNameMatch = contentDisposition.match(
  1083. /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
  1084. )
  1085. if (fileNameMatch && fileNameMatch[1]) {
  1086. try {
  1087. fileName = decodeURIComponent(
  1088. fileNameMatch[1].replace(/['"]/g, '')
  1089. )
  1090. } catch (e) {
  1091. fileName = fileNameMatch[1].replace(/['"]/g, '')
  1092. }
  1093. }
  1094. }
  1095. if (!fileName) {
  1096. const defaultName = row?.informationName || row?.name || '模板文件'
  1097. fileName = `${defaultName}_模板.xlsx`
  1098. }
  1099. if (!/\.[a-zA-Z0-9]+$/.test(fileName)) {
  1100. fileName += '.xlsx'
  1101. }
  1102. const url = window.URL.createObjectURL(blob)
  1103. const link = document.createElement('a')
  1104. link.style.display = 'none'
  1105. link.href = url
  1106. link.download = fileName
  1107. document.body.appendChild(link)
  1108. link.click()
  1109. document.body.removeChild(link)
  1110. window.URL.revokeObjectURL(url)
  1111. this.$message &&
  1112. this.$message.success &&
  1113. this.$message.success('开始下载文件')
  1114. } catch (error) {
  1115. // 兼容:axios 抛错时,错误信息可能在 error.response.data(同样可能是 Blob)
  1116. try {
  1117. const errRes = error && error.response
  1118. const errData = errRes && errRes.data
  1119. let errJson = null
  1120. if (
  1121. errData &&
  1122. typeof errData === 'object' &&
  1123. !(errData instanceof Blob)
  1124. ) {
  1125. errJson = errData
  1126. } else if (errData instanceof Blob) {
  1127. try {
  1128. const text = await errData.text()
  1129. errJson = text ? JSON.parse(text) : null
  1130. } catch (_) {
  1131. errJson = null
  1132. }
  1133. }
  1134. if (errJson && (errJson.message || errJson.msg)) {
  1135. this.$message &&
  1136. this.$message.warning &&
  1137. this.$message.warning(errJson.message || errJson.msg)
  1138. return
  1139. }
  1140. } catch (_) {
  1141. // ignore
  1142. }
  1143. console.error('模板下载失败:', error)
  1144. this.$message &&
  1145. this.$message.error &&
  1146. this.$message.error(error.message || '模板下载失败,请稍后重试')
  1147. } finally {
  1148. if (loading && loading.close) loading.close()
  1149. }
  1150. },
  1151. // 以下为在线填报所需方法,与 CostSurveyTab 对齐
  1152. async initDynamicTableData() {
  1153. try {
  1154. const uploadId =
  1155. (this.currentTemplateRow &&
  1156. (this.currentTemplateRow.uploadId ||
  1157. this.currentTemplateRow.id)) ||
  1158. ''
  1159. const auditedUnitId =
  1160. this.auditedUnitId ||
  1161. (this.currentTemplateRow &&
  1162. this.currentTemplateRow.auditedUnitId) ||
  1163. ''
  1164. const catalogId =
  1165. (this.currentTemplateRow && this.currentTemplateRow.catalogId) || ''
  1166. const surveyTemplateId = this.getSurveyTemplateId(
  1167. this.currentTemplateRow
  1168. )
  1169. const params = {
  1170. uploadId,
  1171. auditedUnitId,
  1172. catalogId,
  1173. surveyTemplateId,
  1174. type: 2,
  1175. }
  1176. const res = await getDynamicTableData(params)
  1177. if (res && res.code === 200) {
  1178. const records = res.value?.records || res.value || []
  1179. this.dynamicTableData = Array.isArray(records) ? records : []
  1180. } else {
  1181. this.dynamicTableData =
  1182. this.currentTemplateRow?.dynamicTableData || []
  1183. }
  1184. if (
  1185. this.currentTemplateRow &&
  1186. this.currentTemplateRow.tableItems &&
  1187. this.currentTemplateRow.tableItems.length > 0
  1188. ) {
  1189. this.tableItems = this.currentTemplateRow.tableItems
  1190. } else {
  1191. this.tableItems = this.getMockTableItems()
  1192. }
  1193. this.dynamicTableDialogVisible = true
  1194. } catch (error) {
  1195. console.error('获取动态表数据失败', error)
  1196. this.dynamicTableData =
  1197. this.currentTemplateRow?.dynamicTableData || []
  1198. this.tableItems =
  1199. this.currentTemplateRow?.tableItems || this.getMockTableItems()
  1200. this.dynamicTableDialogVisible = true
  1201. }
  1202. },
  1203. async initFormFields() {
  1204. if (
  1205. this.currentTemplateRow &&
  1206. this.getSurveyTemplateId(this.currentTemplateRow)
  1207. ) {
  1208. try {
  1209. const params = {
  1210. surveyTemplateId: this.getSurveyTemplateId(
  1211. this.currentTemplateRow
  1212. ),
  1213. type: 2,
  1214. }
  1215. const res = await getListBySurveyFdTemplateIdAndVersion(params)
  1216. if (res && res.code === 200) {
  1217. let mapped = []
  1218. if (Array.isArray(res.value)) {
  1219. mapped = res.value
  1220. .map((item, index) =>
  1221. this.mapApiFieldToFormField(item, index)
  1222. )
  1223. .filter(Boolean)
  1224. } else if (res.value && typeof res.value === 'object') {
  1225. const { fixedFields, fixedFieldids } = res.value
  1226. if (fixedFields && fixedFieldids) {
  1227. const labels = fixedFields.split(',').map((i) => i.trim())
  1228. const ids = fixedFieldids.split(',').map((i) => i.trim())
  1229. mapped = labels.map((label, index) => ({
  1230. prop: ids[index] || `field_${index}`,
  1231. label,
  1232. type: 'input',
  1233. colSpan: 12,
  1234. placeholder: `请输入${label}`,
  1235. rules: [],
  1236. defaultValue: '',
  1237. disabled: false,
  1238. clearable: true,
  1239. multiple: false,
  1240. required: false,
  1241. }))
  1242. }
  1243. }
  1244. this.formFields =
  1245. mapped.length > 0 ? mapped : this.getMockFormFields()
  1246. } else {
  1247. this.formFields = this.getMockFormFields()
  1248. }
  1249. this.surveyFormDialogVisible = true
  1250. } catch (err) {
  1251. console.error('获取单记录表单字段配置失败', err)
  1252. this.formFields = this.getMockFormFields()
  1253. this.surveyFormDialogVisible = true
  1254. }
  1255. } else {
  1256. this.formFields = this.getMockFormFields()
  1257. this.surveyFormDialogVisible = true
  1258. }
  1259. },
  1260. async initFixedTableData() {
  1261. if (
  1262. this.currentTemplateRow &&
  1263. this.getSurveyTemplateId(this.currentTemplateRow)
  1264. ) {
  1265. try {
  1266. const params = {
  1267. surveyTemplateId: this.getSurveyTemplateId(
  1268. this.currentTemplateRow
  1269. ),
  1270. type: 2,
  1271. }
  1272. const res = await getSingleRecordSurveyList(params)
  1273. if (res && res.code === 200 && res.value) {
  1274. // 将接口返回的数据转换为固定表配置格式
  1275. // 固定表使用 itemlist,不使用 fixedFields 和 fixedFieldids
  1276. const { itemlist } = res.value
  1277. console.log('itemlist', itemlist)
  1278. // 如果有 itemlist,使用 itemlist 作为表格项配置
  1279. if (itemlist && Array.isArray(itemlist) && itemlist.length > 0) {
  1280. this.tableItems = itemlist.map((item, index) => ({
  1281. id: item.id || item.itemId || '',
  1282. rowid: item.rowid || item.id || item.itemId || '', // rowid 用于父子关系
  1283. seq: item.序号, // 序号就是序号
  1284. itemName: item.项目 || '', // 项目就是项目
  1285. unit: item.unit || '', // 单位是 unit
  1286. isCategory: item.isCategory || false,
  1287. categorySeq: item.categorySeq || '',
  1288. categoryId: item.categoryId || '',
  1289. parentid:
  1290. item.parentid !== undefined
  1291. ? item.parentid
  1292. : item.parentId !== undefined
  1293. ? item.parentId
  1294. : '-1', // 父项ID,默认为 '-1'(父项)
  1295. validateRules: item.validateRules || {},
  1296. linkageRules: item.linkageRules || {},
  1297. children: item.children || [],
  1298. ...item, // 保留其他字段
  1299. }))
  1300. // 若该接口同时提供 fixedFields/fixedFieldids,则同步到弹窗表头
  1301. if (res.value.fixedFields && res.value.fixedFieldids) {
  1302. this.fixedFields = res.value.fixedFields
  1303. console.log(this.fixedFields, 'biaogeshuju')
  1304. this.fixedFieldids = res.value.fixedFieldids
  1305. }
  1306. } else {
  1307. // 如果没有 itemlist,使用假数据
  1308. this.tableItems = this.getMockTableItems()
  1309. }
  1310. } else {
  1311. this.tableItems = this.getMockTableItems()
  1312. }
  1313. } catch (err) {
  1314. console.error('获取固定表配置失败', err)
  1315. this.tableItems = this.getMockTableItems()
  1316. }
  1317. } else if (
  1318. this.currentTemplateRow &&
  1319. this.currentTemplateRow.tableItems
  1320. ) {
  1321. this.tableItems = this.currentTemplateRow.tableItems
  1322. } else {
  1323. this.tableItems = this.getMockTableItems()
  1324. }
  1325. // 监审期间:优先使用 props.auditPeriod,其次使用行上的 auditPeriod,否则默认最近三年
  1326. if (this.auditPeriod) {
  1327. if (Array.isArray(this.auditPeriod)) {
  1328. this.auditPeriods = this.auditPeriod.map((p) => String(p))
  1329. } else {
  1330. this.auditPeriods = this.parseAuditPeriod(this.auditPeriod)
  1331. }
  1332. } else if (
  1333. this.currentTemplateRow &&
  1334. this.currentTemplateRow.auditPeriod
  1335. ) {
  1336. this.auditPeriods = this.parseAuditPeriod(
  1337. this.currentTemplateRow.auditPeriod
  1338. )
  1339. } else {
  1340. const currentYear = new Date().getFullYear()
  1341. this.auditPeriods = [
  1342. String(currentYear - 2),
  1343. String(currentYear - 1),
  1344. String(currentYear),
  1345. ]
  1346. }
  1347. try {
  1348. const headerRes = await getListBySurveyTemplateIdAndVersion({
  1349. surveyTemplateId: this.getSurveyTemplateId(this.currentTemplateRow),
  1350. type: 2,
  1351. })
  1352. if (headerRes && headerRes.code === 200) {
  1353. const hdrVal = headerRes.value
  1354. // 统一规范:columnsMeta + fixedFields + fixedFieldids
  1355. let columnsMeta = []
  1356. let fixedFieldsStr = this.fixedFields || ''
  1357. let fixedFieldidsStr = this.fixedFieldids || ''
  1358. if (Array.isArray(hdrVal)) {
  1359. columnsMeta = hdrVal
  1360. } else if (hdrVal && typeof hdrVal === 'object') {
  1361. const {
  1362. fixedFields,
  1363. fixedFieldids,
  1364. columnsMeta: metas,
  1365. headers,
  1366. items,
  1367. } = hdrVal
  1368. fixedFieldsStr = fixedFieldsStr || fixedFields || ''
  1369. fixedFieldidsStr = fixedFieldidsStr || fixedFieldids || ''
  1370. columnsMeta = Array.isArray(metas)
  1371. ? metas
  1372. : Array.isArray(headers)
  1373. ? headers
  1374. : Array.isArray(items)
  1375. ? items
  1376. : []
  1377. }
  1378. // 如未提供 fixedFields/fixedFieldids,则从 columnsMeta 推导
  1379. if (
  1380. (!fixedFieldsStr || !fixedFieldidsStr) &&
  1381. Array.isArray(columnsMeta) &&
  1382. columnsMeta.length
  1383. ) {
  1384. const labels = columnsMeta
  1385. .map((m) => (m && (m.label || m.fieldName || m.name)) || '')
  1386. .map((s) => String(s || '').trim())
  1387. .filter(Boolean)
  1388. const ids = columnsMeta
  1389. .map(
  1390. (m) =>
  1391. (m && (m.fieldId || m.fieldName || m.prop || m.code)) || ''
  1392. )
  1393. .map((s) => String(s || '').trim())
  1394. .filter(Boolean)
  1395. if (labels.length) fixedFieldsStr = labels.join(',')
  1396. if (ids.length) fixedFieldidsStr = ids.join(',')
  1397. }
  1398. // 回写到实例;优先保留服务端原始 fixedHeaders,以与成本调查表保持一致
  1399. this.columnsMeta = columnsMeta
  1400. this.fixedFields = fixedFieldsStr
  1401. this.fixedFieldids = fixedFieldidsStr
  1402. if (hdrVal) {
  1403. this.fixedHeaders = hdrVal
  1404. } else if (
  1405. (Array.isArray(this.columnsMeta) && this.columnsMeta.length) ||
  1406. (this.fixedFields && this.fixedFields.length) ||
  1407. (this.fixedFieldids && this.fixedFieldids.length)
  1408. ) {
  1409. this.fixedHeaders = {
  1410. fixedFields: this.fixedFields,
  1411. fixedFieldids: this.fixedFieldids,
  1412. columnsMeta: this.columnsMeta,
  1413. }
  1414. } else {
  1415. this.fixedHeaders = null
  1416. }
  1417. } else {
  1418. this.fixedHeaders = null
  1419. this.fixedFields = ''
  1420. this.fixedFieldids = ''
  1421. this.columnsMeta = []
  1422. }
  1423. } catch (e) {
  1424. this.fixedHeaders = null
  1425. this.fixedFields = ''
  1426. this.fixedFieldids = ''
  1427. this.columnsMeta = []
  1428. }
  1429. this.fixedDialogKey++
  1430. this.fixedTableDialogVisible = true
  1431. },
  1432. extractLengthFromFormat(format) {
  1433. if (!format) return undefined
  1434. const str = String(format).trim()
  1435. if (!str) return undefined
  1436. const match = str.match(/\d+/)
  1437. if (match && match[0]) {
  1438. const len = Number(match[0])
  1439. return Number.isNaN(len) ? undefined : len
  1440. }
  1441. return undefined
  1442. },
  1443. buildFieldRules(meta) {
  1444. const {
  1445. type,
  1446. label,
  1447. required,
  1448. totalLength,
  1449. decimalLength,
  1450. formatLength,
  1451. format,
  1452. isAuditPeriod,
  1453. } = meta || {}
  1454. const rules = []
  1455. const trigger = type === 'select' ? 'change' : 'blur'
  1456. if (required) {
  1457. rules.push({
  1458. required: true,
  1459. message: `${type === 'select' ? '请选择' : '请输入'}${label}`,
  1460. trigger,
  1461. })
  1462. }
  1463. const inputMaxLength = formatLength || totalLength
  1464. if (type === 'input' && inputMaxLength) {
  1465. rules.push({
  1466. validator: (_, value, callback) => {
  1467. if (value === undefined || value === null || value === '')
  1468. return callback()
  1469. const str = String(value)
  1470. if (str.length > inputMaxLength)
  1471. callback(
  1472. new Error(`${label}长度不能超过${inputMaxLength}个字符`)
  1473. )
  1474. else callback()
  1475. },
  1476. trigger: 'blur',
  1477. })
  1478. }
  1479. const numberTotal = totalLength || formatLength
  1480. if (type === 'number') {
  1481. rules.push({
  1482. validator: (_, value, callback) => {
  1483. if (value === undefined || value === null || value === '')
  1484. return callback()
  1485. if (Number.isNaN(Number(value)))
  1486. return callback(new Error(`${label}必须为数字`))
  1487. const pure = String(value).replace('-', '')
  1488. if (numberTotal && pure.replace('.', '').length > numberTotal)
  1489. return callback(
  1490. new Error(`${label}总位数不能超过${numberTotal}`)
  1491. )
  1492. if (decimalLength !== undefined && decimalLength !== null) {
  1493. const decimals = pure.split('.')[1] || ''
  1494. if (decimals.length > decimalLength)
  1495. return callback(
  1496. new Error(`${label}小数位不能超过${decimalLength}位`)
  1497. )
  1498. }
  1499. callback()
  1500. },
  1501. trigger: 'blur',
  1502. })
  1503. }
  1504. if (type === 'datetime' || type === 'date') {
  1505. if (format) {
  1506. rules.push({
  1507. validator: (_, value, callback) => callback(),
  1508. trigger: 'change',
  1509. })
  1510. }
  1511. }
  1512. if (type === 'year' || isAuditPeriod) {
  1513. rules.push({
  1514. validator: (_, value, callback) => {
  1515. if (value === undefined || value === null || value === '')
  1516. return callback()
  1517. const pattern = /^\d{4}$/
  1518. if (!pattern.test(String(value)))
  1519. callback(new Error(`${label}必须是四位年份`))
  1520. else callback()
  1521. },
  1522. trigger: 'change',
  1523. })
  1524. }
  1525. return rules
  1526. },
  1527. mapApiFieldToFormField(item, index = 0) {
  1528. if (!item) return null
  1529. const getVal = (keys, fallback) => {
  1530. for (const key of keys) {
  1531. if (
  1532. key &&
  1533. item[key] !== undefined &&
  1534. item[key] !== null &&
  1535. item[key] !== ''
  1536. )
  1537. return item[key]
  1538. }
  1539. return fallback
  1540. }
  1541. const toBool = (value) => {
  1542. if (value === undefined || value === null) return false
  1543. if (typeof value === 'boolean') return value
  1544. if (typeof value === 'number') return value === 1
  1545. const str = String(value).trim().toLowerCase()
  1546. return ['1', 'true', 'y', 'yes', '是'].includes(str)
  1547. }
  1548. const toNumber = (value) => {
  1549. if (value === undefined || value === null || value === '')
  1550. return undefined
  1551. const num = Number(value)
  1552. return Number.isNaN(num) ? undefined : num
  1553. }
  1554. const prop =
  1555. getVal(
  1556. [
  1557. 'fieldName',
  1558. 'field_name',
  1559. 'columnName',
  1560. 'column_name',
  1561. 'fieldCode',
  1562. ],
  1563. undefined
  1564. ) || `field_${index}`
  1565. const label =
  1566. getVal(
  1567. [
  1568. 'columnComment',
  1569. 'column_comment',
  1570. 'fieldCname',
  1571. 'field_cname',
  1572. 'fieldLabel',
  1573. 'field_label',
  1574. ],
  1575. prop
  1576. ) || prop
  1577. const columnType =
  1578. (getVal(
  1579. ['columnType', 'column_type', 'fieldType', 'field_type'],
  1580. ''
  1581. ) || '') + ''
  1582. const columnTypeLower = columnType.toLowerCase()
  1583. const totalLength = toNumber(
  1584. getVal(
  1585. ['fieldTypeLen', 'field_typelen', 'length', 'fieldLength'],
  1586. undefined
  1587. )
  1588. )
  1589. const decimalLength = toNumber(
  1590. getVal(
  1591. ['fieldTypeNointLen', 'field_typenointlen', 'scale'],
  1592. undefined
  1593. )
  1594. )
  1595. const isAuditPeriod = toBool(
  1596. getVal(['isAuditPeriod', 'is_audit_period'], false)
  1597. )
  1598. const dictCode =
  1599. getVal(
  1600. [
  1601. 'dictCode',
  1602. 'dict_code',
  1603. 'dictId',
  1604. 'dictid',
  1605. 'dictType',
  1606. 'dict_type',
  1607. ],
  1608. ''
  1609. ) || ''
  1610. const optionsRaw = getVal(['options'], [])
  1611. let options = []
  1612. if (Array.isArray(optionsRaw)) options = optionsRaw
  1613. else if (typeof optionsRaw === 'string' && optionsRaw.trim() !== '') {
  1614. options = optionsRaw
  1615. .split(',')
  1616. .map((value) => ({ label: value.trim(), value: value.trim() }))
  1617. }
  1618. let type = getVal(['componentType', 'type'], '')
  1619. if (!type) {
  1620. if (dictCode || options.length > 0) type = 'select'
  1621. else if (
  1622. columnTypeLower.includes('datetime') ||
  1623. columnTypeLower.includes('timestamp') ||
  1624. columnTypeLower.includes('date time')
  1625. )
  1626. type = 'datetime'
  1627. else if (columnTypeLower.includes('date')) type = 'date'
  1628. else if (columnTypeLower.includes('year')) type = 'year'
  1629. else if (
  1630. columnTypeLower.includes('int') ||
  1631. columnTypeLower.includes('number') ||
  1632. columnTypeLower.includes('decimal') ||
  1633. columnTypeLower.includes('float') ||
  1634. columnTypeLower.includes('double')
  1635. )
  1636. type = 'number'
  1637. else type = 'input'
  1638. }
  1639. const required = toBool(
  1640. getVal(['isRequired', 'is_required', 'required'], false)
  1641. )
  1642. const multiple = toBool(
  1643. getVal(['isMultiple', 'is_multiple', 'multiple'], false)
  1644. )
  1645. const colSpan =
  1646. toNumber(
  1647. getVal(['colSpan', 'colspan', 'columnSpan', 'column_span'], 12)
  1648. ) || 12
  1649. const placeholder =
  1650. getVal(
  1651. ['placeholder', 'columnComment', 'column_comment'],
  1652. undefined
  1653. ) || (type === 'select' ? `请选择${label}` : `请输入${label}`)
  1654. const defaultValue = getVal(
  1655. ['defaultValue', 'default_value', 'defaultVal', 'default_val'],
  1656. undefined
  1657. )
  1658. const precision = toNumber(
  1659. getVal(
  1660. ['fieldTypeNointLen', 'field_typenointlen', 'precision'],
  1661. undefined
  1662. )
  1663. )
  1664. const min = toNumber(getVal(['min'], undefined))
  1665. const max = toNumber(getVal(['max'], undefined))
  1666. const format = getVal(['format'], undefined)
  1667. const valueFormat =
  1668. getVal(['valueFormat', 'value_format'], undefined) ||
  1669. (type === 'datetime'
  1670. ? 'yyyy-MM-dd HH:mm:ss'
  1671. : type === 'date'
  1672. ? 'yyyy-MM-dd'
  1673. : type === 'year'
  1674. ? 'yyyy'
  1675. : undefined)
  1676. const formatLength = this.extractLengthFromFormat(format)
  1677. const rules = this.buildFieldRules({
  1678. type,
  1679. label,
  1680. required,
  1681. totalLength,
  1682. decimalLength,
  1683. formatLength,
  1684. format,
  1685. isAuditPeriod,
  1686. })
  1687. return {
  1688. prop,
  1689. label,
  1690. type,
  1691. colSpan,
  1692. placeholder,
  1693. dictCode,
  1694. dictType: dictCode,
  1695. options,
  1696. required,
  1697. defaultValue,
  1698. multiple,
  1699. precision,
  1700. min,
  1701. max,
  1702. format,
  1703. valueFormat,
  1704. totalLength,
  1705. decimalLength,
  1706. formatLength,
  1707. rules,
  1708. }
  1709. },
  1710. getMockFormFields() {
  1711. // return [
  1712. // {
  1713. // prop: 'institutionName',
  1714. // label: '机构名称',
  1715. // type: 'input',
  1716. // colSpan: 12,
  1717. // defaultValue: '幼儿园基本情况',
  1718. // placeholder: '请输入机构名称',
  1719. // required: true,
  1720. // },
  1721. // {
  1722. // prop: 'institutionNature',
  1723. // label: '机构性质',
  1724. // type: 'select',
  1725. // colSpan: 12,
  1726. // dictType: 'institutionNature',
  1727. // defaultValue: '公办',
  1728. // placeholder: '请选择机构性质',
  1729. // required: true,
  1730. // clearable: true,
  1731. // },
  1732. // {
  1733. // prop: 'institutionLevel',
  1734. // label: '机构评定等级',
  1735. // type: 'select',
  1736. // colSpan: 12,
  1737. // dictType: 'institutionLevel',
  1738. // defaultValue: '省一级',
  1739. // placeholder: '请选择机构评定等级',
  1740. // required: true,
  1741. // clearable: true,
  1742. // },
  1743. // {
  1744. // prop: 'educationMode',
  1745. // label: '机构办学方式',
  1746. // type: 'select',
  1747. // colSpan: 12,
  1748. // dictType: 'educationMode',
  1749. // defaultValue: '全日制',
  1750. // placeholder: '请选择机构办学方式',
  1751. // required: true,
  1752. // clearable: true,
  1753. // },
  1754. // {
  1755. // prop: 'institutionAddress',
  1756. // label: '机构地址',
  1757. // type: 'input',
  1758. // colSpan: 12,
  1759. // placeholder: '请输入机构地址',
  1760. // required: true,
  1761. // },
  1762. // {
  1763. // prop: 'formFiller',
  1764. // label: '机构填表人',
  1765. // type: 'input',
  1766. // colSpan: 12,
  1767. // placeholder: '请输入机构填表人',
  1768. // required: true,
  1769. // },
  1770. // {
  1771. // prop: 'financialManager',
  1772. // label: '机构财务负责人',
  1773. // type: 'input',
  1774. // colSpan: 12,
  1775. // placeholder: '请输入机构财务负责人',
  1776. // required: true,
  1777. // },
  1778. // {
  1779. // prop: 'contactPhone',
  1780. // label: '机构联系电话',
  1781. // type: 'input',
  1782. // colSpan: 12,
  1783. // placeholder: '请输入机构联系电话',
  1784. // required: true,
  1785. // rules: [
  1786. // {
  1787. // required: true,
  1788. // message: '请输入机构联系电话',
  1789. // trigger: 'blur',
  1790. // },
  1791. // {
  1792. // pattern: /^1[3-9]\d{9}$/,
  1793. // message: '请输入正确的手机号码',
  1794. // trigger: 'blur',
  1795. // },
  1796. // ],
  1797. // },
  1798. // ]
  1799. },
  1800. getMockTableItems() {
  1801. // return [
  1802. // {
  1803. // id: '1',
  1804. // itemName: '班级数',
  1805. // unit: '个',
  1806. // isCategory: false,
  1807. // seq: 1,
  1808. // validateRules: { required: true, type: 'number', min: 0 },
  1809. // },
  1810. // {
  1811. // id: '2',
  1812. // itemName: '幼儿学生人数',
  1813. // unit: '人',
  1814. // isCategory: false,
  1815. // seq: 2,
  1816. // validateRules: { required: true, type: 'number', min: 0 },
  1817. // },
  1818. // ]
  1819. },
  1820. resetDynamicDialogState() {
  1821. this.dynamicTableDialogVisible = false
  1822. this.dynamicTableData = []
  1823. this.tableItems = []
  1824. this.dynamicDialogKey = Date.now()
  1825. },
  1826. },
  1827. }
  1828. </script>
  1829. <style scoped>
  1830. .text-danger {
  1831. color: #d9001b;
  1832. }
  1833. /* 类别头行样式 */
  1834. .category-header-row {
  1835. background-color: #f5f7fa !important;
  1836. }
  1837. .category-header-row td {
  1838. background-color: #f5f7fa !important;
  1839. padding: 12px 16px !important;
  1840. }
  1841. .category-header-cell {
  1842. font-weight: 700;
  1843. color: #303133;
  1844. padding-left: 16px;
  1845. }
  1846. </style>