king
2022-04-27 e4546b5660297352252085315e79fb6aef2523c3
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
import md5 from 'md5'
import moment from 'moment'
import options from '@/store/options.js'
import Utils from './utils.js'
 
export default class DataUtils {
  /**
   * @description 数据源名称,用于统一查询
   * @param {Object}   setting      数据源设置
   * @param {String}   arrFields    查询字段
   * @param {Array}    search       搜索条件
   * @param {String}   orderBy      排序方式
   * @param {Number}   pageIndex    页码
   * @param {Number}   pageSize     每页数量
   * @param {String}   BID          上级ID
   * @param {String}   menuType     菜单类型,普通菜单与HS
   * @return {Object}  param
   */
  static getQueryDataParams (setting, arrFields, search = [], orderBy = '', pageIndex = 1, pageSize = 10, BID, menuType, id) {
    let param = null
 
    if (setting.interType === 'system' || (setting.interType === 'custom' && setting.requestMode === 'system')) {
      param = this.getDefaultQueryParam(setting, arrFields, search, orderBy, pageIndex, pageSize, menuType, id)
    } else {
      param = this.getCustomQueryParam(setting, search, orderBy, pageIndex, pageSize, menuType, id)
    }
 
    if (BID) {
      param.BID = BID
    }
    // 数据管理权限
    if (sessionStorage.getItem('dataM') === 'true') {
      param.dataM = 'Y'
    }
 
    return param
  }
 
  /**
   * @description 获取用户自定义存储过程传参
   */
  static getCustomQueryParam (setting, search, orderBy, pageIndex, pageSize, menuType, id) {
    let param = Utils.formatCustomMainSearch(search)
 
    if (orderBy) {
      param.OrderCol = orderBy
    }
 
    if (id) {
      param.ID = id
    } else if (setting.laypage) {
      param.PageIndex = pageIndex
      param.PageSize = pageSize
    }
 
    if (setting.interType === 'inner' || (setting.interType === 'custom' && setting.requestMode === 'inner')) {
      param.func = setting.innerFunc
    } else {
      if (menuType === 'HS') {
        if (setting.sysInterface === 'true' && options.cloudServiceApi) {
          param.rduri = options.cloudServiceApi
        } else if (setting.sysInterface !== 'true') {
          param.rduri = setting.interface
        }
      } else {
        if (setting.sysInterface === 'true' && window.GLOB.mainSystemApi) {
          param.rduri = window.GLOB.mainSystemApi
        } else if (setting.sysInterface !== 'true') {
          param.rduri = window.GLOB.systemType === 'production' ? (setting.proInterface || setting.interface) : setting.interface
        }
      }
 
      if (setting.outerFunc) {
        param.func = setting.outerFunc
      }
    }
 
    return param
  }
 
