king
2020-02-05 74f42024805abe7850dbeeb03dae48a0d9ef0b79
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
import moment from 'moment'
import md5 from 'md5'
 
const service = window.GLOB.service ? (/\/$/.test(window.GLOB.service) ? window.GLOB.service : window.GLOB.service + '/') : ''
 
export default class Utils {
  /**
   * @description 生成32位uuid string + 时间
   * @return {String}  uuid
   */
  static getuuid () {
    let uuid = []
    let timestamp = new Date().getTime()
    let options = '0123456789abcdefghigklmnopqrstuv'
    for (let i = 0; i < 19; i++) {
      uuid.push(options.substr(Math.floor(Math.random() * 0x20), 1))
    }
    uuid = timestamp + uuid.join('')
    return uuid
  }
 
  /**
   * @description 生成GUID
   * @return {String}  guid
   */
  static getguid () {
    // 产生一个新的GUID值
    let uuid = []
    let d = new Date()
    let options = '0123456789abcdefghigklmnopqrstuv'
    for (let i = 0; i < 19; i++) {
      uuid.push(options.substr(Math.floor(Math.random() * 0x20), 1))
    }
    uuid = moment().format('YYYYMMDDHHmmss') + d.getMilliseconds() + uuid.join('')
    return uuid.toUpperCase()
  }
 
  /**
   * @description md5加密
   * @return {String}  str         加密串
   * @return {String}  timestamp   时间戳  
   */
  static encrypt (str, timestamp) {
    let salt = 'mingke' // 盐值
    let _str = str + salt + timestamp
    if (_str.length > 8000) {
      _str = _str.slice(_str.length - 8000)
    }
    return md5(_str)
  }
 
  /**
   * @description sql加密
   * @return {String}  value
   */
  static formatOptions (value) {
    if (!value) return ''
 
    let salt = 'minKe' // 盐值
    // 关键字转换规则
    let format = [{
      key: 'select',
      value: ' msltk '
    }, {
      key: 'from',
      value: ' mfrmk '
    }, {
      key: 'where',
      value: ' mwhrk '
    }, {
      key: 'order by',
      value: ' modbk '
    }, {
      key: 'asc',
      value: ' modack '
    }, {
      key: 'desc',
      value: ' moddesk '
    }, {
      key: 'top',
      value: ' mtpk '
    }, {
      key: 'like',
      value: ' mlkk '
    }, {
      key: 'not like',
      value: ' mnlkk '
    }, {
      key: 'between',
      value: ' mbtnk '
    }, {
      key: 'and',
      value: ' madk '
    }, {
      key: 'insert',
      value: ' mistk '
    }, {
      key: 'into',
      value: ' mitk '
    }, {
      key: 'update',
      value: ' muptk '
    }, {
      key: 'delete',
      value: ' mdelk '
    }, {
      key: 'begin',
      value: ' mbgink '
    }, {
      key: 'end',
      value: ' medk '
    }, {
      key: 'if',
      value: ' mefk '
    }, {
      key: 'while',
      value: ' mwilk '
    }, {
      key: 'create',
      value: ' mcrtk '
    }, {
      key: 'alter',
      value: ' matek '
    }, {
      key: 'len',
      value: ' mlnk '
    }, {
      key: 'left',
      value: ' mlftk '
    }, {
      key: 'right',
      value: ' mritk '
    }, {
      key: 'union',
      value: ' munok '
    }, {
      key: 'varchar',
      value: ' mvcrk '
    }, {
      key: 'getdate',
      value: ' mgtdtk '
    }, {
      key: 'TRY',
      value: ' mtryonek '
    }, {
      key: 'TRAN',
      value: ' mtrnk '
    }, {
      key: 'goto',
      value: ' mgtk '
    }, {
      key: 'set',
      value: ' mstk '
    }, {
      key: 'ROLLBACK',
      value: ' mrlbkk '
    }]
 
    // 替换关键字
    format.forEach(item => {
      let reg  =  new RegExp('(^|\\s)' + item.key + '(\\s|$)', 'ig')
      value = value.replace(reg, item.value)
    })
 
    // 1、替换%符(数据库中解析后sql报错),2、去除收尾多余空格
    value = value.replace(/%/ig, 'mpercent')
    value = value.replace(/(^\s|\s$)/ig, '')
 
    // 1、encode编码(中文字符超出base64加密范围),2、base64加密
    value = window.btoa(window.encodeURIComponent(value))
 
    // 插入字符
    let index = Math.floor(value.length / 2)
    value = value.slice(0, index) + salt + value.slice(index)
 
    // base64加密
    value = window.btoa(value)
 
    return value
  }
 
