king
2023-11-14 169f6cd29a0d3add4fe2cf35c3579b45fa83c0d4
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { is, fromJS } from 'immutable'
import { Button, Modal, notification, message } from 'antd'
 
import ExcelIn from './excelin'
import Utils, { getExcelInSql } from '@/utils/utils.js'
import Api from '@/api'
import MKEmitter from '@/utils/events.js'
import MkIcon from '@/components/mk-icon'
// import './index.scss'
 
const { confirm } = Modal
 
class ExcelInButton extends Component {
  static propTpyes = {
    BID: PropTypes.string,            // 主表ID
    BData: PropTypes.any,             // 主表数据
    selectedData: PropTypes.any,      // 子表中选择数据
    btn: PropTypes.object,            // 按钮
    setting: PropTypes.any,           // 页面通用设置
    disabled: PropTypes.any,          // 行按钮禁用
  }
 
  state = {
    loading: false,
    selines: null,
    disabled: false,
    hidden: false,
    primaryId: '',
  }
 
  UNSAFE_componentWillMount () {
    const { btn, selectedData, BData, disabled } = this.props
 
    if (btn.controlField) {
      this.setStatus(btn, selectedData || [], BData, disabled)
    } else if (disabled) {
      this.setState({disabled: true})
    }
  }
 
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
 
  componentDidMount () {
    MKEmitter.addListener('triggerBtnId', this.actionTrigger)
  }
 
  UNSAFE_componentWillReceiveProps (nextProps) {
    const { btn } = this.props
 
    if (btn.controlField) {
      this.setStatus(btn, nextProps.selectedData || [], nextProps.BData, nextProps.disabled)
    } else {
      this.setState({disabled: nextProps.disabled === true})
    }
  }
 
  componentWillUnmount () {
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('triggerBtnId', this.actionTrigger)
  }
 
  setStatus = (btn, data, BData, disprop) => {
    let disabled = false
    let hidden = false
 
    if (btn.control !== 'parent') {
      if (data.length > 0) {
        data.forEach(item => {
          let s = item[btn.controlField] !== undefined ? item[btn.controlField] + '' : ''
          if (btn.controlVals.includes(s) || item.$lock) {
            disabled = true
          }
        })
      } else if (btn.controlVals.includes('')) {
        disabled = true
      }
    } else {
      if (!BData || !BData.hasOwnProperty(btn.controlField)) {
        hidden = true
      } else {
        let s = BData[btn.controlField] + ''
        if (btn.controlVals.includes(s)) {
          hidden = true
        }
      }
    }
 
    if (disabled && btn.control === 'hidden') {
      hidden = true
    }
 
    if (disprop) {
      disabled = true
    }
 
    this.setState({hidden, disabled})
  }
  
  /**
   * @description 触发按钮操作
   */
  actionTrigger = (triggerId, record, type) => {
    const { setting, BID, btn, selectedData } = this.props
    const { loading, disabled } = this.state
 
    if (loading || disabled) return
    if (triggerId && btn.uuid !== triggerId) return
 
    if (setting.supModule && !BID) {
      notification.warning({
        top: 92,
        message: '需要上级主键值!',
        duration: 5
      })
      return
    } else if (type === 'linkbtn' && !btn.$toolbtn && !is(fromJS(selectedData || []), fromJS(record))) {
      return
    }
 
    let data = record || selectedData || []
    
    if (btn.Ot === 'requiredSgl' && data.length !== 1) {
      // 需要选择单行时,校验数据
      notification.warning({
        top: 92,
        message: '请选择单行数据!',
        duration: 5
      })
      return
    } else if (!btn.verify || !btn.verify.sheet || !btn.verify.columns || btn.verify.columns.length === 0) {
      notification.warning({
        top: 92,
        message: 'excel导入验证信息未设置!',
        duration: 5
      })
      return
    }
 
    let primaryId = '' // 导入时行Id
    if (btn.Ot === 'requiredSgl' && setting.primaryKey) {
      primaryId = data[0][setting.primaryKey] || ''
    }
 
    this.setState({
      selines: data,
      primaryId: primaryId
    }, () => {
      this.refs.excelIn.exceltrigger()
    })
 
    if (window.GLOB.systemType === 'production') {
      MKEmitter.emit('queryTrigger', {menuId: btn.uuid, name: '导入Excel'})
    }
  }
 