  /**
   * @description 获取系统存储过程 sPC_Get_TableData 的参数
   */
  static getDefaultQueryParam (setting, arrFields, search, orderBy, pageIndex, pageSize, menuType, id) {
    let param = {
      func: 'sPC_Get_TableData',
      obj_name: 'data',
      exec_type: 'y',
      arr_field: arrFields,
      default_sql: setting.execute ? 'true' : 'false'
    }
 
    if (setting.transaction === 'true') {
      param.func = 'sPC_Get_TableData_try'
    }
 
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
 
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
 
    let _dataresource = setting.dataresource
    let _customScript = ''
    
    if (setting.customScript) {
      _customScript = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${setting.customScript}
      `
    }
 
    _dataresource = _dataresource.replace(/@select\$|\$select@/ig, '')
    _customScript = _customScript.replace(/@select\$|\$select@/ig, '')
    _dataresource = _dataresource.replace(/\$sum@/ig, '/*')
    _dataresource = _dataresource.replace(/@sum\$/ig, '*/')
    _customScript = _customScript.replace(/\$sum@/ig, '/*')
    _customScript = _customScript.replace(/@sum\$/ig, '*/')
 
    let regoptions = null
    if (setting.queryType === 'statistics' || _customScript) {
      let allSearch = Utils.getAllSearchOptions(search)
      regoptions = allSearch.map(item => {
        return {
          reg: new RegExp('@' + item.key + '@', 'ig'),
          value: `'${item.value}'`
        }
      })
      regoptions.push({
        reg: new RegExp('@orderBy@', 'ig'),
        value: orderBy
      }, {
        reg: new RegExp('@pageSize@', 'ig'),
        value: setting.laypage ? pageSize : '9999'
      }, {
        reg: new RegExp('@pageIndex@', 'ig'),
        value: pageIndex
      })
    }
 
    let _search = ''
    
    if (_dataresource) {
      if (setting.queryType === 'statistics') { // 统计数据源,内容替换
        regoptions.forEach(item => {
          _dataresource = _dataresource.replace(item.reg, item.value)
        })
        if (id) {
          _dataresource = _dataresource + ` where ${setting.primaryKey || 'ID'}='${id}'`
        }
      } else if (!id) {
        _search = Utils.joinMainSearchkey(search)
        if (_search) {
          _search = 'where ' + _search
        }
      } else if (id) {
        _search = Utils.joinMainSearchkey(search)
        _search = `where ${_search ? _search + ' AND ' : ''} ${setting.primaryKey || 'ID'}='${id}'`
      }
    }
 
    if (_customScript) {
      regoptions.forEach(item => {
        _customScript = _customScript.replace(item.reg, item.value)
      })
    }
 
    let LText = ''
    let DateCount = ''
 
    if (_dataresource && setting.laypage && orderBy && !id) {
      LText = ` select top ${pageSize} ${arrFields} from (select ${arrFields} ,ROW_NUMBER() over(order by ${orderBy}) as rows from ${_dataresource} ${_search}) tmptable where rows > ${pageSize * (pageIndex - 1)} order by tmptable.rows `
      DateCount = `select count(1) as total from ${_dataresource} ${_search}`
    } else if (_dataresource && orderBy) {
      LText = ` select ${arrFields} from (select ${arrFields} ,ROW_NUMBER() over(order by ${orderBy}) as rows from ${_dataresource} ${_search}) tmptable order by tmptable.rows `
    } else if (_dataresource) {
      LText = ` select ${arrFields} from ${_dataresource} ${_search}  `
    }
 
    if (_customScript) {
      if (LText) {
        LText = `${LText}
          aaa:
          if @ErrorCode!=''
            insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@ 
        `
      } else {
        _customScript = `${_customScript}
          aaa:
          if @ErrorCode!=''
            insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@ 
        `
      }
    } else {
      LText = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${LText}
      `
    }
 
    // 测试系统打印查询语句
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      _customScript && console.info(`${setting.$name ? `/*${setting.$name} 自定义脚本*/\n` : ''}${LText ? '' : '/*不执行默认sql*/\n'}${_customScript}`)
      LText && console.info(`${setting.$name ? `/*${setting.$name} 数据源*/\n` : ''}` + LText.replace(/\n\s{8}/ig, '\n'))
    }
 
    if (setting.$name) {
      param.menuname = setting.$name
    }
 
    param.custom_script = Utils.formatOptions(_customScript)
    param.LText = Utils.formatOptions(LText)
    param.DateCount = Utils.formatOptions(DateCount)
 