  /**
   * @description 初始化搜索条件
   * @param {Array}   searches     搜索条件
   * @return {String}  searches    格式化后结果
   */
  static initMainSearch (searches) {
    if (!searches || searches.length === 0) return []
 
    let newsearches = []
    searches.forEach(search => {
      let item = {
        key: search.field,
        match: search.match,
        type: search.type,
        value: search.initval
      }
      if (item.type === 'date') {
        item.value = item.value ? moment().subtract(item.value, 'days').format('YYYY-MM-DD') : ''
      } else if (item.type === 'datemonth') {
        item.value = item.value ? moment().subtract(item.value, 'month').format('YYYY-MM') : ''
      } else if (item.type === 'dateweek') {
        item.value = item.value ? [moment().subtract(item.value * 7, 'days').startOf('week').format('YYYY-MM-DD'),
          moment().subtract(item.value * 7, 'days').endOf('week').format('YYYY-MM-DD')] : ''
      } else if (item.type === 'daterange') {
        let _val = item.value
        if (_val) {
          try {
            _val = JSON.parse(_val)
          } catch {
            _val = ''
          }
        }
        item.value = _val ? [moment().subtract(_val[0], 'days').format('YYYY-MM-DD'),
          moment().subtract(_val[1], 'days').format('YYYY-MM-DD')] : ''
      } else if (item.type === 'multiselect') {
        item.value = item.value ? item.value.split(',').filter(Boolean) : []
      }
      newsearches.push(item)
    })
    
    return newsearches
  }
 
  /**
   * @description 初始化搜索条件
   * @param {Array}   searches     搜索条件
   * @return {String}  searches    格式化后结果
   */
  static formatCustomMainSearch (searches) {
    if (!searches || searches.length === 0) return {}
 
    let newsearches = {}
    searches.forEach(item => {
      if (item.type === 'date') {
        let timetail = ''
        let _val = item.value
 
        if (item.match === '<' || item.match === '<=') {
          timetail = ' 00:00:00.000'
          if (_val) {
            _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
          }
        } else if (item.match === '>' || item.match === '>=') {
          timetail = ' 00:00:00.000'
        }
 
        if (newsearches[item.key]) {
          newsearches[item.key + '1'] = _val ? _val + timetail : null
        } else {
          newsearches[item.key] = _val ? _val + timetail : null
        }
      } else if (item.type === 'datemonth') {
        // 月-过滤条件,从月开始至结束
        let _startval = null
        let _endval = null
 
        if (item.value) {
          _startval = moment(item.value, 'YYYY-MM').startOf('month').format('YYYY-MM-DD') + ' 00:00:00.000'
          _endval = moment(item.value, 'YYYY-MM').endOf('month').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        }
        
        newsearches[item.key] = _startval
        newsearches[item.key + '1'] = _endval
      } else if (item.type === 'dateweek') {
        let _endval = ''
        if (item.value) {
          _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
        }
 
        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : null
        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : null
      } else if (item.type === 'daterange') {
        let _endval = ''
        if (item.value) {
          _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
        }
 
        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : null
        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : null
      } else if (item.type === 'text') {
        item.key.split(',').forEach(field => { // 综合搜索,所字段拼接
          newsearches[field] = item.value
        })
      } else if (item.type === 'multiselect') {
        newsearches[item.key] = item.value.join(',')
      } else {
        newsearches[item.key] = item.value
      }
    })
    
    return newsearches
  }
 