  /**
   * @description 操作成功后处理
   * 1、excel导出,成功后取消导出按钮加载中状态
   * 2、状态码为 S 时,显示成功信息后系统默认信息
   * 3、状态码为 -1 时,不显示任何信息
   * 4、模态框执行成功后是否关闭
   * 5、通知主列表刷新
   */
  execSuccess = (res = {}) => {
    const { btn } = this.props
 
    if (res.ErrCode === 'S' || !res.ErrCode) { // 执行成功
      notification.success({
        top: 92,
        message: res.message || '执行成功!',
        duration: btn.verify && btn.verify.stime ? btn.verify.stime : 2
      })
    } else if (res.ErrCode === 'Y') { // 执行成功
      Modal.success({
        title: res.message || '执行成功!'
      })
    } else if (res.ErrCode === '-1') { // 完成后不提示
 
    }
 
    this.setState({
      loading: false
    })
 
    if (btn.execSuccess === 'closepoptab') {
      MKEmitter.emit('popclose')
    } else if (btn.execSuccess !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execSuccess, btn, '', this.state.selines)
    }
    
    if (btn.syncComponentId) {
      if (btn.syncComponentId === 'multiComponent') {
        btn.syncComponentIds.forEach((id, i) => {
          setTimeout(() => {
            if (/\$focus/.test(id)) {
              MKEmitter.emit('reloadData', id.split('$')[0], id.split('$')[1])
            } else {
              MKEmitter.emit('reloadData', id)
            }
          }, 20 * i)
        })
      } else if (/\$focus/.test(btn.syncComponentId)) {
        MKEmitter.emit('reloadData', btn.syncComponentId.split('$')[0], btn.syncComponentId.split('$')[1])
      } else {
        MKEmitter.emit('reloadData', btn.syncComponentId)
      }
    }
 
    if (btn.switchTab && btn.switchTab.length > 0) {
      let id = btn.switchTab[btn.switchTab.length - 1]
      let node = document.getElementById('tab' + id)
      node && node.click()
    }
 
