董国庆
2025-06-25 d8d68a0aee93073b5ec3195368ca0ed1076f66a2
laboratory/src/components/DynamicComponent/addTableData.vue
@@ -1,6 +1,6 @@
<template>
  <el-dialog
    title="添加表数据"
    :title="isEdit? '编辑表数据' : '添加表数据'"
    :visible.sync="dialogVisible"
    width="60%"
    :close-on-click-modal="false"
@@ -38,6 +38,7 @@
                  <el-input
                    v-model="form[header.name]"
                    :placeholder="'请输入' + header.name"
                    :disabled="!checkEditPermission(header)"
                  />
                </el-form-item>
                <el-form-item
@@ -52,12 +53,16 @@
                >
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :file-list="spectrumList"
                    :auto-upload="false"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :file-list="imageList"
                    :auto-upload="true"
                    list-type="picture-card"
                    :on-change="handleSpectrumChange"
                    :on-remove="handleSpectrumRemove"
                    :on-change="handleImageChange"
                    :on-remove="handleImageRemove"
                    :on-success="handleImageSuccess"
                    :on-preview="handlePreview"
                    :disabled="!checkEditPermission(header)"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
@@ -77,6 +82,7 @@
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :disabled="!checkEditPermission(header)"
                    :picker-options="{
                      shortcuts: [{
                        text: '今天',
@@ -116,6 +122,7 @@
                    multiple
                    filterable
                    placeholder="请选择用户"
                    :disabled="!checkEditPermission(header)"
                  >
                    <el-option
                      v-for="item in userOptions"
@@ -135,10 +142,17 @@
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
    <el-dialog :visible.sync="imagePreviewVisible" append-to-body>
      <img width="100%" :src="imagePreviewUrl" alt="" />
    </el-dialog>
  </el-dialog>
</template>
  
<script>
import { listByRole } from './service';
import { getFullUrl } from '@/utils/utils';
import apiConfig from '@/utils/baseurl';
export default {
  name: "AddDialog",
  props: {
@@ -166,14 +180,15 @@
      form: {},
      rules: {},
      photoList: [],
      spectrumList: [],
      userOptions: [
        { value: '1', label: '用户1' },
        { value: '2', label: '用户2' },
        { value: '3', label: '用户3' },
        { value: '4', label: '用户4' },
        { value: '5', label: '用户5' }
      ]
      imageList: [],
      defaultImageUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', // 默认图片地址
      userOptions: [],
      imagePreviewVisible: false,
      imagePreviewUrl: '',
      uploadUrl: apiConfig.imgUrl,
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token') || ''
      }
    };
  },
  computed: {
@@ -185,12 +200,15 @@
        this.$emit("update:visible", val);
      },
    },
    currentUserId() {
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
      return userInfo.userId;
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          console.log('弹窗打开,初始化数据');
          this.showHeaderList = JSON.parse(JSON.stringify(this.headerList));
          this.$forceUpdate();
          if (this.isEdit && this.editData) {
@@ -201,8 +219,6 @@
            this.initFormData();
          }
          this.initRules();
          console.log('初始化后的表单数据:', this.form);
          console.log('初始化后的校验规则:', this.rules);
        }
      },
    },
