chenlu
8 小时以前 33dbc6a161554f3a897f9e9273feb4f2c1b47381
north-glass-erp/northglass-erp/src/components/BasicTable.vue
@@ -2,11 +2,19 @@
import {Search} from "@element-plus/icons-vue"
import {defineEmits, onMounted, reactive, ref, watch} from "vue"
import {changeFilterEvent} from "@/hook"
import request from "@/utils/request";
import request from "@/utils/request"
import exportExcel  from "@/hook/exportExcel"
import {addListener,exportData} from "@/hook/mouseMove"
import deepClone from "@/utils/deepClone";
import {ElMessage} from "element-plus";
import * as XLSX from "xlsx";
import {useI18n} from "vue-i18n";
import useOrderInfoStore from "@/stores/sd/order/orderInfo";
const { t } = useI18n()
const xGrid = ref()
let filterData = ref({})
const orderInfo = useOrderInfoStore()
const gridOptions = reactive({
  loading:true,
  border:  "full",//表格加边框
@@ -19,7 +27,8 @@
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  scrollY:{ enabled: true },//开启虚拟滚动
  scrollY:{ enabled: true,gt:0 },//开启虚拟滚动
  scrollX:{ enabled: true,gt:5 },//开启虚拟滚动
  showOverflow:true,
  columnConfig: {
    resizable: true,
@@ -36,12 +45,25 @@
    mode: 'row',
    showStatus: true
  },//表头参数
  columns:[
  menuConfig: {
    body: {
      options: [
        [
          { code: 'exportExcelChecked', name: t('components.exportSelected'), prefixIcon: 'vxe-icon-download', visible: true }
        ]
      ]
    }
  },
  columns:[
  ],//表头按钮
  toolbarConfig: {
    buttons: [],
    slots: {
      tools: 'toolbar_buttons',
      buttons:'buttons'
    },
    // import: false,
    // export: true,
    // print: true,
@@ -54,7 +76,7 @@
    return[
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return '合计:'
          return t('basicData.total')
        }
        if (props.childrenData.footList.includes(column.field)) {
          return sumNum(data, column.field)
@@ -65,6 +87,26 @@
  }
})
const gridEvents = {
  menuClick ({ menu, row, column }) {
    const $grid = xGrid.value
    if ($grid) {
      switch (menu.code) {
        case 'exportExcelChecked': {
          let result = exportData()
          if(result){
            // 将数据转换为 worksheet 对象
            const worksheet = XLSX.utils.aoa_to_sheet(result);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            XLSX.writeFile(workbook, `${props.childrenData.exportName}.xlsx`);
          }
          break
        }
      }
    }
  }
}
const props = defineProps({
@@ -74,7 +116,7 @@
  }
})
const basicProp = ref({
  pageSize : 100,//页面显示数量
  pageSize : 10000,//页面显示数量
  pageNum:1,//当前页
  selectDate:['',''],//查询的日期
  pageTotal : 0,//总页数
@@ -88,6 +130,71 @@
  return count.toFixed(2)
}
//合并显示其他列
const handleDynamicColumns = (data,title) => {
  // 1. 收集所有行的otherColumns字段(去重)
  const allOtherFields = new Set();
  data.forEach(row => {
    if (!row || !row.otherColumns) return;
    let parsedOtherColumns;
    try {
      // 核心:将字符串解析为JSON
      parsedOtherColumns = JSON.parse(row.otherColumns);
    } catch (e) {
      console.error('解析otherColumns失败:', e, '原始数据:', row.otherColumns);
      return;
    }
    // 2. 从解析后的JSON中收集字段(支持数组或对象格式)
    if (Array.isArray(parsedOtherColumns)) {
      // 数组格式:[{ key: 'field1', label: '字段1', value: '值1' }, ...]
      parsedOtherColumns.forEach(item => {
        if (item.key) allOtherFields.add(item.key);
      });
    } else if (typeof parsedOtherColumns === 'object' && parsedOtherColumns !== null) {
      // 对象格式:{ field1: { label: '字段1', value: '值1' }, ... }
      Object.keys(parsedOtherColumns).forEach(key => {
        allOtherFields.add(key);
      });
    }
  });
  // 2. 生成动态子列(作为processList的children)
  const otherColumns = Array.from(allOtherFields).map(field => {
    // 尝试获取字段对应的label(优先取第一个出现的label)
    let label=field;
    title.forEach(item=>{
      if(field==item.column){
        label=item.alias
      }
    })
    return {
      title: label,
      field: `otherColumnsJson.${field}`,
      width: 120,
      align: 'center',
      // 处理字段值显示(兼容数组/对象类型的otherColumns)
      formatter: ({ row }) => {
        return row.otherColumnsJson?.[field] || '';
      }
    };
  });
  // 3. 定义父级列processList,包含动态子列
  const processList = {
    title: t('basicData.otherColumns'),
    field: 'process',
    children: otherColumns // 将动态列作为子列
  };
  // 4. 先移除已存在的process列(避免重复),再添加新列
  gridOptions.columns = gridOptions.columns.filter(col => col.field !== 'process');
  gridOptions.columns.push(processList);
}
watch(props, (newVal) => {
@@ -97,8 +204,7 @@
onMounted(() => {
  gridOptions.columns = props.childrenData.columns
  getReportData()
  addListener(xGrid.value,gridOptions)
})
function filterChanged(column){
  //gridOptions.loading=true
@@ -132,26 +238,57 @@
}
const  getReportData = () => {
  request.post(`${props.childrenData.url}/${basicProp.value.pageNum}/${basicProp.value.pageSize}/${basicProp.value.selectDate}`,filterData.value).then(res => {
  if(props.childrenData.model!=null){
    request.post(`${props.childrenData.url}/${basicProp.value.pageNum}/${basicProp.value.pageSize}/${orderInfo.reportFormDate}/${props.childrenData.model}/${props.childrenData.scope}`,filterData.value).then(res => {
      if(res.code === '200'){
        props.childrenData.data = res.data.data
        basicProp.value.pageTotal = res.data.total.pageTotal
        basicProp.value.dataTotal = res.data.total.total
        orderInfo.reportFormDate = res.data.selectDate
        //订单明细报表
        if (props.childrenData.url === '/order/getOrderReport') {
          const dataList = res.data.data || [];
          handleDynamicColumns(dataList,res.data.title)
        }
      }
    })
    return
  }
  request.post(`${props.childrenData.url}/${basicProp.value.pageNum}/${basicProp.value.pageSize}/${orderInfo.reportFormDate}`,filterData.value).then(res => {
    if(res.code === '200'){
      props.childrenData.data = res.data.data
      basicProp.value.pageTotal = res.data.total.pageTotal
      basicProp.value.dataTotal = res.data.total.total
      basicProp.value.selectDate = res.data.selectDate
      orderInfo.reportFormDate = res.data.selectDate
    }
  })
}
const exportEvent = () => {
  const $table = xGrid.value
  if ($table) {
    $table.exportData({
      filename: 'order_export',
      sheetName: 'Sheet1',
      type: 'xlsx'
    })
  }
}
</script>
<template>
  <div class="main-div">
  <div  style="width: 100%;height: 100%">
    <div class="head">
    <el-date-picker
        v-model="basicProp.selectDate"
        v-model="orderInfo.reportFormDate"
        type="daterange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        :start-placeholder="$t('basicData.startDate')"
        :end-placeholder="$t('basicData.endDate')"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
    />
@@ -160,14 +297,16 @@
        id="searchButton"
        type="primary"
        style="margin-top: -5px"
        :icon="Search">查询</el-button>
    <div class="order-detail">
        :icon="Search">{{$t('basicData.search')}}</el-button>
    </div>
    <div class="main-table">
      <vxe-grid
          @filter-change="filterChanged"
          height="110%"
          height="100%"
          class="mytable-scrollbar"
          ref="xGrid"
          v-bind="gridOptions"
          v-on="gridEvents"
      >
        <!--      下拉显示所有信息插槽-->
        <template #content="{ row }">
@@ -182,10 +321,31 @@
        <template #num1_filter="{ column, $panel }">
          <div>
            <div v-for="(option, index) in column.filters" :key="index">
              <input type="type" v-model="option.data" @input="changeFilterEvent($event, option, $panel)"/>
              <input type="text"
                     v-model="option.data"
                     @keyup.enter.native="$panel.confirmFilter()"
                     @input="changeFilterEvent($event, option, $panel)"/>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
          <vxe-button icon="vxe-icon-download" circle
                    style="margin-right: 0.5rem"
                    @click="exportEvent" />
          <vxe-button icon="vxe-icon-cloud-download" style="margin-right: 0.5rem"
                      circle
                    @click="exportExcel(props.childrenData.exportUrl,
                                          props.childrenData.exportName,
                                          orderInfo.reportFormDate)" />
        </template>
        <template #buttons>
          <slot  name="buttons"></slot>
        </template>
        <template #pager>
          <!--使用 pager 插槽-->
          <!--        'PrevJump','NextJump', -->
@@ -219,12 +379,25 @@
  border: none !important;
  background-color: transparent;
}
.order-primary{
.head{
  width: 100%;
  height: 35px;
}
.order-detail{
  width: 100%;
  height:  calc(100% - 30px);
.main-table{
  width: 100%;
  height: calc(100% - 35px);
}
.vxe-grid {
  /* 禁用浏览器默认选中 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
:deep(#product .el-dialog__body){
  height: 90%;
  width: 100%;
}
</style>