华西海圻ELN前端工程
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

624 lines
20 KiB

  1. <template>
  2. <div>
  3. <div class="custom-table-wrapper">
  4. <div class="custom-table-header">
  5. <div class="custom-table-row">
  6. <div v-for="(col, index) in columns" :key="index" class="custom-table-cell header-cell"
  7. :style="{ width: col.width ? col.width + 'px' : 'auto' }">
  8. <div class="header-cell-content">
  9. <div>{{ $t(col.label) }}</div>
  10. <template
  11. v-if="col.headerSelectKey && col.headerOptions && (showHeaderSelect || templateFillType === 'preFill')">
  12. <HandleFormItem :fieldKey="prefixKey+'_'+col.headerSelectKey" :fieldItemLabel="fieldItemLabel" type="select" class="header-select" :item="getHeaderItem(col)"
  13. v-model="headerSelectFields[col.headerSelectKey]" @change="onHeaderSelectChange(col, $event)"
  14. :error="hasError(-1, index, col.headerSelectKey)"
  15. @update:error="onErrorUpdate(-1, index, col.headerSelectKey, $event)" />
  16. </template>
  17. <span v-else-if="headerSelectFields[col.headerSelectKey]" class="fill-type-icon">({{
  18. headerSelectFields[col.headerSelectKey] }})</span>
  19. </div>
  20. </div>
  21. <!-- 默认操作栏 -->
  22. <div class="custom-table-cell header-cell" :style="{ width: '245px' }" v-if="showOperation">
  23. <div class="header-cell-content">
  24. <div>操作</div>
  25. </div>
  26. </div>
  27. </div>
  28. </div>
  29. <div class="custom-table-body">
  30. <div v-for="(row, rowIndex) in localDataSource" :key="rowIndex" class="custometable-row">
  31. <div v-for="(col, colIndex) in columns" :key="colIndex" class="custom-table-cell body-cell"
  32. :style="{ width: col.width ? col.width + 'px' : 'auto' }">
  33. <div class="inner-table-cell">
  34. <div>
  35. <template v-if="col.bodyType === 'input'">
  36. <HandleFormItem :fieldKey="prefixKey+'_'+col.prop+'_'+rowIndex" :fieldItemLabel="fieldItemLabel" type="input" @blur="onBlur(rowIndex, col.prop, $event)" @copy="onCopy(rowIndex, col)"
  37. class="body-input" :item="getBodyItem(col, rowIndex)" v-model="row[col.prop]"
  38. @change="onBodyValueChange(rowIndex, colIndex, $event)"
  39. :error="hasError(rowIndex, colIndex, col.prop)"
  40. @update:error="onErrorUpdate(rowIndex, colIndex, col.prop, $event)"
  41. :orange-bg="hasOrangeBg(rowIndex, colIndex, col.prop)" />
  42. </template>
  43. <template v-else-if="col.bodyType === 'inputNumber'">
  44. <HandleFormItem :fieldKey="prefixKey+'_'+col.prop+'_'+rowIndex" :fieldItemLabel="fieldItemLabel" type="inputNumber" @copy="onCopy(rowIndex, col)" class="body-input-number"
  45. :item="getBodyItem(col, rowIndex)" v-model="row[col.prop]" @blur="onBlur(rowIndex, col.prop, $event)"
  46. @change="onBodyValueChange(rowIndex, colIndex, $event)"
  47. :error="hasError(rowIndex, colIndex, col.prop)"
  48. @update:error="onErrorUpdate(rowIndex, colIndex, col.prop, $event)"
  49. :orange-bg="hasOrangeBg(rowIndex, colIndex, col.prop)" />
  50. </template>
  51. <template v-else-if="col.bodyType === 'select'">
  52. <HandleFormItem :fieldKey="prefixKey+'_'+col.prop+'_'+rowIndex" :fieldItemLabel="fieldItemLabel" type="select" class="body-select" @blur="onBlur(rowIndex, col.prop, $event)"
  53. :item="getBodyItem(col, rowIndex)" v-model="row[col.prop]"
  54. @change="onBodyValueChange(rowIndex, colIndex, $event)"
  55. :error="hasError(rowIndex, colIndex, col.prop)"
  56. @update:error="onErrorUpdate(rowIndex, colIndex, col.prop, $event)"
  57. :orange-bg="hasOrangeBg(rowIndex, colIndex, col.prop)" />
  58. </template>
  59. <template v-else>
  60. {{ row[col.prop] }}
  61. </template>
  62. </div>
  63. <div class="m-l-5" v-if="col.showBodySub">
  64. <template v-if="col.bodySubType === 'inputNumber'">
  65. <HandleFormItem :fieldKey="prefixKey+'_'+col.bodySubKey+'_'+rowIndex" :fieldItemLabel="fieldItemLabel" type="inputNumber" @blur="onSubBlur(rowIndex, col.bodySubKey, $event)"
  66. @copy="onCopy(rowIndex, col)" :item="getBodySubItem(col)" v-model="row[col.bodySubKey]"
  67. @change="onBodySubValueChange(rowIndex, colIndex, $event)"
  68. :error="hasError(rowIndex, colIndex, col.bodySubKey)"
  69. @update:error="onErrorUpdate(rowIndex, colIndex, col.bodySubKey, $event)"
  70. :orange-bg="hasOrangeBg(rowIndex, colIndex, col.bodySubKey)" />
  71. </template>
  72. <template v-else>
  73. {{ row[col.bodySubKey] }}
  74. </template>
  75. </div>
  76. </div>
  77. </div>
  78. <!-- 默认操作栏 -->
  79. <div class="custom-table-cell body-cell" :style="{ width: '245px' }" v-if="showOperation">
  80. <div class="inner-table-cell">
  81. <slot name="operation" :row="row" :rowIndex="rowIndex"></slot>
  82. </div>
  83. </div>
  84. </div>
  85. </div>
  86. <div v-if="localDataSource.length == 0">
  87. <div class="no-data">暂无数据</div>
  88. </div>
  89. </div>
  90. <div class="add-row" v-if="isShowAddRos()">
  91. <el-button type="primary" plain @click="onAddRow">添加行</el-button>
  92. </div>
  93. </div>
  94. </template>
  95. <script>
  96. import HandleFormItem from "./HandleFormItem.vue"
  97. export default {
  98. inject: ['templateFillType'],
  99. name: 'CustomTable',
  100. components: {
  101. HandleFormItem
  102. },
  103. props: {
  104. // 是否显示表头选择器
  105. showHeaderSelect: {
  106. type: Boolean,
  107. default: false,
  108. },
  109. showAddRow: {
  110. type: Boolean,
  111. default: true,
  112. },
  113. // 是否显示操作栏
  114. showOperation: {
  115. type: Boolean,
  116. default: true,
  117. },
  118. columns: {
  119. type: Array,
  120. required: true,
  121. // 示例格式:
  122. // [
  123. // { label: '姓名', prop: 'name' },
  124. // { label: '状态', prop: 'status', type: 'select', options: [{value:1,label:'启用'},...], selected: null }
  125. // ]
  126. },
  127. formData: {
  128. type: Object,
  129. default: () => {
  130. return {
  131. stepTableFormData: [],
  132. headerSelectFields: {}
  133. }
  134. }
  135. },
  136. fieldItemLabel: {
  137. type: String,
  138. default: '',
  139. },
  140. //循环组件的情况下需要用这个来区分字段
  141. prefixKey:{
  142. type: String,
  143. default: "",
  144. }
  145. },
  146. data() {
  147. return {
  148. localDataSource: [],
  149. headerSelectFields: {},
  150. formErrors: [], // 表单错误状态管理
  151. orangeBgCells: {} // 存储需要橙色背景的单元格 {rowIndex-colIndex: true/false}
  152. }
  153. },
  154. watch: {
  155. formData: {
  156. immediate: true,
  157. handler(newData) {
  158. console.log(newData, "newData")
  159. const { stepTableFormData = [], headerSelectFields = {} } = newData;
  160. this.updateDataSource(stepTableFormData);
  161. this.headerSelectFields = JSON.parse(JSON.stringify(headerSelectFields))
  162. }
  163. },
  164. },
  165. mounted() {
  166. // this.initHeaderSelectValues();
  167. },
  168. methods: {
  169. isShowAddRos() {
  170. if(!this.showAddRow) {
  171. return false;
  172. }
  173. return this.templateFillType === 'preFill';
  174. },
  175. // 复制值
  176. onCopy(rowIndex, col) {
  177. if (col.copyFrom) {
  178. if (!this.localDataSource[rowIndex][col.copyFrom]) {//没有值就不用复制了
  179. return
  180. }
  181. this.$set(this.localDataSource[rowIndex], col.prop, this.localDataSource[rowIndex][col.copyFrom])
  182. this.onBlur(rowIndex, col.prop, this.localDataSource[rowIndex][col.prop]);
  183. }
  184. },
  185. // 初始化表头选择器值
  186. initHeaderSelectValues() {
  187. const headerSelectObj = {};
  188. this.columns.map(col => {
  189. if (col.headerSelectKey) {
  190. headerSelectObj[col.headerSelectKey] = col.defaultValue || col.headerOptions[0].value || ""
  191. }
  192. });
  193. this.headerSelectFields = headerSelectObj;
  194. },
  195. // 直接获取表单数据,不做校验
  196. getFilledFormData() {
  197. return {
  198. stepTableFormData: [...this.localDataSource],
  199. headerSelectFields: this.headerSelectFields,
  200. };
  201. },
  202. // 获取最新数据
  203. getFormData() {
  204. // 合并表头选择器值到 columns
  205. // 数据校验
  206. const validateResult = this.validateFormData();
  207. return new Promise((resolve, reject) => {
  208. if (validateResult.valid) {
  209. resolve({
  210. stepTableFormData: [...this.localDataSource],
  211. headerSelectFields: this.headerSelectFields,
  212. })
  213. } else {
  214. // this.$message.error("表单内容未填完,请填写后再提交");
  215. reject(validateResult.errors[0].error)
  216. }
  217. })
  218. },
  219. // 表单数据校验
  220. validateFormData() {
  221. const errors = [];
  222. // 清空之前的错误状态
  223. this.formErrors = [];
  224. // 校验表头的 HandleFormItem
  225. this.columns.forEach((col, colIndex) => {
  226. if (col.headerSelectKey && col.headerOptions && col.fillType === this.templateFillType) {
  227. const headerValue = this.headerSelectFields[col.headerSelectKey];
  228. if (this.isValueEmpty(headerValue)) {
  229. const errorItem = {
  230. rowIndex: -1, // 表头特殊标记
  231. colIndex,
  232. field: col.headerSelectKey,
  233. label: this.$t(col.label),
  234. error: `请选择${this.$t(col.label)}`
  235. };
  236. errors.push(errorItem);
  237. this.formErrors.push(errorItem);
  238. }
  239. }
  240. });
  241. // 遍历数据行
  242. this.localDataSource.forEach((row, rowIndex) => {
  243. // 遍历列
  244. this.columns.forEach((col, colIndex) => {
  245. // 只校验 fillType 与当前模板状态匹配的字段
  246. if (col.bodyFillType === this.templateFillType || col.bodySubFillType === this.templateFillType) {
  247. // 检查主字段
  248. const mainValue = row[col.prop];
  249. if (this.isValueEmpty(mainValue) && !col.bodyDisabled) {
  250. const errorItem = {
  251. rowIndex,
  252. colIndex,
  253. field: col.prop,
  254. label: this.$t(col.label),
  255. error: `请填写${this.$t(col.label)}`
  256. };
  257. errors.push(errorItem);
  258. this.formErrors.push(errorItem);
  259. }
  260. // 检查子字段(如果有)
  261. if (col.bodySubKey && !col.bodySubDisabled) {
  262. const subValue = row[col.bodySubKey];
  263. console.log(col, subValue, "subValue")
  264. if (this.isValueEmpty(subValue)) {
  265. const errorItem = {
  266. rowIndex,
  267. colIndex,
  268. field: col.bodySubKey,
  269. label: `${this.$t(col.label)}单位`,
  270. error: `请填写${this.$t(col.label)}单位`
  271. };
  272. errors.push(errorItem);
  273. this.formErrors.push(errorItem);
  274. }
  275. }
  276. }
  277. });
  278. });
  279. return {
  280. valid: errors.length === 0,
  281. errors: errors
  282. };
  283. },
  284. // 判断值是否为空
  285. isValueEmpty(value) {
  286. if (value === null || value === undefined || value === '') {
  287. return true;
  288. }
  289. if (typeof value === 'string' && value.trim() === '') {
  290. return true;
  291. }
  292. if (Array.isArray(value) && value.length === 0) {
  293. return true;
  294. }
  295. return false;
  296. },
  297. // 表头选择器变化
  298. onHeaderSelectChange(col, value) {
  299. this.headerSelectFields[col.headerSelectKey] = value;
  300. // 输入时清除对应表单项的错误状态
  301. this.formErrors = this.formErrors.filter(error =>
  302. !(error.rowIndex === -1 &&
  303. error.field === col.headerSelectKey)
  304. );
  305. },
  306. // 表体值变化
  307. onBodyValueChange(rowIndex, colIndex, value) {
  308. const col = this.columns[colIndex];
  309. this.localDataSource[rowIndex][col.prop] = value;
  310. // 输入时清除对应表单项的错误状态
  311. this.formErrors = this.formErrors.filter(error =>
  312. !(error.rowIndex === rowIndex &&
  313. error.colIndex === colIndex &&
  314. error.field === col.prop)
  315. );
  316. this.$emit('body-value-change', rowIndex, colIndex, value);
  317. },
  318. // 表体子值变化
  319. onBodySubValueChange(rowIndex, colIndex, value) {
  320. const col = this.columns[colIndex];
  321. this.localDataSource[rowIndex][col.bodySubKey] = value;
  322. // 输入时清除对应表单项的错误状态
  323. this.formErrors = this.formErrors.filter(error =>
  324. !(error.rowIndex === rowIndex &&
  325. error.colIndex === colIndex &&
  326. error.field === col.bodySubKey)
  327. );
  328. this.$emit('body-sub-value-change', rowIndex, colIndex, value);
  329. },
  330. getHeaderItem(col) {
  331. return {
  332. fillType: col.fillType,
  333. options: col.headerOptions,
  334. label: ""
  335. }
  336. },
  337. getBodyItem(col, rowIndex) {
  338. const currentItem = this.localDataSource[rowIndex];
  339. const item = {
  340. fillType: col.bodyFillType,
  341. options: col.bodyOptions,
  342. maxlength: col.bodyMaxlength,
  343. label: this.$t(col.label),
  344. precision: currentItem[col.bodyPrecisionKey] || col.precision || 0,
  345. copyFrom: col.copyFrom || "",
  346. compareTo: col.bodyCompareTo, // 添加 compareTo 字段
  347. };
  348. if (col.bodyDisabled) {
  349. item.disabled = col.bodyDisabled;
  350. }
  351. return item
  352. },
  353. getBodySubItem(col) {
  354. const item = {
  355. fillType: col.bodySubFillType,
  356. options: col.bodySubOptions,
  357. maxlength: col.bodySubMaxlength || 10,
  358. label: "",
  359. placeholder: col.bodySubPlaceholder || "请输入",
  360. precision: col.subPrecision || 0,
  361. compareTo: col.bodySubCompareTo, // 添加 compareTo 字段
  362. }
  363. if (col.bodySubDisabled) {
  364. item.disabled = col.bodySubDisabled;
  365. }
  366. return item
  367. },
  368. // 删除行
  369. deleteRow(rowIndex) {
  370. this.localDataSource.splice(rowIndex, 1);
  371. this.$emit('row-delete', rowIndex);
  372. },
  373. // 更新数据方法,可在formData变更时调用,也可由父组件调用
  374. updateDataSource(dataSource = []) {
  375. // 深拷贝数据以避免直接修改原始数据
  376. this.localDataSource = JSON.parse(JSON.stringify(dataSource || []));
  377. },
  378. onAddRow() {
  379. this.addRow({
  380. actSolutionVolumePrecision: 3,//小数点精度默认为3
  381. actSolutionConcentrationPrecision: 3,//小数点精度默认为3
  382. targetDiluentVolumePrecision: 3,//小数点精度默认为3
  383. targetStartSolutionVolumePrecision: 3,//小数点精度默认为3
  384. });
  385. },
  386. // 添加行
  387. addRow(row = {}) {
  388. this.localDataSource.push(row);
  389. },
  390. getDataSource() {
  391. return this.localDataSource;
  392. },
  393. // 根据行索引更新数据
  394. updateDataSourceByRowIndex(rowIndex, data) {
  395. this.localDataSource[rowIndex] = { ...this.localDataSource[rowIndex], ...data };
  396. console.log(this.localDataSource, "this.localDataSource")
  397. this.localDataSource = [...this.localDataSource];
  398. },
  399. // 判断表单项是否有错误
  400. hasError(rowIndex, colIndex, field) {
  401. return this.formErrors.some(error =>
  402. error.rowIndex === rowIndex &&
  403. error.colIndex === colIndex &&
  404. error.field === field
  405. );
  406. },
  407. // 处理错误状态更新
  408. onErrorUpdate(rowIndex, colIndex, field, isError) {
  409. if (!isError) {
  410. this.formErrors = this.formErrors.filter(error =>
  411. !(error.rowIndex === rowIndex &&
  412. error.colIndex === colIndex &&
  413. error.field === field)
  414. );
  415. }
  416. },
  417. onSubBlur(rowIndex, colKey, value) {
  418. this.$emit("blur", { rowIndex, colKey, value, item: this.localDataSource[rowIndex] });
  419. },
  420. // 检查是否需要橙色背景
  421. hasOrangeBg(rowIndex, colIndex, field) {
  422. const key = `${rowIndex}-${colIndex}-${field}`;
  423. return this.orangeBgCells[key] || false;
  424. },
  425. // 设置橙色背景状态
  426. setOrangeBg(rowIndex, colIndex, field, status) {
  427. const key = `${rowIndex}-${colIndex}-${field}`;
  428. this.$set(this.orangeBgCells, key, status);
  429. },
  430. onBlur(rowIndex, colKey) {
  431. const value = this.localDataSource[rowIndex][colKey];
  432. // 查找对应的列配置
  433. const col = this.columns.find(c => c.prop === colKey);
  434. if (col && col.bodyFillType === "actFill" && col.bodyCompareTo) {
  435. const compareToValue = this.localDataSource[rowIndex][col.bodyCompareTo];
  436. // 比较当前值和compareTo值,如果不相等则设置橙色背景
  437. if (value !== compareToValue) {
  438. this.setOrangeBg(rowIndex, this.columns.findIndex(c => c.prop === colKey), colKey, true);
  439. } else {
  440. // 相等则移除橙色背景
  441. this.setOrangeBg(rowIndex, this.columns.findIndex(c => c.prop === colKey), colKey, false);
  442. }
  443. }
  444. this.$emit("blur", { rowIndex, colKey, value, item: this.localDataSource[rowIndex] });
  445. },
  446. onSubBlur(rowIndex, colKey, value) {
  447. // 查找对应的列配置
  448. const col = this.columns.find(c => c.bodySubKey === colKey);
  449. if (col && col.bodySubFillType === "actFill" && col.bodySubCompareTo) {
  450. const compareToValue = this.localDataSource[rowIndex][col.bodySubCompareTo];
  451. // 比较当前值和compareTo值,如果不相等则设置橙色背景
  452. if (value !== compareToValue) {
  453. this.setOrangeBg(rowIndex, this.columns.findIndex(c => c.bodySubKey === colKey), colKey, true);
  454. } else {
  455. // 相等则移除橙色背景
  456. this.setOrangeBg(rowIndex, this.columns.findIndex(c => c.bodySubKey === colKey), colKey, false);
  457. }
  458. }
  459. this.$emit("blur", { rowIndex, colKey, value, item: this.localDataSource[rowIndex] });
  460. }
  461. }
  462. };
  463. </script>
  464. <style scoped>
  465. .custom-table-wrapper {
  466. border: 1px solid #ebeef5;
  467. border-radius: 4px;
  468. overflow: hidden;
  469. font-size: 14px;
  470. color: #606266;
  471. margin-top: 20px;
  472. }
  473. .inner-table-cell {
  474. display: flex;
  475. align-items: center;
  476. justify-content: center;
  477. }
  478. .m-l-5 {
  479. margin-left: 5px;
  480. }
  481. .sub-input-number {
  482. width: 145px;
  483. .el-input-number--mini {
  484. width: 145px;
  485. }
  486. }
  487. /* 表头 */
  488. .custom-table-header {
  489. background-color: #f5f7fa;
  490. border-bottom: 1px solid #ebeef5;
  491. white-space: nowrap;
  492. display: block;
  493. }
  494. .custom-table-body {
  495. max-height: 300px;
  496. /* 可根据需要调整或由父组件控制 */
  497. }
  498. .header-cell-content {
  499. display: flex;
  500. align-items: center;
  501. justify-content: center;
  502. }
  503. /* 共同行样式 */
  504. .custom-table-row {
  505. display: table;
  506. width: 100%;
  507. table-layout: fixed;
  508. }
  509. .custometable-row {
  510. display: table;
  511. width: 100%;
  512. table-layout: fixed;
  513. &:not(:last-child) {
  514. border-bottom: 1px solid #ebeef5;
  515. }
  516. }
  517. /* 单元格 */
  518. .custom-table-cell {
  519. display: table-cell;
  520. padding: 12px 10px;
  521. text-align: left;
  522. vertical-align: middle;
  523. border-right: 1px solid #ebeef5;
  524. box-sizing: border-box;
  525. }
  526. .custom-table-cell:last-child {
  527. border-right: none;
  528. }
  529. .header-cell {
  530. font-weight: bold;
  531. color: #909399;
  532. background-color: #f5f7fa;
  533. }
  534. .body-cell {
  535. color: #606266;
  536. background-color: #fff;
  537. }
  538. /* select 样式(模仿 Element UI) */
  539. .header-cell select {
  540. width: 100%;
  541. padding: 4px 8px;
  542. border: 1px solid #dcdfe6;
  543. border-radius: 4px;
  544. outline: none;
  545. background-color: #fff;
  546. font-size: 13px;
  547. color: #606266;
  548. appearance: none;
  549. /* 隐藏默认箭头(可选) */
  550. background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
  551. background-repeat: no-repeat;
  552. background-position: right 8px center;
  553. background-size: 14px;
  554. padding-right: 28px;
  555. }
  556. /* 滚动容器:如果整体宽度超限,显示横向滚动条 */
  557. .custom-table-wrapper {
  558. display: flex;
  559. flex-direction: column;
  560. max-width: 100%;
  561. /* 父容器决定宽度 */
  562. overflow-x: auto;
  563. }
  564. .custom-table-header,
  565. .custom-table-body {
  566. min-width: 100%;
  567. }
  568. .header-select {
  569. width: 100px;
  570. margin-left: 5px;
  571. }
  572. .no-data {
  573. text-align: center;
  574. padding: 20px 0;
  575. color: rgb(144, 147, 153)
  576. }
  577. .add-row {
  578. display: flex;
  579. justify-content: center;
  580. padding: 20px 0;
  581. margin-top: 20px;
  582. }
  583. </style>