    // 多层结构数据
    // LText = `SELECT a.id as bid,a.ID,a.workerCode,a.workerName,a.jobName,a.Initials,case when isnull(m.friend_id ,'') ='' then '' 
    // when isnull(m.status,0)=10 then '已添加' else '待通过' end as friend_text
    // ,case when images='' then  'http://epc.mk9h.cn/Content/images/upload/img/kane.jpg'  else images end as icon FROM  
    // (select friend_id,status from oa_mail_list where userid='sso202004100959326131C0805998B6745F886F9' and  Initials=case when right('0',1)='0' then Initials else '0'  end 
    // and status=10  and deleted=0) m 
    //  inner join  (select * from BD_workers where 
    //  Initials=case when right('0',1)='0' then Initials else '0' end and deleted=0 ) a
    //  on a.id=m.friend_id `
    // param.custom_script = ''
    // param.LText = Utils.formatOptions(LText)
    // param.DateCount = ''
    // param.prm_field = 'workerCode'
    // param.arr_field = 'workerName,jobName'
    // param.tabid = 'ID'
    // param.parid = 'BID'
    // param.sub_name = 'sub_data'
    // param.sub_field = 'BID,friend_text,icon,Initials'
 
    // exec_type: 'y' 解码字段:LText、LText1、LText2、custom_script、DateCount
 
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt('', param.timestamp)
 
    if (menuType === 'HS') { // 云端数据验证
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
    }
 
