WXL
2026-03-13 45680b99ccdfb0d323088c57c237e0bc714a8e0b
src/views/business/maintain/components/LiverKidneyPanel.vue
@@ -30,7 +30,7 @@
        class-name="leave-alone"
      >
        <template #default="scope">
          <span :class="{'required-item': scope.row.required}">
          <span :class="{ 'required-item': scope.row.required }">
            {{ scope.row.itemName }}
          </span>
        </template>
@@ -54,8 +54,11 @@
              class="value-input"
            />
            <span v-else class="value-display">
              {{ scope.row.values[index] || '-' }}
              <span v-if="scope.row.values[index] && scope.row.unit" class="unit">
              {{ scope.row.values[index] || "-" }}
              <span
                v-if="scope.row.values[index] && scope.row.unit"
                class="unit"
              >
                {{ scope.row.unit }}
              </span>
            </span>
@@ -65,23 +68,91 @@
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 附件上传区域 -->
    <!-- 附件上传区域优化 -->
    <div class="attachment-section">
      <div class="attachment-title">
      <div class="attachment-header">
        <i class="el-icon-paperclip"></i>
        附件上传
        <span class="attachment-tip">支持上传检验报告单等文件</span>
        <span class="attachment-title">附件上传</span>
        <span class="attachment-tip"
          >支持上传检验报告单等文件 (最多{{ attachmentLimit }}个)</span
        >
      </div>
      <upload-attachment
        :file-list="attachments"
      <!-- 使用 UploadAttachment 组件 -->
      <UploadAttachment
        ref="uploadAttachment"
        :file-list="attachmentFileList"
        :limit="attachmentLimit"
        :accept="attachmentAccept"
        :multiple="true"
        @change="handleAttachmentChange"
        :limit="10"
        :accept="'.pdf,.jpg,.jpeg,.png,.doc,.docx'"
        @upload-success="handleUploadSuccess"
        @upload-error="handleUploadError"
        @remove="handleAttachmentRemove"
      />
      <!-- 附件列表展示 -->
      <div class="attachment-list" v-if="attachments && attachments.length > 0">
        <div class="list-title">已上传附件 ({{ attachments.length }})</div>
        <el-table :data="attachments" style="width: 100%" size="small">
          <el-table-column label="文件名" min-width="200">
            <template slot-scope="scope">
              <i
                class="el-icon-document"
                :style="{ color: getFileIconColor(scope.row.fileName) }"
              ></i>
              <span class="file-name">{{ scope.row.fileName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="文件类型" width="100">
            <template slot-scope="scope">
              <el-tag :type="getFileTagType(scope.row.fileName)" size="small">
                {{ getFileTypeText(scope.row.fileName) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="上传时间" width="160">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.uploadTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" width="100">
            <template slot-scope="scope">
              <span>{{ formatFileSize(scope.row.fileSize) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="266" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handlePreview(scope.row)"
                :disabled="!isPreviewable(scope.row.fileName)"
              >
                预览
              </el-button>
              <el-button
                v-if="isEditing"
                size="mini"
                type="success"
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
              <el-button
                v-if="isEditing"
                size="mini"
                type="danger"
                @click="handleRemoveAttachment(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 列编辑对话框 -->
@@ -95,7 +166,9 @@
        <el-form-item
          label="日期"
          prop="date"
          :rules="[{ required: true, message: '请选择日期', trigger: 'change' }]"
          :rules="[
            { required: true, message: '请选择日期', trigger: 'change' }
          ]"
        >
          <el-date-picker
            v-model="columnForm.date"
@@ -108,7 +181,9 @@
        <el-form-item
          label="时间"
          prop="time"
          :rules="[{ required: true, message: '请选择时间', trigger: 'change' }]"
          :rules="[
            { required: true, message: '请选择时间', trigger: 'change' }
          ]"
        >
          <el-time-picker
            v-model="columnForm.time"
@@ -123,16 +198,27 @@
        <el-button type="primary" @click="confirmAddColumn">确定</el-button>
      </span>
    </el-dialog>
    <!-- 文件预览弹窗 -->
    <FilePreviewDialog
      :visible="previewVisible"
      :file="currentPreviewFile"
      @close="previewVisible = false"
      @download="handleDownload"
    />
  </div>
</template>
<script>
import UploadAttachment from "@/components/UploadAttachment";
import FilePreviewDialog from "@/components/FilePreviewDialog";
import dayjs from "dayjs";
export default {
  name: 'LiverKidneyPanel',
  name: "LiverKidneyPanel",
  components: {
    UploadAttachment,
    FilePreviewDialog
  },
  props: {
    isEditing: {
@@ -140,151 +226,167 @@
      default: false
    },
    initialData: {
      type: Array,
      default: () => []
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      tableData: [],
      dynamicColumns: [
        {
          label: '2024-12-27\n08:00',
          key: 'time1',
          date: '2024-12-27',
          time: '08:00'
        },
        {
          label: '2024-12-27\n14:00',
          key: 'time2',
          date: '2024-12-27',
          time: '14:00'
        }
      ],
      dynamicColumns: [],
      attachments: [],
      columnDialogVisible: false,
      columnForm: {
        date: '',
        time: ''
        date: "",
        time: ""
      },
      tableKey: 0 // 用于强制重新渲染表格
      tableKey: 0,
      internalData: {},
      // 预览相关
      previewVisible: false,
      currentPreviewFile: null,
      // 附件相关配置
      attachmentLimit: 10,
      attachmentAccept:
        ".pdf,.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt",
      attachmentFileList: []
    };
  },
  watch: {
    initialData: {
      handler(newData) {
        if (newData && Object.keys(newData).length > 0) {
          this.internalData = { ...newData };
          this.initFromExternalData();
        }
      },
      immediate: true,
      deep: true
    },
    isEditing(newVal) {
      if (!newVal) {
        // 保存数据
        this.$emit('data-change', {
          type: 'liver_kidney',
          data: this.tableData,
          columns: this.dynamicColumns,
          attachments: this.attachments
        });
        this.saveData();
      }
      // 编辑模式切换时重新计算列宽
      this.$nextTick(() => {
        this.forceTableLayout();
      });
    },
    dynamicColumns: {
      handler() {
        // 列变化时重新计算布局
        this.$nextTick(() => {
          this.forceTableLayout();
        });
      },
      deep: true
    },
    // 监听附件数据变化
    attachments: {
      handler(newAttachments) {
        this.attachmentFileList = newAttachments.map(item => ({
          uid: item.id || Math.random(),
          name: item.fileName,
          fileSize: item.fileSize,
          url: item.path || item.fileUrl,
          uploadTime: item.uploadTime,
          status: "success"
        }));
      },
      deep: true
    }
  },
  methods: {
    // 从外部数据初始化组件
    initFromExternalData() {
      if (this.internalData.data && this.internalData.columns) {
        this.tableData = this.internalData.data.map(item => ({
          ...item,
          values:
            item.values || new Array(this.internalData.columns.length).fill("")
        }));
        this.dynamicColumns = [...this.internalData.columns];
      } else {
        this.initTableData();
      }
      // 初始化附件
      if (this.internalData.attachments) {
        this.attachments = [...this.internalData.attachments];
      }
    },
    // 初始化默认表格数据
    initTableData() {
      const medicalItems = [
        {
          itemName: '血钠',
          unit: 'mmol/L',
          itemName: "血钠",
          unit: "mmol/L",
          required: true,
          reference: '135-145'
          reference: "135-145"
        },
        {
          itemName: '血钾',
          unit: 'mmol/L',
          itemName: "血钾",
          unit: "mmol/L",
          required: true,
          reference: '3.5-5.5'
          reference: "3.5-5.5"
        },
        { itemName: "BUN", unit: "mg/dL", required: true, reference: "<20" },
        { itemName: "肌酐", unit: "μmol/L", required: true, reference: "<100" },
        {
          itemName: 'BUN',
          unit: 'mg/dL',
          itemName: "总胆红素",
          unit: "μmol/L",
          required: true,
          reference: '<20'
          reference: "<21"
        },
        {
          itemName: '肌酐',
          unit: 'μmol/L',
          required: true,
          reference: '<100'
        },
        {
          itemName: '总胆红素',
          unit: 'μmol/L',
          required: true,
          reference: '<21'
        },
        {
          itemName: 'ALT',
          unit: 'U/L',
          required: true,
          reference: '<50'
        },
        {
          itemName: 'AST',
          unit: 'U/L',
          required: true,
          reference: '<40'
        },
        {
          itemName: 'GGT',
          unit: 'U/L',
          required: true,
          reference: '<57'
        },
        {
          itemName: 'ALP',
          unit: 'U/L',
          required: true,
          reference: '<120'
        },
        {
          itemName: 'PT',
          unit: '秒',
          required: true,
          reference: '9.4-12.5'
        },
        {
          itemName: 'INR',
          unit: '',
          required: true,
          reference: '0.85-1.15'
        }
        { itemName: "ALT", unit: "U/L", required: true, reference: "<50" },
        { itemName: "AST", unit: "U/L", required: true, reference: "<40" },
        { itemName: "GGT", unit: "U/L", required: true, reference: "<57" },
        { itemName: "ALP", unit: "U/L", required: true, reference: "<120" },
        { itemName: "PT", unit: "秒", required: true, reference: "9.4-12.5" },
        { itemName: "INR", unit: "", required: true, reference: "0.85-1.15" }
      ];
      if (this.dynamicColumns.length === 0) {
        this.dynamicColumns = [
          {
            label: `${new Date().toISOString().split("T")[0]}\n08:00`,
            key: "time1",
            date: new Date().toISOString().split("T")[0],
            time: "08:00"
          }
        ];
      }
      this.tableData = medicalItems.map(item => ({
        ...item,
        values: new Array(this.dynamicColumns.length).fill('')
        values: new Array(this.dynamicColumns.length).fill("")
      }));
    },
    // 保存数据到父组件
    saveData() {
      const dataToEmit = {
        type: "liver_kidney",
        data: this.tableData,
        columns: this.dynamicColumns,
        attachments: this.attachments
      };
      this.$emit("data-change", dataToEmit);
    },
    addColumn() {
      this.columnForm = {
        date: new Date().toISOString().split('T')[0],
        time: '08:00'
        date: new Date().toISOString().split("T")[0],
        time: "08:00"
      };
      this.columnDialogVisible = true;
    },
    confirmAddColumn() {
      this.$refs.columnForm.validate((valid) => {
      this.$refs.columnForm.validate(valid => {
        if (!valid) {
          this.$message.warning('请完善时间点信息');
          this.$message.warning("请完善时间点信息");
          return;
        }
@@ -300,59 +402,222 @@
        // 为所有行新增一个空值
        this.tableData.forEach(row => {
          row.values.push('');
          if (!row.values) {
            row.values = [];
          }
          row.values.push("");
        });
        this.columnDialogVisible = false;
        this.$message.success('时间点添加成功');
        // 强制表格重新渲染
        this.$message.success("时间点添加成功");
        this.tableKey += 1;
        this.saveData();
      });
    },
    handleDialogClosed() {
      this.columnForm = {
        date: '',
        time: ''
      };
      this.columnForm = { date: "", time: "" };
      this.$refs.columnForm && this.$refs.columnForm.clearValidate();
    },
    handleValueChange(row, columnIndex) {
      this.$emit('data-change', {
        type: 'liver_kidney',
        data: this.tableData,
        columns: this.dynamicColumns
      });
      this.saveData();
    },
    /** 附件变化处理 */
    handleAttachmentChange(fileList) {
      this.attachments = fileList;
      this.$emit('attachment-change', {
        type: 'liver_kidney',
        attachments: fileList
      });
      this.attachmentFileList = fileList;
    },
    // 强制表格重新布局[1,3](@ref)
    /** 附件移除处理 */
    handleAttachmentRemove(file) {
      if (file.url) {
        const index = this.attachments.findIndex(
          item => item.path === file.url || item.fileUrl === file.url
        );
        if (index > -1) {
          this.attachments.splice(index, 1);
          this.saveData();
          this.$message.success("附件删除成功");
        }
      }
    },
    /** 上传成功处理 */
    handleUploadSuccess({ file, fileList, response }) {
      if (response.code === 200) {
        const attachmentObj = {
          fileName: file.name,
          path: response.fileUrl || file.url,
          fileUrl: response.fileUrl || file.url,
          fileType: this.getFileExtension(file.name),
          fileSize: file.size,
          uploadTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
        };
        // 确保 attachments 是数组
        if (!Array.isArray(this.attachments)) {
          this.attachments = [];
        }
        this.attachments.push(attachmentObj);
        this.attachmentFileList = fileList;
        this.saveData();
        this.$message.success("文件上传成功");
      }
    },
    /** 上传错误处理 */
    handleUploadError({ file, fileList, error }) {
      console.error("附件上传失败:", error);
      this.$message.error("文件上传失败,请重试");
    },
    /** 手动删除附件 */
    handleRemoveAttachment(index) {
      this.attachments.splice(index, 1);
      this.attachmentFileList.splice(index, 1);
      this.saveData();
      this.$message.success("附件删除成功");
    },
    /** 文件预览 */
    handlePreview(file) {
      this.currentPreviewFile = {
        fileName: file.fileName,
        fileUrl: file.path || file.fileUrl,
        fileType: this.getFileType(file.fileName)
      };
      this.previewVisible = true;
    },
    /** 文件下载 */
    handleDownload(file) {
      const fileUrl = file.path || file.fileUrl;
      const fileName = file.fileName;
      if (fileUrl) {
        const link = document.createElement("a");
        link.href = fileUrl;
        link.download = fileName;
        link.style.display = "none";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success("开始下载文件");
      } else {
        this.$message.warning("文件路径不存在,无法下载");
      }
    },
    /** 获取文件类型 */
    getFileType(fileName) {
      if (!fileName) return "other";
      const extension = fileName
        .split(".")
        .pop()
        .toLowerCase();
      const imageTypes = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
      const pdfTypes = ["pdf"];
      const officeTypes = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"];
      if (imageTypes.includes(extension)) return "image";
      if (pdfTypes.includes(extension)) return "pdf";
      if (officeTypes.includes(extension)) return "office";
      return "other";
    },
    /** 获取文件图标颜色 */
    getFileIconColor(fileName) {
      const type = this.getFileType(fileName);
      const colorMap = {
        image: "#67C23A",
        pdf: "#F56C6C",
        office: "#409EFF",
        other: "#909399"
      };
      return colorMap[type] || "#909399";
    },
    /** 获取文件标签类型 */
    getFileTagType(fileName) {
      const type = this.getFileType(fileName);
      const typeMap = {
        image: "success",
        pdf: "danger",
        office: "primary",
        other: "info"
      };
      return typeMap[type] || "info";
    },
    /** 获取文件类型文本 */
    getFileTypeText(fileName) {
      const type = this.getFileType(fileName);
      const textMap = {
        image: "图片",
        pdf: "PDF",
        office: "文档",
        other: "其他"
      };
      return textMap[type] || "未知";
    },
    /** 检查是否可预览 */
    isPreviewable(fileName) {
      const type = this.getFileType(fileName);
      return ["image", "pdf"].includes(type);
    },
    /** 获取文件扩展名 */
    getFileExtension(filename) {
      return filename
        .split(".")
        .pop()
        .toLowerCase();
    },
    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    },
    /** 日期时间格式化 */
    formatDateTime(dateTime) {
      if (!dateTime) return "";
      try {
        const date = new Date(dateTime);
        if (isNaN(date.getTime())) return dateTime;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return dateTime;
      }
    },
    forceTableLayout() {
      this.$nextTick(() => {
        const table = this.$el.querySelector('.el-table');
        if (table && table.querySelector('colgroup')) {
          // 触发表格重新计算布局
        const table = this.$el.querySelector(".el-table");
        if (table && table.querySelector("colgroup")) {
          this.$nextTick(() => {
            window.dispatchEvent(new Event('resize'));
            window.dispatchEvent(new Event("resize"));
          });
        }
      });
    },
    handleHeaderDragEnd() {
      // 列宽拖拽结束后重新计算布局
      this.forceTableLayout();
    },
    // 提供数据导出方法供父组件调用
    exportData() {
      return {
        tableData: this.tableData,
@@ -363,9 +628,10 @@
    }
  },
  mounted() {
    this.initTableData();
    // 初始渲染后计算列宽
    this.$nextTick(() => {
      if (Object.keys(this.internalData).length === 0) {
        this.initTableData();
      }
      this.forceTableLayout();
    });
  }
@@ -441,6 +707,7 @@
  margin-right: 4px;
}
/* 附件上传区域样式优化 */
.attachment-section {
  margin-top: 30px;
  padding: 20px;
@@ -449,22 +716,43 @@
  background: #fafafa;
}
.attachment-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #409eff;
.attachment-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}
.attachment-title {
  font-weight: bold;
  margin: 0 8px;
  color: #303133;
}
.attachment-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
  font-weight: normal;
  margin-left: auto;
}
/* 响应式设计 */
.attachment-list {
  margin-top: 16px;
}
.list-title {
  font-weight: bold;
  margin-bottom: 12px;
  color: #303133;
  font-size: 14px;
}
.file-name {
  font-size: 13px;
  margin-left: 8px;
}
/* 响应式调整 */
@media (max-width: 768px) {
  .medical-panel {
    padding: 10px;
@@ -488,5 +776,9 @@
    margin-left: 0;
    margin-top: 4px;
  }
  .attachment-section {
    padding: 10px;
  }
}
</style>