  /**
   * @description 拼接搜索条件main
   * @param {Array}   searches     搜索条件
   * @return {String}  searchText  拼接结果
   */
  static joinMainSearchkey (searches) {
    if (!searches || searches.length === 0) return ''
 
    let searchText = ''
    searches.forEach(item => {
      if (!item.value || (item.type === 'multiselect' && item.value.length === 0)) return
      
      searchText += (searchText !== '' ? ' AND ' : '')
      if (item.type === 'text') {
        let str = item.match === '=' ? '' : '%'
        let fields = item.key.split(',').map(field => { // 综合搜索,所字段拼接
          return field + ' ' + item.match + ' \'' + str + item.value + str + '\''
        })
 
        searchText += '(' + fields.join(' OR ') + ')'
      } else if (item.type === 'select') {
        let str = item.match === '=' ? '' : '%'
 
        searchText += item.key + ' ' + item.match + ' \'' + str + item.value + str + '\''
      } else if (item.type === 'multiselect') {
        let str = item.match === '=' ? '' : '%'
        let options = item.value.map(val => {
          return item.key + ' ' + item.match + ' \'' + str + val + str + '\''
        })
 
        searchText += '(' + options.join(' OR ') + ')'
      } else if (item.type === 'date') {
        let _val = item.value
        let timetail = ' 00:00:00.000'
        let _match = item.match
 
        if (item.match === '<' || item.match === '<=') { // 时间为<=时,匹配后一天的0点,匹配方式为<
          _match = '<'
          _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
        } else if (item.match === '=') {
          timetail = ''
        }
 
        searchText += '(' + item.key + ' ' + _match + ' \'' + _val + timetail + '\')'
      } else if (item.type === 'datemonth') { // 月-过滤条件,从月开始至结束,结束时间为月末加一天的0点,方式为<
        let _startval = moment(item.value, 'YYYY-MM').startOf('month').format('YYYY-MM-DD') + ' 00:00:00.000'
        let _endval = moment(item.value, 'YYYY-MM').endOf('month').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
 
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
      } else if (item.type === 'dateweek') { // 周-过滤条件
        let _startval = item.value[0] + ' 00:00:00.000'
        let _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
 
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
      } else if (item.type === 'daterange') {
        let _startval = item.value[0] + ' 00:00:00.000'
        let _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
 
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
      } else {
        searchText += '(' + item.key + ' ' + item.match + ' \'' + item.value + '\')'
      }
    })
    return searchText
  }
 
  /**
   * @description 拼接搜索条件datamanage
   * @param {Array}   searches     搜索条件
   * @return {String}  searchText  拼接结果
   */
  static jointsearchkey (searches) {
    if (!searches || searches.length === 0) return ''
    let searchText = ''
    searches.forEach(item => {
      if (!item.value) return
      searchText += (searchText !== '' ? ' AND ' : '')
      if (item.type === 'text') {
        let options = item.key.split(',').map(op => {
          // equal时不添加%
          let str = item.op === 'equal' ? '' : '%'
          return op + ' ' + item.op + ' \'' + str + item.value + str + '\''
        })
        searchText += '(' + options.join(' OR ') + ')'
      } else if (item.type === 'date') {
        searchText += '(' + item.key + ' ' + item.op + ' \'' + item.value + '\')'
      } else {
        searchText += '(' + item.key + ' ' + item.op + ' \'' + item.value + '\')'
      }
    })
    return searchText
  }
 