    return param
  }
 
  /**
   * @description 获取系统存储过程 sPC_Get_TableData 合计值的参数
   */
  static getStatQueryDataParams (setting, statFields, search, orderBy, BID, menuType) {
    let param = {
      func: 'sPC_Get_TableData',
      obj_name: 'data',
      exec_type: 'y',
      arr_field: statFields.map(col => col.field).join(','),
      default_sql: setting.execute ? 'true' : 'false'
    }
 
    if (setting.transaction === 'true') {
      param.func = 'sPC_Get_TableData_try'
    }
    
    let _dataresource = setting.dataresource
    let _customScript = ''
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
 
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
    
    if (setting.customScript) {
      _customScript = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${setting.customScript}
      `
    }
 
    _dataresource = _dataresource.replace(/@sum\$|\$sum@/ig, '')
    _customScript = _customScript.replace(/@sum\$|\$sum@/ig, '')
    _dataresource = _dataresource.replace(/\$select@/ig, '/*')
    _dataresource = _dataresource.replace(/@select\$/ig, '*/')
    _customScript = _customScript.replace(/\$select@/ig, '/*')
    _customScript = _customScript.replace(/@select\$/ig, '*/')
 
    let regoptions = null
    if (setting.queryType === 'statistics' || _customScript) {
      let allSearch = Utils.getAllSearchOptions(search)
 
      regoptions = allSearch.map(item => {
        return {
          reg: new RegExp('@' + item.key + '@', 'ig'),
          value: `'${item.value}'`
        }
      })
      regoptions.push({
        reg: new RegExp('@orderBy@', 'ig'),
        value: orderBy
      }, {
        reg: new RegExp('@pageSize@', 'ig'),
        value: 999999
      }, {
        reg: new RegExp('@pageIndex@', 'ig'),
        value: 1
      })
    }
 
    let _search = Utils.joinMainSearchkey(search)
    if (_search) {
      _search = 'where ' + _search
    }
    
    if (setting.queryType === 'statistics') { // 统计数据源,内容替换
      regoptions.forEach(item => {
        _dataresource = _dataresource.replace(item.reg, item.value)
      })
      _search = ''
    }
 
    if (_customScript) {
      regoptions.forEach(item => {
        _customScript = _customScript.replace(item.reg, item.value)
      })
    }
 
    let LText = ` select ${statFields.map(col => `isnull(sum(${col.field}),0) as ${col.field}`).join(',')} from ${_dataresource} ${_search} `
 
    if (_customScript) {
      LText = `${LText}
        aaa:
        if @ErrorCode!=''
          insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@ 
      `
    } else {
      LText = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${LText}
      `
    }
 
    // 测试系统打印查询语句
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      _customScript &&  console.info(`${setting.$name ? `/*${setting.$name} 自定义脚本 统计查询*/\n` : ''}${LText ? '' : '/*不执行默认sql*/\n'}${_customScript}`)
      LText &&  console.info(`${setting.$name ? `/*${setting.$name} 数据源 统计查询*/\n` : ''}` + LText.replace(/\n\s{8}/ig, '\n'))
    }
 
    if (setting.$name) {
      param.menuname = setting.$name
    }
    
    param.custom_script = Utils.formatOptions(_customScript)
    param.LText = Utils.formatOptions(LText)
    param.DateCount = ''
 
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt('', param.timestamp)
 
    if (menuType === 'HS') { // 云端数据验证
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
    }
 
    if (BID) {
      param.BID = BID
    }
    
    // 数据管理权限
    if (sessionStorage.getItem('dataM') === 'true') {
      param.dataM = 'Y'
    }
 
    return param
  }
 
  /**
   * @description 数据源名称,用于统一查询
   * @param {Object}   setting      数据源设置
   * @param {String}   arrFields    查询字段
   * @param {Array}    search       搜索条件
   * @param {String}   orderBy      排序方式
   * @param {Number}   pageIndex    页码
   * @param {Number}   pageSize     每页数量
   * @param {String}   BID          上级ID
   * @param {String}   menuType     菜单类型,普通菜单与HS
   * @return {Object}  param
   */
  static getPrevQueryParams (setting, search = [], BID, menuType) {
    let param = null
 
    if (setting.procMode !== 'inner') {
      param = this.getDefaultPrevQueryParam(setting, search, menuType)
    } else {
      param = Utils.formatCustomMainSearch(search)
      param.func = setting.prevFunc || ''
    }
 
    if (BID) {
      param.BID = BID
    }
 
    return param
  }
 
  /**
   * @description 获取系统前置脚本
   */
  static getDefaultPrevQueryParam (setting, search, menuType) {
    let param = {
      func: 'sPC_TableData_InUpDe',
      exec_type: 'y',
      script_type: 'Y'
    }
 
    let sql = ''
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
 
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
 
    setting.preScripts.forEach(item => {
      if (item.status === 'false') return
      sql += `${item.sql}
      `
    })
 
    if (sql) {
      sql = `/*前置脚本*/
        declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${sql}
        aaa:
          if @ErrorCode!=''
            insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@
      `
 
      let allSearch = Utils.getAllSearchOptions(search)
      let regoptions = allSearch.map(item => {
        return {
          reg: new RegExp('@' + item.key + '@', 'ig'),
          value: `'${item.value}'`
        }
      })
      regoptions.push({
        reg: new RegExp('@login_city@', 'ig'),
        value: `'${city}'`
      }, {
        reg: new RegExp('@userName@', 'ig'),
        value: `'${userName}'`
      }, {
        reg: new RegExp('@fullName@', 'ig'),
        value: `'${fullName}'`
      })
 
      regoptions.forEach(item => {
        sql = sql.replace(item.reg, item.value)
      })
 
      // 测试系统打印查询语句
      if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
        console.info(sql.replace(/\n\s{8}/ig, '\n'))
      }
    }
 
    if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
      sql = sql.replace(/\$@/ig, '/*')
      sql = sql.replace(/@\$/ig, '*/')
    } else {
      sql = sql.replace(/@\$|\$@/ig, '')
    }
 
    param.LText = Utils.formatOptions(sql)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt('', param.timestamp)
 
    if (menuType === 'HS') { // 函数 sPC_TableData_InUpDe 云端验证
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
    }
 
    param.menuname = setting.MenuName || ''
 
    return param
  }
 
  /**
   * @description 获取系统回调脚本
   */
  static getCallBackQueryParams (setting, sql, errSql) {
    let param = {
      func: 'sPC_TableData_InUpDe',
      exec_type: 'y',
    }
 
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
 
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
 
    let _prevCustomScript = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
        Select @ErrorCode='',@retmsg='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
        ${errSql}
    `
    let _backCustomScript = `
    `
 
    setting.cbScripts.forEach(script => {
      if (script.status === 'false') return
 
      if (script.position === 'front') {
        _prevCustomScript += `
        /* 自定义脚本 */
        ${script.sql}
        `
      } else {
        _backCustomScript += `
        /* 自定义脚本 */
        ${script.sql}
        `
      }
    })
 
    _backCustomScript += `
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
 
    sql = _prevCustomScript + sql
    sql = sql + _backCustomScript
 
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      console.info(sql.replace(/\n\s{8}/ig, '\n'))
    }
 
    param.LText = sql
    
    if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
      param.LText = param.LText.replace(/\$@/ig, '/*')
      param.LText = param.LText.replace(/@\$/ig, '*/')
    } else {
      param.LText = param.LText.replace(/@\$|\$@/ig, '')
    }
 
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt('', param.timestamp)
    param.LText = Utils.formatOptions(param.LText)
    param.menuname = setting.MenuName || ''
 
    return param
  }
 
  /**
   * @description 获取回调sql
   */
  static getCallBackSql (setting, result) {
    let lines = []
    let pre = setting.callbackType === 'script' ? '@' : ''
 
    let getDefaultSql = (obj, tb, bid, level) => {
      let keys = []
      let vals = []
      let subObjs = []
      let id = Utils.getuuid()
 
      delete obj.$$key
 
      Object.keys(obj).forEach(key => {
        let val = obj[key]
        if (val === null || val === undefined) return
        if (typeof(val) === 'object') {
          if (Array.isArray(val)) {
            val.forEach(item => {
              if (typeof(item) !== 'object' || Array.isArray(item)) return
              if (Object.keys(item).length > 0) {
                item.$$key = tb + '_' + key
                subObjs.push(item)
              }
            })
          } else if (Object.keys(val).length > 0) {
            val.$$key = tb + '_' + key
            subObjs.push(val)
          }
        } else {
          if (typeof(val) === 'string') {
            val = val.replace(/'/ig, '"')
          }
          keys.push(key)
          vals.push(`'${val}'`)
        }
      })
 
      lines.push({
        table: tb,
        insert: `Insert into ${pre}${tb} (${keys.join(',')},mk_level,mk_id,mk_bid)`,
        select: `Select ${vals.join(',')},'${level}','${id}','${bid}'`
      })
 
      subObjs.forEach(item => {
        getDefaultSql(item, item.$$key, id, level + 1)
      })
    }
    
    getDefaultSql(result, setting.cbTable, '', 1)
 
    let lineMap = new Map()
    lines.forEach(line => {
      if (lineMap.has(line.table)) {
        let _line = lineMap.get(line.table)
        _line.selects.push(line.select)
        lineMap.set(line.table, _line)
      } else {
        lineMap.set(line.table, {
          table: line.table,
          insert: line.insert,
          selects: [line.select]
        })
      }
    })
 
    return [...lineMap.values()]
  }
}
 