    if (btn.execSuccess === 'popclose' && btn.$tabId) { // 标签关闭刷新
      MKEmitter.emit('refreshPopButton', btn.$tabId)
    }
  }
 
  /**
   * @description 操作失败后处理
   * 1、状态码为 E、N、F、NM 时,显示相应提示信息
   * 2、excel导出,失败后取消导出按钮加载中状态
   * 3、通知主列表刷新
   */
  execError = (res = {}) => {
    const { btn } = this.props
 
    if (!['LoginError', 'C', '-2', 'E', 'N', 'F', 'NM'].includes(res.ErrCode)) {
      res.ErrCode = 'E'
    }
 
    if (res.ErrCode === 'E') {
      Modal.error({
        title: res.message || '执行失败!',
      })
    } else if (res.ErrCode === 'N') {
      notification.error({
        top: 92,
        message: res.message || '执行失败!',
        duration: btn.verify && btn.verify.ntime ? btn.verify.ntime : 10
      })
    } else if (res.ErrCode === 'F') {
      notification.error({
        className: 'notification-custom-error',
        top: 92,
        message: res.message || '执行失败!',
        duration: btn.verify && btn.verify.ftime ? btn.verify.ftime : 10
      })
    } else if (res.ErrCode === 'NM') {
      message.error(res.message || '执行失败!')
    }
    
    this.setState({
      loading: false
    })
 
    if (btn.execError === 'closepoptab') {
      MKEmitter.emit('popclose')
    } else if (btn.execError !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execError, btn, '', this.state.selines)
    }
 
    if (btn.execError === 'popclose' && btn.$tabId) { // 标签关闭刷新
      MKEmitter.emit('refreshPopButton', btn.$tabId)
    }
  }
 
  /**
   * @description Excel 导入
   */
  getexceldata = (data, errors, sheetName, errDetail) => {
    const { btn, BID } = this.props
 
    if (errors) {
      if (errors === 'notexit') {
        notification.warning({
          top: 92,
          message: '工作表《' + sheetName + '》不存在!',
          duration: 5
        })
      } else if (errors === 'empty') {
        notification.warning({
          top: 92,
          message: '工作表《' + sheetName + '》为空!',
          duration: 5
        })
      } else if (errors === 'headerError') {
        notification.warning({
          top: 92,
          message: `工作表《${sheetName}》表头错误,${errDetail}`,
          duration: 5
        })
      }
 
      this.setState({ loading: false })
      return
    }
 
    if (!data || data.length === 0) {
      notification.warning({
        top: 92,
        message: '未获取到工作表《' + sheetName + '》数据!',
        duration: 5
      })
      this.setState({ loading: false })
      return
    } else if (data.length * btn.verify.columns.length > 30000) {
      notification.warning({
        top: 92,
        message: '当前导入数据量过大,如遇错误提示,请分批导入!',
        duration: 5
      })
    }
 
    let result = getExcelInSql(btn, data, (BID || ''), this.state.primaryId)
 
    if (result.errors) {
      notification.warning({
        top: 92,
        message: result.errors,
        duration: 5
      })
      this.setState({ loading: false })
      return
    }
 
    let param = {
      ID: this.state.primaryId,
      excel_in: result.lines
    }
 
    if (BID) {
      param.BID = BID
    }
 
    if (btn.intertype === 'system') { // 系统存储过程
      param.func = 'sPC_TableData_InUpDe'
 
      delete param.excel_in
 
      // param.excel_in_type = 'true'
      param.exec_type = 'y'
      param.LText = result.sql
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
 
      let unCheckParam = null
 
      if (/\$check@|@check\$/ig.test(param.LText)) {
        unCheckParam = fromJS(param).toJS()
        param.LText = param.LText.replace(/\$check@|@check\$/ig, '')
      }
 
      param.LText = Utils.formatOptions(param.LText)
      param.secretkey = Utils.encrypt('', param.timestamp)
      if (window.GLOB.mkHS) { // 云端验证
        param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
      }
 
      param.menuname = btn.logLabel
      
      if (window.GLOB.probation) {
        param.s_debug_type = 'Y'
      }
 
      if (unCheckParam) {
        unCheckParam.LText = unCheckParam.LText.replace(/\$check@/ig, '/*').replace(/@check\$/ig, '*/')
        unCheckParam.LText = Utils.formatOptions(unCheckParam.LText)
        unCheckParam.secretkey = Utils.encrypt('', unCheckParam.timestamp)
        unCheckParam.menuname = btn.logLabel
 
        if (window.GLOB.probation) {
          unCheckParam.s_debug_type = 'Y'
        }
 
        Api.genericInterface(param).then(res => {
          if (res.status) {
            this.execSuccess(res)
          } else if (res.ErrCode === 'C') {
            const _this = this
            confirm({
              title: '请确认',
              content: res.message,
              onOk() {
                return new Promise(resolve => {
                  Api.genericInterface(unCheckParam).then(result => {
                    if (result.status) {
                      _this.execSuccess(result)
                    } else {
                      _this.execError(result)
                    }
                    resolve()
                  })
                })
              },
              onCancel() {
                _this.execError(res)
              }
            })
          } else {
            this.execError(res)
          }
        }, (error) => {
          if (error && error.ErrCode === 'LoginError') return
          this.execError({})
        })
      } else {
        Api.genericInterface(param).then((res) => {
          if (res.status) {
            this.execSuccess(res)
          } else {
            this.execError(res)
          }
        }, (error) => {
          if (error && error.ErrCode === 'LoginError') return
          this.execError({})
        })
      }
    } else if (btn.intertype === 'inner' && btn.innerFunc) { // 自定义存储过程
      param.func = btn.innerFunc
 
      if (btn.recordUser === 'true') {
        param.username = sessionStorage.getItem('User_Name') || ''
        param.fullname = sessionStorage.getItem('Full_Name') || ''
      }
 
      Api.genericInterface(param).then((res) => {
        if (res.status) {
          this.execSuccess(res)
        } else {
          this.execError(res)
        }
      }, (error) => {
        if (error && error.ErrCode === 'LoginError') return
        this.execError({})
      })
    } else if (btn.intertype === 'outer') { // 外部接口
      let _outParam = null
      let ver_token = false
 
      new Promise(resolve => {
        // 内部请求
        if (btn.innerFunc) {
          param.func = btn.innerFunc
          // 存在内部函数时,数据预处理
          Api.genericInterface(param).then(res => {
            if (res.status) {
              delete res.ErrCode
              delete res.ErrMesg
              delete res.message
              delete res.status
 
              // 使用处理后的数据调用外部接口
              let keys = Object.keys(res) // 提交外部接口前,添加BID
              if (this.props.BID && keys.filter(key => key.toLowerCase() === 'bid').length === 0) {
                res.BID = this.props.BID
              }
              resolve(res)
            } else {
              this.execError(res)
              resolve(false)
            }
          }, (error) => {
            if (error && error.ErrCode === 'LoginError') return
            this.execError({})
          })
        } else {
          resolve(param)
        }
      }).then(res => {
        if (!res) return
        // 外部请求
        _outParam = fromJS(res).toJS()
 
        if (btn.sysInterface === 'true') {
          if (window.GLOB.mainSystemApi) {
            param.rduri = window.GLOB.mainSystemApi
          }
        } else if (btn.sysInterface === 'external') {
          if (window.GLOB.systemType === 'production') {
            param.$token = btn.exProInterface || ''
          } else {
            param.$token = btn.exInterface || ''
          }
          ver_token = true
        } else {
          if (window.GLOB.systemType === 'production' && btn.proInterface) {
            param.rduri = btn.proInterface
          } else {
            param.rduri = btn.interface
          }
          let host = window.GLOB.baseurl.replace(/http(s):\/\//, '')
          if (param.rduri.indexOf(host) === -1 && /\/dostars/.test(param.rduri)) {
            param.$login = true
          }
        }
 
        if (btn.outerFunc) {
          res.func = btn.outerFunc
        }
        
        if (window.GLOB.mkHS && res.func === 's_sDataDictb_excelIn') { // s_sDataDictb_excelIn 云端验证
          let sql = `Declare @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(512),@mk_organization nvarchar(512),@mk_user_type nvarchar(20),@mk_nation nvarchar(50),@mk_province nvarchar(50),@mk_city nvarchar(50),@mk_district nvarchar(50),@mk_address nvarchar(100),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)`
          param.LText = Utils.formatOptions(sql)
          param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
          param.secretkey = Utils.encrypt(param.LText, param.timestamp)
          param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
        }
 
        return Api.genericInterface(res)
      }).then(response => {
        if (!response || response.ErrCode === 'LoginError') return
        // 回调请求
        if (ver_token && response.ErrCode === 'token_error') {
          response.ErrCode = 'E'
          this.execError(response)
        } else if (btn.callbackFunc ) {
          // 存在回调函数时,调用
          delete response.message
          delete response.status
 
          response.func = btn.callbackFunc
 
          let _callbackparam = {..._outParam, ...response}
          return Api.genericInterface(_callbackparam)
        } else {
          if (response.status) {
            this.execSuccess(response)
          } else {
            this.execError(response)
          }
        }
      }).then(res => {
        if (!res || res.ErrCode === 'LoginError') return
 
        if (res.status) {
          this.execSuccess(res)
        } else {
          this.execError(res)
        }
      })
    }
  }
 
  render() {
    const { btn } = this.props
    const { loading, disabled, hidden } = this.state
 
    if (hidden) return null
 
    let label = ''
    let icon = ''
    let type = 'link'
    let className = ''
 
    if (btn.show === 'button') {
      label = btn.label
      icon = btn.icon || ''
    } else if (btn.show === 'link') {
      label = <span>{btn.label}{btn.icon ? <MkIcon style={{marginLeft: '8px'}} type={btn.icon}/> : ''}</span>
      icon = ''
    } else if (btn.show === 'icon') {
      icon = btn.icon || 'upload'
    } else if (!btn.$toolbtn) {
      icon = btn.icon || ''
      label = btn.label
      className = 'mk-btn mk-' + btn.class
    } else {
      type = ''
      icon = btn.icon || ''
      label = btn.label
      className = 'mk-btn mk-' + btn.class
    }
 
    return <>
      <Button
        type={type}
        title={disabled ? (btn.reason || '') : (btn.show === 'icon' ? btn.label : '')}
        loading={loading}
        disabled={disabled}
        style={btn.style}
        icon={icon}
        className={className}
        onClick={(e) => {e.stopPropagation(); this.actionTrigger()}}
      >{label}</Button>
      <ExcelIn btn={btn} triggerExcelIn={() => this.setState({ loading: true })} returndata={this.getexceldata} ref="excelIn" />
    </>
  }
}
 
export default ExcelInButton