  /**
   * @description 获取图片真实路径
   * @return {String}    url 图片路径
   */
  static getrealurl (url) {
    if (!url) return ''
    let baseurl = ''
    if (process.env.NODE_ENV === 'production') {
      baseurl = document.location.origin + '/' + service
    } else {
      baseurl = 'http://qingqiumarket.cn/' + service
    }
    // if (!/Content\/images\/upload\//.test(url)) {
    //   baseurl = baseurl + 'Content/images/upload/'
    // }
    let realurl = url.match(/^http/) || url.match(/^\/\//) ? url : baseurl + url
    return realurl
  }
 
  /**
   * @description 获取下拉搜索查询条件
   * @return {String} item   搜索条件信息
   */
  static getSelectQueryOptions (item) {
    let arrfield = [item.valueField, item.valueText]
 
    if (item.type === 'link') {
      arrfield.push(item.linkField)
    } else if (item.type === 'select' && item.linkSubField && item.linkSubField.length > 0) {
      arrfield.push(...item.linkSubField)
    }
 
    arrfield = Array.from(new Set(arrfield))
 
    let _datasource = item.dataSource
    let sql = ''
 
    if (/\s/.test(_datasource)) { // 拼接别名
      _datasource = '(' + _datasource + ') tb'
    }
 
    arrfield = arrfield.join(',')
 
    if (item.orderBy) {
      sql = 'select distinct ' + arrfield + ',' + item.orderBy + ' as orderfield from ' + _datasource + ' order by orderfield ' + item.orderType
    } else {
      sql = 'select distinct ' + arrfield + ' from ' + _datasource
    }
 
    return {
      sql: sql,
      field: arrfield
    }
  }
 
  /**
   * @description 使用系统函数时(sPC_TableData_InUpDe ),生成sql语句
   * @return {String} type   执行类型
   * @return {String} table  表名
   */
  static getSysDefaultSql (btn, setting, formdata, param, data, logcolumns) {
    let primaryId = param.ID
    let BID = param.BID
    let verify = btn.verify
    let _formFieldValue = {}
 
    // 需要声明的变量集
    let _vars = ['tbid', 'ErrorCode', 'retmsg', 'BillCode', 'BVoucher', 'FIBVoucherDate', 'FiYear', 'UserName', 'FullName']
 
    // 主键字段
    let primaryKey = setting.primaryKey || 'id'
 
    // 系统变量声明与设置初始值
    let _sql = `Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50)
      `
 
    // 获取字段键值对
    if (formdata) {
      formdata.forEach(form => {
        _formFieldValue[form.key] = form.value
      })
    }
 
    // 去除禁用的验证
    if (verify) {
      if (verify.uniques) {
        verify.uniques = verify.uniques.filter(item => item.status !== 'false')
      }
      if (verify.customverifys) {
        verify.customverifys = verify.customverifys.filter(item => item.status !== 'false')
      }
      if (verify.billcodes) {
        verify.billcodes = verify.billcodes.filter(item => item.status !== 'false')
      }
      if (verify.scripts) {
        verify.scripts = verify.scripts.filter(item => item.status !== 'false')
      }
    }
 
    // 设置有自定义脚本时,声明变量中添加所有表单字段,并避免重复
    if (verify && verify.scripts && verify.scripts.length > 0 && formdata && formdata.length > 0) {
      let _initfields = []
      let _formfields = formdata.filter(form => {
        _initfields.push(`@${form.key}='${form.value}'`)
 
        return !_vars.includes(form.key)
      })
 
      _formfields = _formfields.map(form => {
        _vars.push(form.key)
        return `@${form.key} nvarchar(50)`
      })
      _formfields = _formfields.join(',')
      _sql += `,${_formfields}
        `
      _initfields = _initfields.join(',')
      _sql += `select ${_initfields}
        `
 
    }
 
    // 初始化凭证字段
    _sql += `select @BVoucher='',@FIBVoucherDate='',@FiYear=''
      `
 
    // 启用账期验证
    if (verify && verify.accountdate === 'true') {
      _sql += `exec s_FIBVoucherDateCheck @ErrorCode=@ErrorCode OUTPUT,@retmsg=@retmsg OUTPUT
        if @ErrorCode!=''
          GOTO aaa
        `
    }
 
    // 失效验证,添加数据时不用
    if (btn.sqlType !== 'insert' && verify && verify.invalid === 'true' && setting.dataresource) {
      let datasource = setting.dataresource
      if (/\s/.test(datasource)) { // 拼接别名
        datasource = '(' + datasource + ') tb'
      }
 
      _sql += `select @tbid='', @ErrorCode='',@retmsg=''
        select @tbid=${primaryKey} from ${datasource} where ${primaryKey} ='${primaryId}'
        If @tbid=''
        Begin
          select @ErrorCode='E',@retmsg='数据已失效'
          goto aaa
        end
        `
    }
 
    // 唯一性验证,必须存在表单(表单存在时,主键均为单值),必须填写数据源
    if (formdata && verify && verify.uniques.length > 0) {
      let _primaryId = primaryId
      if (btn.sqlType === 'insert') {
        _primaryId = ''
      }
 
      verify.uniques.forEach(item => {
        let _fieldValue = []                     // 表单键值对field=value
        let _value = []                          // 表单值,用于错误提示
        let _labels = item.fieldlabel.split(',') // 表单提示文字
 
        item.field.split(',').forEach((_field, index) => {
          _fieldValue.push(`${_field}='${_formFieldValue[_field]}'`)
          _value.push(`${_labels[index] || ''}:${_formFieldValue[_field] || ''}`)
        })
 
        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
          select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')} and ${primaryKey} !='${_primaryId}'
          If @tbid!=''
          Begin
            select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 已存在'
            goto aaa
          end
          `
      })
    }
    
    // 自定义验证,使用列表及表单数据(表单优先),替换所有@相同字段、@ID、@BID
    if (verify && verify.customverifys.length > 0) {
      let _primaryId = primaryId
      if (btn.sqlType === 'insert') {
        _primaryId = ''
      }
 
      verify.customverifys.forEach(item => {
        let _cuSql = item.sql
        if (data) {
          _formFieldValue = {...data, ..._formFieldValue}
        }
        let keys = Object.keys(_formFieldValue)
        keys = keys.sort((a, b) => {
          return b.length - a.length
        })
 
        keys.forEach(key => {
          let reg = new RegExp('@' + key, 'ig')
          _cuSql = _cuSql.replace(reg, `'${_formFieldValue[key]}'`)
        })
        let idreg = new RegExp('@ID', 'ig')
        _cuSql = _cuSql.replace(idreg, `'${_primaryId}'`)
 
        let bidreg = new RegExp('@BID', 'ig')
        _cuSql = _cuSql.replace(bidreg, `'${BID}'`)
 
        _sql += `select @tbid='', @ErrorCode='',@retmsg=''
          select top 1 @tbid='X' from (${_cuSql}) a
          If @tbid ${item.result === 'true' ? '!=' : '='}''
          Begin
            select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
            goto aaa
          end
          `
      })
    }
 
    // 单号生成,使用上级id(BID)或列表数据,声明变量(检验)
    if (verify && verify.billcodes.length > 0) {
      verify.billcodes.forEach(item => {
        let _ModularDetailCode = ''
        if (item.TypeCharOne === 'Lp' || item.TypeCharOne === 'BN') {
          let _val = ''
          if (item.linkField === 'BID' && BID) { // 替换bid
            _val = BID
          } else if (data && data.hasOwnProperty(item.linkField)) {
            _val = data[item.linkField]
          }
          _ModularDetailCode = item.TypeCharOne + _val
        } else {
          _ModularDetailCode = item.ModularDetailCode
        }
 
        let _declare = ''
        if (!_vars.includes(item.field)) {
          _declare = `Declare @${item.field} nvarchar(50)`
        }
        _vars.push(item.field)
 
        _sql += `${_declare}
          select @BillCode='', @${item.field}=''
          exec s_get_BillCode
            @ModularDetailCode='${_ModularDetailCode}',
            @Type=${item.Type},
            @TypeCharOne='${item.TypeCharOne}',
            @TypeCharTwo ='${item.TypeCharTwo}',
            @BillCode =@BillCode output,
            @ErrorCode =@ErrorCode output, 
            @retmsg=@retmsg output
          if @ErrorCode!=''
            goto aaa
          set @${item.field}=@BillCode
          `
      })
    }
 
    let _updateconfig = ''
 
    // 凭证-显示列中选取,必须选行
    if (verify && verify.voucher && verify.voucher.enabled && data) {
      let _voucher = verify.voucher
 
      _updateconfig = ',BVoucher=@BVoucher,FIBVoucherDate=@FIBVoucherDate,FiYear=@FiYear'
 
      _sql += `exec s_BVoucher_Create
          @Bill ='${data[_voucher.linkField]}',
          @BVoucherType ='${_voucher.BVoucherType}',
          @VoucherTypeOne ='${_voucher.VoucherTypeOne}',
          @VoucherTypeTwo ='${_voucher.VoucherTypeTwo}',
          @Type =${_voucher.Type},
          @BVoucher =@BVoucher OUTPUT ,
          @FIBVoucherDate =@FIBVoucherDate OUTPUT ,
          @FiYear =@FiYear OUTPUT ,
          @ErrorCode =@ErrorCode OUTPUT, 
          @retmsg=@retmsg OUTPUT
        if @ErrorCode!=''
          GOTO aaa
        `
    }
 
    // 用于取用户信息
    let _user = `select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
      `
 
    // 添加、修改、逻辑删除、物理删除
    if (btn.OpenType === 'pop' && btn.sqlType === 'insert') {
      let keys = []
      let values = []
      formdata.forEach(item => {
        if (item.type === 'funcvar') {
          keys.push(item.key)
          values.push('@' + item.key)
        } else if (item.type === 'number') {
          keys.push(item.key)
          values.push(item.value)
        } else {
          keys.push(item.key)
          values.push('\'' + item.value + '\'')
        }
      })
 
      keys = keys.join(',')
      values = values.join(',')
      _sql += _user
      _sql += `insert into ${btn.sql} (${keys},createuserid,CreateUser,CreateStaff,BID) select ${values},@userid,@username,@fullname,@BID;`
    } else if (btn.OpenType === 'pop' && btn.sqlType === 'update') {
      let _form = []
      formdata.forEach(item => {
        if (item.type === 'funcvar') {
          _form.push(item.key + '=@' + item.key)
        } else if (item.type === 'number') {
          _form.push(item.key + '=' + item.value)
        } else {
          _form.push(item.key + '=\'' + item.value + '\'')
        }
      })
      _form = _form.join(',')
      _sql += `update ${btn.sql} set ${_form},modifydate=getdate(),modifyuserid=@userid${_updateconfig} where ${primaryKey}=@${primaryKey};`
    } else if ((btn.OpenType === 'prompt' || btn.OpenType === 'exec') && btn.sqlType === 'LogicDelete') { // 逻辑删除
      _sql += `update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid where ${primaryKey}=@${primaryKey};`
    } else if ((btn.OpenType === 'prompt' || btn.OpenType === 'exec') && btn.sqlType === 'delete') {      // 物理删除
      let _msg = ''
      if (data && logcolumns && logcolumns.length > 0) {
        logcolumns.forEach(col => {
          _msg += col.label + '=' + data[col.field] + ','
        })
      }
      _sql += _user
      _sql += `insert into snote (remark,createuserid,CreateUser,CreateStaff) select '删除表:${btn.sql} 数据: ${_msg}${primaryKey}='+@${primaryKey},@userid,@username,@fullname delete ${btn.sql} where ${primaryKey}=@${primaryKey};`
    }
 
    // 拼接自定义脚本
    if (verify && verify.scripts && verify.scripts.length > 0) {
      let _scripts = ''
      verify.scripts.forEach(item => {
        _scripts += `
        ${item.sql}`
      })
      _sql += `${_scripts}`
    }
 
    _sql += `
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
    console.log(_sql)
    return _sql
  }
 
  /**
   * @description 删除存储过程sql
   * @return {String} name 存储过程名称
   */
  static dropfunc (name) {
    return `IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('${name}') AND type in (N'P', N'PC'))  mdrpk PROCEDURE ${name}`
  }
 
  /**
   * @description 创建页面存储过程
   * @return {String}
   */
  static getTableFunc (param, menu, config) {
    let form = ''
    let formParam = ''
    let _columns = []
    let primaryKey = config.setting.primaryKey || 'ID'
 
    if (config.search && config.search.length > 0) {
      let _fields = new Map()
      config.search.forEach(item => {
        if (item.field) {
          let type = ''
          let _f = item.field
 
          if (item.type.match(/date/ig)) {
            type = 'datetime=null'
          } else {
            type = 'nvarchar(50)=\'\''
          }
 
          if (_fields.has(item.field)) {
            _f = _f + '1'
          }
 
          _fields.set(item.field, true)
          formParam = formParam + `mchr13k@${_f} ${type},`
        }
      })
    }
 
    if (config.columns && config.columns.length > 0) {
      config.columns.forEach(item => {
        if (item.field) {
          _columns.push(`${item.field} as ${item.label}`)
        }
      })
 
      form = `
        declare @dc table (${_columns.join(',')})
        
        @tableid ='${menu.MenuID}'
      `
    }
 
    let Ltext = `create proc ${param.innerFunc}
    ( /*${menu.MenuName}*/
    @BID nvarchar(50)='',
    @${primaryKey} nvarchar(50)='',${formParam}
    @PageIndex nvarchar(50)='',
    @PageSize nvarchar(50)='',
    @OrderCol nvarchar(50)='',
    @OrderType nvarchar(50)='',
    @exceltype nvarchar(50)='',
    @sEPTMenuNo nvarchar(50)='${menu.MenuNo}',
    @lang nvarchar(50)='',
    @debug nvarchar(50)='',
    @LoginUID nvarchar(50)='',
    @SessionUid nvarchar(50)='',
    @UserID nvarchar(50),
    @ErrorCode nvarchar(50) out,
    @retmsg nvarchar(4000) out
    )
    as
    begin
    declare  @BegindateTest datetime,@EnddateTest datetime
    select  @BegindateTest=getdate()
    set @ErrorCode=''
    set @retmsg=''
    BEGIN TRY
      /*事务操作*/
      BEGIN TRAN
        /*具体业务操作*/
        
        /* 
        select top 10 * from sProcExcep order by id desc
        
        declare @UserName  nvarchar(50),@FullName nvarchar(50)
        
        select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
        ${form}
        if 1=2
        begin
          set @ErrorCode='E'
          set @retmsg='在此写报错'
          goto GOTO_RETURN
        end
        
        insert into sNote (remark,createuserid,CreateUser,CreateStaff)
        select '在此写日志',@UserID,@UserName,@FullName
        */
        
      COMMIT TRAN
      SET NOCOUNT ON
      RETURN
    END TRY
    BEGIN CATCH
      /*错误处理*/
      ROLLBACK TRAN
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
      
      /*把自定义的友好的错误信息提示加上*/
      set @ErrorCode=cast(ERROR_NUMBER() as nvarchar(50))
      SET @retmsg=ERROR_MESSAGE();
      SELECT @ErrorMessage=ERROR_MESSAGE(),
        @ErrorSeverity=ERROR_SEVERITY(),
        @ErrorState=ERROR_STATE();
        
      RAISERROR(@ErrorMessage, /*-- Message text.*/
        @ErrorSeverity, /*-- Severity.*/
        @ErrorState  /*-- State.*/
      );
    END CATCH
    
    GOTO_RETURN:
      ROLLBACK TRAN
      
    END`
 
    Ltext = Ltext.replace(/\n\s{4}/ig, 'mchr13k')
 
    return Ltext
  }
 
  /**
   * @description 创建存储过程
   * @return {String}
   */
  static getfunc (param, btn, menu, config) {
    let form = ''
    let formParam = ''
    let columns = config.columns
    let primaryKey = config.setting.primaryKey || 'ID'
 
    if (param.fields && param.fields.length > 0) {
      let _fields = []
      param.fields.forEach(item => {
        if (item.field) {
          let type = ''
          if (item.type.match(/date/ig)) {
            type = 'datetime=null'
          } else if (item.type === 'number') {
            type = `decimal(18,${item.decimal})=0`
          } else {
            type = 'nvarchar(50)=\'\''
          }
          formParam = formParam + `mchr13k@${item.field} ${type},`
 
          _fields.push(item.field)
        }
      })
 
      let field1 = _fields.join(',')
      let field2 = _fields.join(',@')
      let field3 = _fields.map(cell => {
        return cell + '=@' + cell
      })
 
      field2 = field2 ? '@' + field2 : ''
      field3 = field3.join(',')
 
      form = `
        insert into ${param.name} (${field1},createuserid) select ${field2},@UserID
        
        update ${param.name} set ${field3},modifydate=getdate(),modifyuserid=@UserID
      `
    }
 
    if (columns) {
      let _col = []
      let _field = []
      columns.forEach(col => {
        if (col.field) {
          if (col.type === 'number') {
            _col.push(col.field + ' decimal(18,2)')
          } else {
            _col.push(col.field + ' nvarchar(50)')
          }
          _field.push(col.field)
        }
      })
      _col = _col.join(',')
      _field = _field.join(',')
 
      form = form + `
        declare @dc table (${_col})
        
        insert into @dc (${_field})
 
        @tableid ='${menu.MenuID}'
      `
    }
 
    let Ltext = `create proc ${param.funcName}
    ( /*${menu.MenuName}  ${btn.label}*/
    @BID nvarchar(50)='',
    @${primaryKey} nvarchar(50)='',${formParam}
    @sEPTMenuNo nvarchar(50)='${param.menuNo}',
    @lang nvarchar(50)='',
    @debug nvarchar(50)='',
    @LoginUID nvarchar(50)='',
    @SessionUid nvarchar(50)='',
    @UserID nvarchar(50),
    @ErrorCode nvarchar(50) out,
    @retmsg nvarchar(4000) out
    )
    as
    begin
    declare  @BegindateTest datetime,@EnddateTest datetime
    select  @BegindateTest=getdate()
    set @ErrorCode=''
    set @retmsg=''
    BEGIN TRY
      /*事务操作*/
      BEGIN TRAN
        /*具体业务操作*/
        
        /* 
        select top 10 * from sProcExcep order by id desc
        
        declare @UserName  nvarchar(50),@FullName nvarchar(50)
        
        select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
        ${form}
        if 1=2
        begin
          set @ErrorCode='E'
          set @retmsg='在此写报错'
          goto GOTO_RETURN
        end
        
        insert into sNote (remark,createuserid,CreateUser,CreateStaff)
        select '在此写日志',@UserID,@UserName,@FullName
        */
        
      COMMIT TRAN
      SET NOCOUNT ON
      RETURN
    END TRY
    BEGIN CATCH
      /*错误处理*/
      ROLLBACK TRAN
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
      
      /*把自定义的友好的错误信息提示加上*/
      set @ErrorCode=cast(ERROR_NUMBER() as nvarchar(50))
      SET @retmsg=ERROR_MESSAGE();
      SELECT @ErrorMessage=ERROR_MESSAGE(),
        @ErrorSeverity=ERROR_SEVERITY(),
        @ErrorState=ERROR_STATE();
        
      RAISERROR(@ErrorMessage, /*-- Message text.*/
        @ErrorSeverity, /*-- Severity.*/
        @ErrorState  /*-- State.*/
      );
    END CATCH
    
    GOTO_RETURN:
      ROLLBACK TRAN
      
    END`
 
    Ltext = Ltext.replace(/\n\s{4}/ig, 'mchr13k')
 
    return Ltext
  }
}