/**
 * @description 生成单个组件sPC_Get_structured_data请求参数
 */
export function getStructDefaultParam (component, searchlist, first) {
  const { columns, setting, dataName, format } = component
 
  let arr_field = columns.map(col => col.field)
  let _dataresource = setting.dataresource
  let _customScript = setting.customScript
  
  if (setting.queryType === 'statistics' || _customScript) {
    let allSearch = Utils.getAllSearchOptions(searchlist)
    let regoptions = allSearch.map(item => {
      return {
        reg: new RegExp('@' + item.key + '@', 'ig'),
        value: `'${item.value}'`
      }
    })
 
    regoptions.forEach(item => {
      if (_dataresource && setting.queryType === 'statistics') {
        _dataresource = _dataresource.replace(item.reg, item.value)
      }
      _customScript = _customScript.replace(item.reg, item.value)
    })
  }
 
  _dataresource = _dataresource.replace(/@select\$|\$select@/ig, '')
  _customScript = _customScript.replace(/@select\$|\$select@/ig, '')
  _dataresource = _dataresource.replace(/\$sum@/ig, '/*')
  _dataresource = _dataresource.replace(/@sum\$/ig, '*/')
  _customScript = _customScript.replace(/\$sum@/ig, '/*')
  _customScript = _customScript.replace(/@sum\$/ig, '*/')
 
  let _search = ''
  if (setting.queryType !== 'statistics' && _dataresource) {
    _search = Utils.joinMainSearchkey(searchlist)
    _search = _search ? 'where ' + _search : ''
  }
 
  if (setting.order && _dataresource) {
    _dataresource = `select top 1000 ${arr_field.join(',')} from (select ${arr_field.join(',')} ,ROW_NUMBER() over(order by ${setting.order}) as rows from ${_dataresource} ${_search}) tmptable order by tmptable.rows `
  } else if (_dataresource) {
    _dataresource = `select top 1000 ${arr_field.join(',')} from ${_dataresource} ${_search} `
  }
 
  if (first) {
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
  
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
    _customScript = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50)
      select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
      ${_customScript}
    `
  }
 
  // 测试系统打印查询语句
  if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
    _customScript && console.info(`${setting.$name ? `/*${setting.$name} 自定义脚本(同步查询)*/\n` : ''}${_dataresource ? '' : '/*不执行默认sql*/\n'}${_customScript}`)
    _dataresource && console.info(`${setting.$name ? `/*${setting.$name} 数据源(同步查询)*/\n` : ''}` + _dataresource)
  }
 
  return {
    name: dataName,
    columns: columns,
    par_tablename: '',
    type: format === 'array' ? format : '',
    primaryKey: setting.primaryKey || '',
    foreign_key: '',
    sql: _dataresource,
    script: _customScript,
    transaction: setting.transaction === 'true'
  }
}
 
/**
 * @description 生成sPC_Get_structured_data请求参数
 * 1、把大接口sPC_Get_structured_data的ltext拆成三份,第一段:@LText1,第二段@LText,第三段@LText2
 */
export function getStructuredParams (params, config, BID = '') {
  let LText_field = []
  let diffUser = false
  let transaction = false
  
  let _LText = params.map((item, index) => {
    let _script = item.script
 
    if (!diffUser && (/@userid@/ig.test(item.sql) || /@userid@/ig.test(_script))) {
      diffUser = true
    }
    if (item.transaction) {
      transaction = true
    }
 
    item.columns.forEach(cell => {
      LText_field.push(`Select '${item.name}' as tablename,'${cell.field}' as fieldname,'${cell.datatype}' as field_type`)
    })
    return `Select '${item.name}' as tablename,'${window.btoa(window.encodeURIComponent(item.sql))}' as LText,'${window.btoa(window.encodeURIComponent(_script))}' as Lcustomize,'${item.type}' as table_type,'${item.primaryKey}' as primary_key,'${item.par_tablename}' as par_tablename,'${item.foreign_key}' as foreign_key,'${index}' as Sort`
  })
 
  let param = {
    func: 'sPC_Get_structured_data',
    LText: _LText.join(' union all '),
    LText_field: LText_field.join(' union all '),
    BID: BID
  }
 
  if (transaction) {
    param.func = 'sPC_Get_structured_data_try'
  }
 
  let { LText, LText1, LText2 } = Utils.sPCInUpDeFormatOptions(param.LText)
 
  param.LText1 = LText1
  param.LText = LText
  param.LText2 = LText2
  param.LText_field = Utils.formatOptions(param.LText_field)
 
  if (config.cacheUseful === 'true') {
    param.time_type = config.timeUnit
    param.time_limit = config.cacheTime
    if (diffUser) {
      param.userid = sessionStorage.getItem('UserID')
    }
    param.data_md5 = md5(JSON.stringify(param))
  }
 
  param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
  param.secretkey = Utils.encrypt(param.LText, param.timestamp)
 
  return param
}