@@ -210,7 +226,6 @@
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.length) {
          console.log('headerList变化,重新初始化');
          if (this.isEdit && this.editData) {
            this.setFormData(this.editData);
          } else {
@@ -220,18 +235,28 @@
        }
      },
    },
    showHeaderList: {
      immediate: true,
      handler(newVal) {
        if (newVal ) {
          console.log("222222222222222222", JSON.stringify(newVal));
        }
      },
    },
  },
  methods: {
    getUserOptions() {
      listByRole().then(res => {
        if (res) {
          this.userOptions = res.map(user => ({
            value: user.userId,
            label: user.nickName || user.userName
          }));
        } else {
          this.$message.error('获取用户列表失败');
        }
      }).catch(err => {
        console.error('获取用户列表失败', err);
      });
    },
    checkEditPermission(header) {
      if (!header.role || !Array.isArray(header.role)) {
        return true;
      }
      return header.role.includes(this.currentUserId);
    },
    initRules() {
      // 初始化校验规则
      const rules = {};
@@ -248,7 +273,6 @@
          }
        });
      }
      console.log('生成的校验规则:', rules);
      this.rules = rules;
    },
    initFormData() {
@@ -272,8 +296,6 @@
      Object.keys(formData).forEach(key => {
        this.$set(this.form, key, formData[key]);
      });
      console.log('初始化后的表单数据:', this.form);
    },
    setFormData(data) {
      // 设置基础表单数据
@@ -309,14 +331,13 @@
      }
      // 设置图谱列表
      if (data.spectrums && data.spectrums.length) {
        this.spectrumList = data.spectrums.map((spectrum) => ({
          name: spectrum.name,
          url: spectrum.url,
          status: "success",
        }));
      } else {
        this.spectrumList = [];
      this.imageList = [];
      const imageHeader = this.headerList.find(h => h.type === 'image');
      if (imageHeader && data[imageHeader.name]) {
        this.imageList = [{
          name: 'image',
          url: getFullUrl(data[imageHeader.name]),
        }];
      }
      // 重置表单校验状态
@@ -337,50 +358,78 @@
      this.dialogVisible = false;
      this.$refs.form?.resetFields();
      this.photoList = [];
      this.spectrumList = [];
      this.imageList = [];
      this.initFormData();
    },
    handleSubmit() {
      console.log('开始提交表单');
      console.log('表单数据:', this.form);
      console.log('校验规则:', this.rules);
      
      this.$refs.form.validate((valid) => {
        console.log('表单验证结果:', valid);
        if (valid) {
          const submitData = {
            ...this.form,
            photos: this.photoList,
            spectrums: this.spectrumList,
          };
          console.log('提交数据:', submitData);
          // 为用户类型字段添加用户完整信息
          if (this.headerList && this.headerList.length) {
            this.headerList.forEach(header => {
              if (header.type === 'user' && Array.isArray(submitData[header.name])) {
                // 为每个用户类型字段添加userInfo属性,包含用户完整信息
                submitData[`${header.name}_userInfo`] = submitData[header.name].map(userId => {
                  const userInfo = this.userOptions.find(user => user.value === userId);
                  return userInfo ? userInfo : { value: userId, label: userId };
                });
              }
            });
          }
          console.log(submitData,'修改的数据')
          this.$emit("success", submitData);
          this.handleClose();
        } else {
          console.log('表单验证失败');
          this.$message.error('请填写必填项');
        }
      });
    },
    handlePhotoChange(file, fileList) {
      this.photoList = fileList;
      this.$refs.form.validateField("photos");
    handleImageChange(file, fileList) {
      this.imageList = fileList;
      const imageHeader = this.headerList.find(h => h.type === 'image');
      if (imageHeader) {
        this.$refs.form.validateField(imageHeader.name);
      }
    },
    handleSpectrumChange(file, fileList) {
      this.spectrumList = fileList;
      this.$refs.form.validateField("spectrums");
    handleImageSuccess(res, file, fileList) {
      console.log('res, file, fileList',res, file, fileList)
      const url = res.msg;
      file.url = getFullUrl(url);
      const imageHeader = this.headerList.find(h => h.type === 'image');
      if (imageHeader) {
        this.$set(this.form, imageHeader.name, url);
        this.$refs.form.validateField(imageHeader.name);
      }
      this.imageList = fileList.map(f => {
        if (f.uid === file.uid) {
          return file;
        }
        return f;
      });
    },
    handleSpectrumRemove(file) {
      // 处理文件移除逻辑
    handleImageRemove(file, fileList) {
      const imageHeader = this.headerList.find(h => h.type === 'image');
      if (imageHeader) {
        this.$set(this.form, imageHeader.name, '');
      }
      this.imageList = fileList;
    },
    handleIPadSpectrum() {
      // TODO: 调用 iPad 选择图谱功能
      console.log("调用 iPad 选择图谱功能");
    handlePreview(file) {
      this.imagePreviewUrl = file.url;
      this.imagePreviewVisible = true;
    },
    getFullUrl,
  },
  mounted() {
    console.log("初始headerList:", this.headerList);
    // 获取用户列表数据
    this.getUserOptions();
  },
};
</script>
@@ -417,7 +466,7 @@
    .form-content {
      flex: 1;
      overflow-y: auto;
      padding: 0 10px;
      padding: 10px 10px;
      max-height: calc(90vh - 250px); // 设置内容区域最大高度
      &::-webkit-scrollbar {
@@ -433,6 +482,9 @@
        background: #f5f7fa;
      }
    }
    .el-form-item::after{
      height: 10px !important;
    }
  }
}