king
2019-12-18 977ce3d348f898d64ea240c8397b83d3e1cc5bb4
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { is, fromJS } from 'immutable'
import { BackTop, notification} from 'antd'
import moment from 'moment'
import Api from '@/api'
import MainSearch from './mainSearch'
import MainAction from './mainAction'
import MainTable from './mainTable'
import NotFount from '@/components/404'
import Loading from '@/components/loading'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import Utils from '@/utils/utils.js'
import './index.scss'
 
export default class NormalTable extends Component {
  static propTpyes = {
    MenuNo: PropTypes.string,  // 菜单参数
    MenuID: PropTypes.string   // 菜单Id
  }
 
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    loadingview: true,    // 页面加载中
    viewlost: false,      // 页面丢失:1、未获取到配置-页面丢失;2、页面未启用
    lostmsg: '',          // 页面丢失时的提示信息
    config: {},
    searchlist: null,
    actions: null,
    columns: null,
    arr_field: '',
    setting: null,
    data: null,
    total: 0,
    loading: false,
    pageIndex: 1,
    pageSize: 10,
    orderColumn: '',
    orderType: 'asc',
    search: '',
    configMap: {}
  }
 
  /**
   * @description 获取页面配置信息
   */
  async loadconfig () {
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: this.props.MenuID
    }
    let result = await Api.getSystemCacheConfig(param)
    if (result.status && result.LongParam) {
      let config = ''
 
      try { // 配置信息解析
        config = window.decodeURIComponent(window.atob(result.LongParam))
        config = JSON.parse(config)
      } catch (e) {
        config = ''
      }
 
      // 页面配置解析错误时提示
      if (!config) {
        notification.warning({
          top: 92,
          message: this.state.dict['main.page.settingerror'],
          duration: 10
        })
        return
      }
 
      // 页面未启用时,显示未启用页面
      if (!config.enabled) {
        this.setState({
          loadingview: false,
          viewlost: true,
          lostmsg: this.state.dict['main.view.unenabled']
        })
        return
      }
 
      let _arrField = []     // 字段集
      let _columns = []      // 显示列
      let _hideCol = []      // 隐藏及合并列中字段的uuid集
      let colMap = new Map()
 
      // 1、筛选字段集,2、过滤隐藏列及合并列中的字段uuid
      config.columns.forEach(col => {
        if (col.field) {
          _arrField.push(col.field)
        }
        if (col.type === 'colspan' && col.sublist) { // 筛选隐藏列
          _hideCol = _hideCol.concat(col.sublist)
        } else if (col.Hide === 'true') {
          _hideCol.push(col.uuid)
        }
        colMap.set(col.uuid, col)
      })
 
      // 生成显示列,处理合并列中的字段
      config.columns.forEach(col => {
        if (_hideCol.includes(col.uuid)) return
 
        if (col.type === 'colspan' && col.sublist) {
          let _col = JSON.parse(JSON.stringify(col))
          let subColumn = []
          _col.sublist.forEach(sub => {
            if (colMap.has(sub)) {
              subColumn.push(colMap.get(sub))
            }
          })
          _col.subColumn = subColumn
          _columns.push(_col)
        } else {
          _columns.push(col)
        }
      })
 
      // 添加操作列(存在时)(未经过权限过滤)
      if (config.gridBtn && config.gridBtn.display) {
        _columns.push({
          ...config.gridBtn,
          operations: config.action.filter(item => item.position === 'grid')
        })
      }
 
      // 过滤工具栏按钮(未经过权限过滤)
      let _actions = config.action.filter(item => item.position === 'toolbar')
 
      this.setState({
        loadingview: false,
        config: config,
        setting: config.setting,
        searchlist: config.search,
        actions: _actions,
        columns: _columns,
        arr_field: _arrField.join(','),
        search: Utils.initMainSearch(config.search), // 搜索条件初始化(含有时间格式,需要转化)
        loading: true
      }, () => {
        this.improveSearch()
        this.loadmaindata()
      })
    } else {
      this.setState({
        loadingview: false,
        viewlost: true
      })
      notification.warning({
        top: 92,
        message: result.message,
        duration: 10
      })
    }
  }
 
  improveSearch = () => {
    let searchlist = JSON.parse(JSON.stringify(this.state.searchlist))
    let deffers = []
    searchlist.forEach(item => {
      if (item.type !== 'select' && item.type !== 'link') return
      if (item.setAll === 'true') {
        item.options.unshift({
          key: Utils.getuuid(),
          Value: '',
          Text: this.state.dict['main.all']
        })
      }
 
      if (item.resourceType === '1' && item.dataSource) {
        let arrfield = item.valueField + ',' + item.valueText
        if (item.type === 'link') {
          arrfield = arrfield + ',' + item.linkField
        }
        let param = {
          func: 'sPC_Get_SelectedList',
          LText: item.dataSourceSql,
          obj_name: 'data',
          arr_field: arrfield
        }
 
        param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
        param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
        let defer = new Promise(resolve => {
          Api.getSystemCacheConfig(param).then(res => {
            res.search = item
            resolve(res)
          })
        })
        deffers.push(defer)
      } else if (item.resourceType === '1' && !item.dataSource) {
        notification.warning({
          top: 92,
          message: item.label + ': ' + this.state.dict['main.datasource.settingerror'],
          duration: 10
        })
      }
    })
 
    this.setState({searchlist: JSON.parse(JSON.stringify(searchlist))})
 
    if (deffers.length === 0) return
 
    Promise.all(deffers).then(result => {
      result.forEach(res => {
        if (res.status) {
          searchlist = searchlist.map(item => {
            if (item.uuid === res.search.uuid) {
              res.data.forEach(cell => {
                item.options.push({
                  key: Utils.getuuid(),
                  Value: cell[res.search.valueField],
                  Text: cell[res.search.valueText]
                })
              })
            }
            return item
          })
        } else {
          notification.warning({
            top: 92,
            message: res.search.label + ':' + res.message,
            duration: 10
          })
        }
      })
      this.setState({searchlist})
    })
  }
 
 
  async loadmaindata () {
    const { arr_field, pageIndex, pageSize, orderColumn, orderType, search, setting } = this.state
 
    let _search = Utils.joinMainSearchkey(search)
    _search = _search ? 'where (' + _search + ')' : ''
    // 获取列表数据
    let param = {
      func: setting.innerFunc || 'sPC_Get_TableData',
      obj_name: 'data',
      arr_field: arr_field
    }
 
    let orderBy = orderColumn ? (orderColumn + ' ' + orderType) : setting.order
 
    let LText = `select top ${pageSize} ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by ${orderBy}) as rows from ${setting.dataresource} ${_search}) tmptable where rows > ${pageSize * (pageIndex - 1)} order by tmptable.rows`
    let DateCount = `select count(1) as total from ${setting.dataresource} ${_search}`
    console.log(LText)
    param.LText = Utils.formatOptions(LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    param.DateCount = Utils.formatOptions(DateCount)
 
    let result = await Api.genericInterface(param)
    if (result.status) {
      this.setState({
        data: result.data.map((item, index) => {
          item.key = index
          return item
        }),
        total: result.total,
        loading: false
      })
    } else {
      // this.setState({
      //   data: [1,2,3,4,5,6,7,8,9,10].map((item, index) => {
      //     let cell = {}
      //     this.state.config.columns.forEach(column => {
      //       if (!column.field) return
      //       cell[column.field] = 'test' + item
      //     })
      //     cell.key = index
      //     return cell
      //   }),
      //   total: 329,
      //   loading: false
      // })
      this.setState({
        loading: false
      })
      notification.error({
        top: 92,
        message: result.message,
        duration: 15
      })
    }
  }
 
  refreshbysearch = (searches) => {
    // 搜索条件变化
    this.refs.mainTable.resetTable()
 
    this.setState({
      loading: true,
      pageIndex: 1,
      search: searches
    }, () => {
      this.loadmaindata()
    })
  }
 
  refreshbytable = (pagination, filters, sorter) => {
    // 表格查询条件修改
    if (sorter.order) {
      let _chg = {
        ascend: 'asc',
        descend: 'desc'
      }
      sorter.order = _chg[sorter.order]
    }
 
    this.setState({
      loading: true,
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      orderColumn: sorter.field || this.state.setting.orderColumn,
      orderType: sorter.order || 'asc'
    }, () => {
      this.loadmaindata()
    })
  }
 
  reloadtable = () => {
    this.refs.mainTable.resetTable()
    this.setState({
      loading: true,
      pageIndex: 1
    }, () => {
      this.loadmaindata()
    })
  }
 
  reloadview = () => {
    this.setState({
      loadingview: true,    // 页面加载中
      viewlost: false,      // 页面丢失:1、未获取到配置-页面丢失;2、页面未启用
      lostmsg: '',          // 页面丢失时的提示信息
      config: {},
      searchlist: null,
      actions: null,
      columns: null,
      arr_field: '',
      setting: null,
      data: null,
      total: 0,
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      orderColumn: '',
      orderType: 'asc',
      search: '',
      configMap: {}
    }, () => {
      this.loadconfig()
    })
  }
 
  refreshbyaction = (btn, type) => {
    // 按钮操作后刷新表格,重置页码及选择项
    if (btn.execSuccess === 'grid' && type === 'success') {
      this.reloadtable()
    } else if (btn.execError === 'grid' && type === 'error') {
      this.reloadview()
    } else if (btn.execSuccess === 'view' && type === 'success') {
      this.reloadtable()
    } else if (btn.execError === 'view' && type === 'error') {
      this.reloadview()
    }
  }
 
  gettableselected = () => {
    // 获取表格选择项
    let data = []
    this.refs.mainTable.state.selectedRowKeys.forEach(item => {
      data.push(this.refs.mainTable.props.data[item])
    })
    return data
  }
 
  UNSAFE_componentWillMount () {
    // 组件加载时,获取菜单数据
    this.loadconfig()
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
 
  render() {
    const { setting, searchlist, actions, columns, loadingview, viewlost } = this.state
 
    return (
      <div className="commontable" id={'commontable' + this.props.MenuID}>
        {loadingview && <Loading />}
        {searchlist && searchlist.length > 0 ?
          <MainSearch
            refreshdata={this.refreshbysearch}
            searchlist={searchlist}
            dict={this.state.dict}
          /> : null
        }
        {actions &&
          <MainAction
            MenuID={this.props.MenuID}
            setting={setting}
            refreshdata={this.refreshbyaction}
            gettableselected={this.gettableselected}
            actions={actions}
            dict={this.state.dict}
          />
        }
        {columns &&
          <MainTable
            ref="mainTable"
            MenuID={this.props.MenuID}
            setting={setting}
            refreshdata={this.refreshbytable}
            columns={columns}
            data={this.state.data}
            total={this.state.total}
            loading={this.state.loading}
            dict={this.state.dict}
          />
        }
        <BackTop>
          <div className="ant-back-top">
            <div className="ant-back-top-content">
              <div className="ant-back-top-icon"></div>
            </div>
          </div>
        </BackTop>
        {viewlost ? <NotFount msg={this.state.lostmsg} /> : null}
      </div>
    )
  }
}