Jelajahi Sumber

自定义表格的样式渲染

lph 1 tahun lalu
induk
melakukan
75b08893c9

+ 14 - 0
ruoyi-ui/src/views/tableMange/components/StyleFormPanel.vue

@@ -626,6 +626,20 @@ export default {
       });
       return res;
     },
+
+    // 获取样式条件中的表名和字段
+    getStyleTableField() {
+      let res = [];
+      this.styleTableData
+        .filter((item) => item.styleType != 2)
+        .map((item) => {
+          let tableList = JSON.parse(item.conditionTableStr);
+          tableList.forEach((val) => {
+            res.push(val.tableName + "." + val.fieldName);
+          });
+        });
+      return res;
+    },
   },
   async mounted() {
     let res = await listType(this.addDateRange({ isEnablePaging: false }, []));

+ 13 - 6
ruoyi-ui/src/views/tableMange/index.vue

@@ -1223,9 +1223,10 @@ export default {
         let temp = tableFieldList[i];
         if (temp.isShow) {
           let tempArr = prefix + temp.tableName + "." + temp.fieldName;
-          if (temp.isChildren) {
-            tempArr += asOrSpace + temp.tableName + "_" + temp.fieldName;
-          }
+          // 给主表也加上表名前缀
+          // if (temp.isChildren) {
+          tempArr += asOrSpace + temp.tableName + "_" + temp.fieldName;
+          // }
           fieldArr.push(tempArr);
         }
         if (temp.relationTable && temp.relationFieldName && temp.relationType) {
@@ -1270,6 +1271,7 @@ export default {
     getSQLStr() {
       let prefix = "{DBNAME}.";
       let sqlType = this.databaseType; //数据库类型
+      let asOrSpace = sqlType == "oracle" ? " " : " AS ";
       // let sqlType = "oracle";
       let sql = "";
       // mysql
@@ -1285,8 +1287,13 @@ export default {
       // if (discriISEmpty) {
       //   return false;
       // }
+      let styleFieldList = this.$refs.styleTableRef.getStyleTableField();
+      styleFieldList = styleFieldList.map((item) => {
+        return `${prefix}${item}${asOrSpace}${item.replace(".", "_")}`;
+      });
+      let set = new Set([...fieldNameArr, ...styleFieldList]);
+      fieldNameArr = [...set];
       let isNeedUsername = sqlType == "oracle" ? this.username + "." : "";
-      let asOrSpace = sqlType == "oracle" ? " " : " AS ";
       sql +=
         fieldNameArr.join(",") +
         " FROM " +
@@ -1369,7 +1376,8 @@ export default {
           tempFieldName = temp.tableName + "_" + temp.fieldName;
           exportFieldName = temp.tableName + "@" + temp.fieldName;
         } else {
-          tempFieldName = temp.fieldName;
+          // tempFieldName = temp.fieldName;
+          tempFieldName = temp.tableName + "_" + temp.fieldName;
           exportFieldName = temp.fieldName;
         }
         if (temp.isShow) {
@@ -1529,7 +1537,6 @@ export default {
           //   this.$message.error("请补全关联条件");
           //   return;
           // }
-          console.log("123", columns);
           this.uuid = uuidv4();
           this.tableKey = uuidv4();
           // 表单

+ 235 - 29
ruoyi-ui/src/views/tablelist/commonTable/listInfo.vue

@@ -121,13 +121,15 @@
       :data="tableList"
       @selection-change="handleSelectionChange"
       row-key="id"
+      :cell-style="cellStyle"
     >
       <el-table-column
         type="selection"
         width="55"
         reserve-selection
         align="center"
-      />
+      >
+      </el-table-column>
       <!-- <span v-for="(key, val) in columns" :key="key">
         <el-table-column :label="key" align="center" :prop="val" />
       </span> -->
@@ -137,7 +139,74 @@
         :label="item.value"
         align="center"
         :prop="item.key"
-      />
+      >
+        <template slot-scope="scope">
+          <!-- 存在字段样式或字典样式 -->
+          <template
+            v-if="
+              scope.row.styleFieldObj != undefined &&
+              scope.row.styleFieldObj[item.key]
+            "
+          >
+            <!-- 字段样式 -->
+            <template v-if="scope.row.styleFieldObj[item.key].styleType == 1">
+              <!-- 一般字体样式 -->
+              <template
+                v-if="scope.row.styleFieldObj[item.key].fieldStyleType == 0"
+              >
+                <span
+                  :style="`color:${
+                    scope.row.styleFieldObj[item.key].fontColor
+                  }`"
+                  >{{ scope.row[item.key] }}</span
+                >
+              </template>
+              <!-- 标签字体样式 -->
+              <template
+                v-else-if="
+                  scope.row.styleFieldObj[item.key].fieldStyleType == 1
+                "
+              >
+                <el-tag
+                  :type="scope.row.styleFieldObj[item.key].tagType"
+                  :effect="
+                    scope.row.styleFieldObj[item.key].isTagFullBg
+                      ? 'dark'
+                      : 'light'
+                  "
+                >
+                  {{ scope.row[item.key] }}
+                </el-tag>
+              </template>
+            </template>
+            <!-- 字典样式 -->
+            <template
+              v-else-if="scope.row.styleFieldObj[item.key].styleType == 2"
+            >
+              <span
+                v-if="
+                  scope.row.styleFieldObj[item.key].listClass == '' ||
+                  scope.row.styleFieldObj[item.key].listClass == 'default'
+                "
+                >{{ scope.row.styleFieldObj[item.key].dictLabel }}</span
+              >
+              <el-tag
+                v-else
+                :type="
+                  scope.row.styleFieldObj[item.key].listClass == 'primary'
+                    ? ''
+                    : scope.row.styleFieldObj[item.key].listClass
+                "
+                >{{ scope.row.styleFieldObj[item.key].dictLabel }}</el-tag
+              >
+            </template>
+          </template>
+          <!-- 显示默认值 -->
+          <template v-else>
+            {{ scope.row[item.key] }}
+          </template>
+        </template>
+      </el-table-column>
       <el-table-column
         label="操作"
         align="center"
@@ -212,16 +281,17 @@ import {
   getInfoBySqlKey,
   addTableData,
   batchEdit,
-  getStatisticList
+  getStatisticList,
 } from "@/api/tablelist/commonTable";
-import {getToken} from "@/utils/auth";
+import { listData } from "@/api/system/tenant/data";
+import { getToken } from "@/utils/auth";
 import Queryfrom from "@/views/tablelist/commonTable/queryfrom.vue";
-import {camelCase} from "@/utils";
-import {inputDisableComplete} from "@/utils/other";
+import { camelCase } from "@/utils";
+import { inputDisableComplete } from "@/utils/other";
 
 export default {
   name: "listInfo",
-  components: {Queryfrom},
+  components: { Queryfrom },
   data() {
     return {
       // 遮罩层
@@ -260,7 +330,7 @@ export default {
         // 是否更新已经存在的数据
         updateSupport: 0,
         // 设置上传的请求头部
-        headers: {Authorization: "Bearer " + getToken()},
+        headers: { Authorization: "Bearer " + getToken() },
         // 上传的地址
         url: process.env.VUE_APP_BASE_API3 + "common/uploadData",
       },
@@ -302,6 +372,10 @@ export default {
       defaultValue: {},
       // 统计card
       statisticList: [],
+      // 样式表
+      styleList: [],
+      // 字典样式对象
+      dictStyleObj: {},
     };
   },
 
@@ -309,6 +383,14 @@ export default {
     // 得到当前展示的table的唯一标识
     this.tableKey = this.$route.query.tableKey;
   },
+  watch: {
+    tableList: {
+      handler(val) {
+        console.log(JSON.parse(JSON.stringify(val)), "tableListChange");
+      },
+      deep: true,
+    },
+  },
   methods: {
     /** 查询列表 */
     getList(queryParams) {
@@ -316,17 +398,22 @@ export default {
       // 序列化当前查询参数列表
       queryParams && (this.queryParams.queryMap = queryParams.queryMap);
       // 获取当前表单结构信息
-      dragTableInfo({queryMap: {tableKey: this.tableKey}})
+      dragTableInfo({ queryMap: { tableKey: this.tableKey } })
         .then((res) => {
-          console.log(res);
           // 得到当前模版信息 --- sql columns queryWhere
           this.templateInfo = res.data.resultMap;
+          this.styleList = res.data.resultMap.style?.map((item) => {
+            item.styleField = camelCase(
+              item.styleField.replace(".", "_") || ""
+            );
+            return item;
+          });
           // console.log('res', this.templateInfo)
           this.queryParams.orderByColumn =
             res.data.resultMap.querySql.orderByColumn;
           this.sortOrder = JSON.parse(res.data.resultMap.querySql.sortOrder);
           // 根据拖拽时设置当前列表排列顺序
-          this.queryParams.isAsc = this.sortOrder ? "DESC" : "ASC"
+          this.queryParams.isAsc = this.sortOrder ? "DESC" : "ASC";
           this.tableName = this.templateInfo.template.dtTableName;
           // 得到查询条件
           this.queryFromWhere = res.data.resultMap.where;
@@ -343,30 +430,35 @@ export default {
             this.queryParams.orderByColumn || ""
           );
           // 根据sql语句查询当前表数据
-          console.log(this.queryParams)
-          unionListTableData(this.queryParams).then((res) => {
+          unionListTableData(this.queryParams).then(async (res) => {
             // console.log('unionListTableData');
             this.tableList = [];
             res.rows.forEach((item) => {
               this.tableList.push(item.resultMap);
             });
             // 驼峰转换
-            this.tableList = this.tableList.map((item) => {
+            let tempTableList = [];
+            tempTableList = this.tableList.map((item) => {
               let kv = {};
               for (let itemKey in item) {
                 kv[camelCase(itemKey)] = item[itemKey];
               }
               return kv;
             });
+            // this.setDictStyleData().then(() => {
+            //   this.tableList = this.setFieldStyleData(this.tableList);
+            // });
+            this.tableList = await this.setFieldStyleData(tempTableList);
             this.total = res.total;
             this.loading = false;
           });
 
           // 查询统计信息
-          getStatisticList({queryMap: {tableKey: this.templateInfo.template.tableKey}}).then(res => {
-            console.log('getStatisticList', res);
-            this.statisticList = res.data
-          })
+          getStatisticList({
+            queryMap: { tableKey: this.templateInfo.template.tableKey },
+          }).then((res) => {
+            this.statisticList = res.data;
+          });
         });
     },
     isUpperCase(char) {
@@ -436,9 +528,9 @@ export default {
       this.$refs.mychild.pageList(
         row == undefined
           ? {
-            limit: this.queryParams.pageSize,
-            page: this.queryParams.pageNum,
-          }
+              limit: this.queryParams.pageSize,
+              page: this.queryParams.pageNum,
+            }
           : row
       );
     },
@@ -468,7 +560,7 @@ export default {
     handleAdd(row) {
       // this.reset();
       this.defaultValue = {};
-      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({data}) => {
+      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({ data }) => {
         if (!data || !data.dfVueTemplate) {
           this.$message.error("当前表格未绑定表单!");
           return;
@@ -485,7 +577,7 @@ export default {
     },
     /** 修改按钮操作 */
     handleUpdate(row) {
-      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({data}) => {
+      getInfoBySqlKey(this.templateInfo.template.sqlKey).then(({ data }) => {
         if (!data || !data.dfVueTemplate) {
           this.$message.error("当前表格未绑定表单!");
           return;
@@ -564,8 +656,7 @@ export default {
           this.$refs.mychild.pageList();
           this.$modal.msgSuccess("删除成功");
         })
-        .catch(() => {
-        });
+        .catch(() => {});
     },
     /** 导出按钮操作 */
     handleExport() {
@@ -598,7 +689,7 @@ export default {
     importTemplate() {
       this.download(
         process.env.VUE_APP_BASE_API3 +
-        `common/exportTemplate?tableName=${this.tableName}&sqlkey=${this.templateInfo.template.sqlKey}`,
+          `common/exportTemplate?tableName=${this.tableName}&sqlkey=${this.templateInfo.template.sqlKey}`,
         {},
         `下载模版名称${new Date().getTime()}.xlsx`
       );
@@ -614,10 +705,10 @@ export default {
       this.$refs.upload.clearFiles();
       this.$alert(
         "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
-        response.msg +
-        "</div>",
+          response.msg +
+          "</div>",
         "导入结果",
-        {dangerouslyUseHTMLString: true}
+        { dangerouslyUseHTMLString: true }
       );
       this.$refs.mychild.pageList({
         limit: this.queryParams.pageSize,
@@ -703,6 +794,121 @@ export default {
           console.log("验证未通过,获取失败");
         });
     },
+    // 判断是否生效行样式
+    cellStyle({ row, column, rowIndex, columnIndex }) {
+      let rowStyleList = this.styleList.filter((item) => item.styleType == 0);
+      if (!rowStyleList.length) return "";
+      let mainTableName = this.templateInfo.querySql.tableAlias; //主表名
+      for (let i = 0; i < rowStyleList.length; i++) {
+        let item = rowStyleList[i];
+        let judgeRes = this.determineCondition(item.styleCondtion, row);
+        if (judgeRes) {
+          let styleCode = JSON.parse(item.styleCode);
+          return `background-color:${styleCode.rowBgColor}`;
+        }
+      }
+    },
+
+    // 获取生效条件组结果
+    determineCondition(conditionStr, row) {
+      let conditionList = JSON.parse(conditionStr);
+      if (!conditionList.length) return false;
+      return conditionList.every((item) => this.judgeOneCondition(item, row));
+    },
+
+    // 获取单个判断条件结果
+    judgeOneCondition(item, row) {
+      let fullField = camelCase(item.tableName + "_" + item.fieldName);
+      switch (item.condition) {
+        case 1:
+          return row[fullField] > item.flagValue;
+        case 2:
+          return row[fullField] < item.flagValue;
+        case 3:
+          return row[fullField] == item.flagValue;
+        case 4:
+          return row[fullField] >= item.flagValue;
+        case 5:
+          return row[fullField] <= item.flagValue;
+        default:
+          return true; //默认为true
+      }
+    },
+
+    // 设置表格字段样式
+    async setFieldStyleData(tableList) {
+      let fieldConditionList = this.styleList.filter(
+        (item) => item.styleType == 1 || item.styleType == 2
+      );
+      if (!fieldConditionList.length) return tableList;
+      let res = await this.setDictStyleData();
+      console.log(res);
+      this.dictStyleObj = res;
+      console.log(JSON.parse(JSON.stringify(this.dictStyleObj)));
+      tableList.forEach((row) => {
+        // if (!row.styleFieldObj) row.styleFieldObj = {};
+        for (let i = 0; i < fieldConditionList.length; i++) {
+          let item = fieldConditionList[i];
+          if (item.styleType == 1) {
+            //字段样式
+            let judgeRes = this.determineCondition(item.styleCondtion, row);
+            if (judgeRes) {
+              let styleCode = JSON.parse(item.styleCode);
+              if (!row.styleFieldObj) row.styleFieldObj = {};
+              row.styleFieldObj[item.styleField] = {
+                styleType: item.styleType,
+                fieldStyleType: styleCode.fieldStyleType,
+                fontColor: styleCode.fontColor,
+                isTagFullBg: styleCode.isTagFullBg,
+                tagType: styleCode.tagType,
+              };
+              // row.styleField = item.styleField; //样式生效字段
+              // row.styleType = item.styleType; //0:行样式 1:字段样式 2:字典样式
+              // row.fieldStyleType = styleCode.fieldStyleType; //0:文本  1:标签
+              // row.fontColor = styleCode.fontColor;
+              // row.isTagFullBg = styleCode.isTagFullBg; //true/false
+              // row.tagType = styleCode.tagType; //string
+            }
+          } else {
+            //字典样式
+            let dicStyle = this.dictStyleObj[item.styleField]?.find((dict) => {
+              return dict.dictValue == row[item.styleField];
+            });
+            if (dicStyle) {
+              if (!row.styleFieldObj) row.styleFieldObj = {};
+              row.styleFieldObj[item.styleField] = dicStyle; //设置该字段应该显示的字典样式
+              row.styleFieldObj[item.styleField].styleType = 2;
+            }
+          }
+        }
+      });
+      return tableList;
+    },
+
+    //设置表格字典相关数据
+    setDictStyleData() {
+      let fieldConditionList = this.styleList.filter(
+        (item) => item.styleType == 2
+      );
+      if (!fieldConditionList.length) return;
+
+      return new Promise((resolve, reject) => {
+        fieldConditionList.forEach((item) => {
+          try {
+            let temp = {};
+            listData({
+              isEnablePaging: false,
+              dictType: item.styleCondtion,
+            }).then((res) => {
+              temp[item.styleField] = res.rows;
+              resolve(temp);
+            });
+          } catch (error) {
+            reject(error);
+          }
+        });
+      });
+    },
   },
 };
 </script>