廖井涛
10 小时以前 4a64552686d1911fd23716ddcff575d9b03ce780
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<script setup>
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 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",//表格加边框
  keepSource: true,//保持源数据
  align: 'center',//文字居中
  stripe:true,//斑马纹
  rowConfig: {isCurrent: true, isHover: true,height: 30},//鼠标移动或选择高亮
  id: 'OrderReport',
  showFooter: true,//显示脚
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  scrollY:{ enabled: true,gt:0 },//开启虚拟滚动
  scrollX:{ enabled: true,gt:5 },//开启虚拟滚动
  showOverflow:true,
  columnConfig: {
    resizable: true,
    useKey: true
  },
  filterConfig: {   //筛选配置项
    remote: true
  },
  customConfig: {
    storage: true
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },//表头参数
  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,
    zoom: true,
    custom: true
  },
  data:  [
  ],//table body实际数据
  footerMethod ({ columns, data }) {//页脚函数
    return[
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return t('basicData.total')
        }
        if (props.childrenData.footList.includes(column.field)) {
          return sumNum(data, column.field)
        }
        return ''
      })
    ]
  }
 
})
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({
  childrenData:{
    Object,
    default: ''
  }
})
const basicProp = ref({
  pageSize : 10000,//页面显示数量
  pageNum:1,//当前页
  selectDate:['',''],//查询的日期
  pageTotal : 0,//总页数
  dataTotal : 0,//数据总条数
})
const sumNum = (list, field) => {
  let count = 0
  list.forEach(item => {
    count += Number(item[field])
  })
  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) => {
  xGrid.value.loadData(props.childrenData.data)
  gridOptions.loading = false
})
onMounted(() => {
  gridOptions.columns = props.childrenData.columns
  getReportData()
  addListener(xGrid.value,gridOptions)
})
function filterChanged(column){
  //gridOptions.loading=true
  //筛选条件发生变化条件发生变化
  let value = column.datas[0]!=undefined?column.datas[0]:''
  value = value.trim()
  //判断是否存在外键
  if (column.property.indexOf('.')>-1){
    const  columnArr = column.property.split('.')
    filterData.value[columnArr[0]] = {
      [columnArr[1]]:value
    }
  }else{
    filterData.value[column.property] = value
  }
 
  gridOptions.loading = true
  getReportData()
 
}
 
const handlePageChange = ({ currentPage, pageSize }) => {
  basicProp.value.pageNum = currentPage
  basicProp.value.pageTotal = pageSize
  gridOptions.loading = true
  getReportData()
}
const dateChanged = () => {
  gridOptions.loading = true
  getReportData()
}
 
const  getReportData = () => {
  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
      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  style="width: 100%;height: 100%">
    <div class="head">
    <el-date-picker
        v-model="orderInfo.reportFormDate"
        type="daterange"
        :start-placeholder="$t('basicData.startDate')"
        :end-placeholder="$t('basicData.endDate')"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
    />
    <el-button
        @click="dateChanged"
        id="searchButton"
        type="primary"
        style="margin-top: -5px"
        :icon="Search">{{$t('basicData.search')}}</el-button>
    </div>
    <div class="main-table">
      <vxe-grid
          @filter-change="filterChanged"
          height="100%"
          class="mytable-scrollbar"
          ref="xGrid"
          v-bind="gridOptions"
          v-on="gridEvents"
      >
        <!--      下拉显示所有信息插槽-->
        <template #content="{ row }">
          <ul class="expand-wrapper">
            <li  v-for="(item,index) in gridOptions.columns" v-show="item.field!==undefined && index>9">
              <span style="font-weight: bold">{{item.title+':  '}}</span>
              <span>{{ row[item.field] }}</span>
            </li>
          </ul>
        </template>
        <!--      下拉筛选插槽-->
        <template #num1_filter="{ column, $panel }">
          <div>
            <div v-for="(option, index) in column.filters" :key="index">
              <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', -->
          <vxe-pager
              @page-change="handlePageChange"
              :layouts="[  'PrevPage', 'Jump','PageCount', 'NextPage',  'Total']"
              v-model:current-page="basicProp.pageNum"
              v-model:page-size="basicProp.pageSize"
              v-model:pager-count="basicProp.pageTotal"
              :total="basicProp.dataTotal"
          >
          </vxe-pager>
        </template>
      </vxe-grid>
 
    </div>
  </div>
</template>
 
<style scoped >
.main-div {
  width: 100%;
  height: 100%;
}
.el-col{
  border: #181818 1px solid;
}
:deep(.el-table .el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  cursor: default;
  border: none !important;
  background-color: transparent;
}
.head{
  width: 100%;
  height: 35px;
}
 
.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>