utils.js
38.9 KB
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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
/*
* 打开先项卡 isView:强制刷新 ,callback:回调函数
*/
function showTabUtils(node,r,fn) {
var isView=false;
var callback;
for (var i = 1; i < arguments.length; i++) {
if (typeof (arguments[i]) == "boolean") {
isView = arguments[i];
} else if (typeof (arguments[i]) == "function") {
callback = arguments[i];
}
}
if (node.url) {
var layout = $(document.body).children(".rs-base").children(".rs-layout");
var center = layout.layout("panel", "center");
var tabs=center.children(".tabs-container");
var list = tabs.tabs("tabs");
var isFind = false;
for (var i = 0; i < list.length; i++) {
if (list[i].panel("options").title == node.text) {
tabs.tabs("select", i);
isFind = true;
if(isView){
var index=tabs.tabs("getTabIndex",list[i]);
tabs.tabs("close",index);
isFind=false;
// list[i].panel('options').tabParams=node;
// list[i].panel("refresh",changeUrl(node.url));
}
break;
}
}
if (!isFind) {
tabs.tabs("add", {
title : node.text,
closable : true,
href : changeUrl(node.url),
tabParams : node,
// onResize:function(width, height){
// $(this).triggerHandler("_resize");
// },
callback:callback
});
}
}
function changeUrl(){
var frame=node.url.length>8&&node.url.substr(0,9)=="iframe://";
if(frame){
node.url=(node.url+(node.url.indexOf('?')>0?'&':'?')+'platid='+global.platId+'&pltid='+global.platTypeId)
}
var url=frame?("./iframe?url="+node.url.substr(9)):node.url;
return url;
}
}
/*得到选中面板*/
function getSelectedPanel(){
return $(document.body).children(".rs-base").children(".rs-layout").layout("panel", "center").children(".tabs-container").tabs("getSelected");
}
/*关闭当前选中tab*/
function closeSelectedPanel(fn) {
if(fn){
fn();
}
var layout = $(document.body).children(".rs-base").children(".rs-layout");
var center = layout.layout("panel", "center");
var tabs=center.children(".tabs-container");
var selectedTab =tabs.tabs('getSelected');
var options=selectedTab.panel("options");
var index = tabs.tabs("getTabIndex", selectedTab);
tabs.tabs("close", index);
if(options.callback){
options.callback.call(this);
}
}
function panelRefreshUtils(){
getSelectedPanel().panel("refresh");
}
function menuReloadUtils(id){
var layout = $(document.body).children(".rs-base").children(".rs-layout");
var menu=layout.children(".rs-menu");
var roots=menu.tree("getRoots");
for (var i =(roots.length-1); i >=0 ; i--) {
menu.tree("remove",roots[i].target);
}
menuLoad('./menu/select.json?parent='+id);
}
function getAuthzUtils(code){
var t;
for (var i = 0; i < authz.length; i++) {
if(authz[i].code==code){
return authz[i];
}
}
return t;
}
/* 判断按钮或操作是否有权限 */
function checkAuthzUtils(menuCode,menuActionCode){
var check=false;
var cAuthz=getAuthzUtils(menuCode);
if(!menuActionCode){
check=true;
}else if(menuActionCode&&cAuthz&&cAuthz.actions){
for (var i = 0; i < cAuthz.actions.length; i++) {
var t=cAuthz.actions[i];
if(t.code==menuActionCode){
check=true;
break;
}
}
}
return check;
}
function getCondObjectValue(id){
var body=$(document.body);
var condobject=body.children(".window").children("#"+id);
return condobject.length==0?{}:condobject.rs_condobject("getValue");
}
function showCondObject(options,callback){
var body=$(document.body);
var opts=$.extend({},{
path:'./query/',
closed:true,
disableSelect:false, /*返回类型 false值类型,true表达式 */
singleSelect:true, /*是否支持多选*/
showGrid:false, /*是否显示表格*/
condHidden:null, /*查询条件隐藏列*/
refresh:false, /*是否刷新 */
refCascade:false, /*引用查询 去除 变量默认值 该参数只能添加到url中 如 : uuid.json?refCascade=true*/
// gridHeight:200 /*表格高度*/
// onCascade:{
// "81d2b9f9-1ead-48d0-9eb7-601d780c1673":{
// change:function(newValue,oldValue){
// return "d258dc6a-8fa0-4501-961e-48fe1230e3ff"; /*指定取field id的值*/
// }
// },
// "d258dc6a-8fa0-4501-961e-48fe1230e3ff":{
// fields:function(params,node){
// return "81d2b9f9-1ead-48d0-9eb7-601d780c1673"; /*指定取field id的值*/
// },
// beforeLoad:function(params,node){
// if(params["018adf52-4b2e-47ea-b1b5-60250889e448"]){
// params["c2139911-0d31-4886-b6b8-fa9a84ea9b7d"]=params["018adf52-4b2e-47ea-b1b5-60250889e448"];
// params["c2139911-0d31-4886-b6b8-fa9a84ea9b7d-exp"]=params["018adf52-4b2e-47ea-b1b5-60250889e448-exp"];
// }else{
// params["c2139911-0d31-4886-b6b8-fa9a84ea9b7d"]="0";
// params["c2139911-0d31-4886-b6b8-fa9a84ea9b7d-exp"]="in";
// }
// }
// }
// },
onBeforeLoad:function(params){return params;}
},typeof options == 'string'?{id:options}:options);
var condobject=body.children(".window").children("#"+opts.id);
if(condobject.length==0){
opts.data=opts.id;
opts.onConfirm=callback;
condobject=$('<div></div>').rs_condobject(opts);
show();
}else{
show();
condobject.rs_condobject("options").onConfirm=callback;
condobject.rs_condobject("reload",opts);
}
function show(){
condobject.dialog("open");
}
}
function showTreeObject(options,callback){
var body=$(document.body);
var opts=$.extend({},{
path:'./query/'
// width:500,
// height:400,
// closed:false,
// singleSelect:true, /*是否支持多选*/
// condHidden:null, /*查询条件隐藏列*/
// refresh:false, /*刷新*/
// idField:null, /*编号列*/
// nameField:null, /*名称列*/
// parentField:null, /*上级列过滤*/
// parentDefval:null, /*上级列默认值*/
// filterField:null, /*过滤列编号*/
// showColumns:[], /*显示通用查询的列*/
// cascade:true, /*级联加载*/
// expandLevel:null, /*展开层级*/
// formatter:function(node){},
// onBeforeLoad:function(node,params){return params;},
// onConfirm:function(params,rowCount){}
},options);
var treeobject=body.children(".window").children("#"+'tree-'+opts.id);
if(treeobject.length==0){
opts.data=opts.id;
opts.onConfirm=callback;
treeobject=$('<div></div>').rs_treeobject(opts);
show();
}else{
show();
treeobject.rs_treeobject("reload",opts);
treeobject.rs_treeobject("options").onConfirm=callback;
}
function show(){
treeobject.dialog("open");
}
}
function maxlengthUtils(control,maxlength){
var span=control.next(".textbox");
var textbox=span.find(".textbox-text");
textbox.attr("maxlength",maxlength);
}
function readonlyUtils(control,callback){
var span=control.next(".textbox");
var textbox=span.find(".textbox-text");
textbox.addClass("ime-disable").attr("autocomplete","off");
textbox.bind("focus",function(e){
var obj=$(this);
obj.attr("ime-options",obj.val());
}).bind("_clear",function(){
var obj=$(this);
if(obj.val()!=""){
obj.val(obj.attr("ime-options"));
}else{
obj.val("");
}
}).bind("keydown",{control:control},function(e){
var obj=$(this);
var c=e.data.control;
if(e.keyCode==8||e.keyCode==46){
obj.attr("ime-options","");
if(c.hasClass("searchbox-f")){
c.searchbox("clear");
if(callback&&(typeof (callback) == "function")){
callback.call(c[0]);
}
}else{
c.textbox("clear");
}
}
setTimeout(function(){
obj.triggerHandler("_clear");
},100);
if (e&&e.stopPropagation){
e.stopPropagation();
}else{
window.event.cancelBubble = true;
}
return false;
});
}
/**
* 只读但可以删除
*/
function readonlyUtils_cascade(control_1, control_2) {
control_1.bind("keydown", function(e) {
if (e.keyCode == 8 || e.keyCode == 46) {
control_1.val('');
if(!isNull(control_2)){
control_2.val('');
}
}
return false;
});
}
/*检验返回格式*/
function responseUtils(result) {
var success=false;
var data=(typeof result == 'string')?eval('(' + result + ')'):result;
if(data.status){
success=data && data.status == "success";
if (!success) {
$.messager.alert(resource.msg_title,resourceUtils(data.message));
}
}
if(data.token&&data.token.length==36){
$.cookie('rs-token',data.token);
}
return success;
}
function paramsAppendUtils(params){
params["_rs-token"]=token;
return params;
}
/*加载过滤 */
function loadFilterUtils(data,format){
var val;
var success=responseUtils(data);
var control=$(this);
var cls=control.attr("class");
if(format && typeof (format) == "function"){
format.call(this, data.list);
}
if(cls.indexOf("datagrid")>-1){
return success?{rows:data.list,total:data.total}:{rows:[],total:0};
}else if(cls.indexOf("tree")>-1){//tree
return $.isArray(data)?data[0].list:data.list;
}else{
return data.list;
}
}
/*资源获取*/
function resourceUtils(message){
var rev=message;
var i=message.lastIndexOf('.');
if(i>0){
var t=message.replace(new RegExp(/(\.)/g),'_');
var b=resource[t.substr(0,i)];
if(b&&b[t.substr(i+1)]){
rev=b[t.substr(i+1)];
}
}
return rev;
}
$.extend($.fn.tree.defaults,{
loadFilter: loadFilterUtils,
animate: true,
lines: true,
checkbox: true,
cascadeCheck: true
});
/*默认window选项*/
$.extend($.fn.window.defaults, {
modal:true,
closed:true,
collapsible:false,
minimizable:false,
maximizable:false,
/*draggable:false,*/
resizable:false
});
$.extend($.fn.combobox.defaults, {
// loadFilter: loadFilterUtils,
panelHeight:'auto',
panelMaxHeight:300,
editable: false
});
/*默认dialog选项*/
$.extend($.fn.dialog.defaults, {
modal:true/*,
draggable:false*/
});
/*默认pagination*/
$.extend($.fn.pagination.defaults, {
showRefresh:false
});
/*默认datagrid*/
$.extend($.fn.datagrid.defaults, {
fit:true,
rownumbers:true,
singleSelect:true,
striped:true,
pageList:[20,50,100],
pageSize:20,
pagination:true,
loadFilter: loadFilterUtils
});
$.extend($.fn.datagrid.methods, {
editCell: function(jq,param){
return jq.each(function(){
var opts = $(this).datagrid('options');
var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
for(var i=0; i<fields.length; i++){
var col = $(this).datagrid('getColumnOption', fields[i]);
col.editor1 = col.editor;
if (fields[i] != param.field){
col.editor = null;
}
}
$(this).datagrid('beginEdit', param.index);
var ed = $(this).datagrid('getEditor', param);
if (ed){
if ($(ed.target).hasClass('textbox-f')){
$(ed.target).textbox('textbox').focus();
} else {
$(ed.target).focus();
}
}
for(var i=0; i<fields.length; i++){
var col = $(this).datagrid('getColumnOption', fields[i]);
col.editor = col.editor1;
}
});
},
enableCellEditing: function(jq){
return jq.each(function(){
var dg = $(this);
var opts = dg.datagrid('options');
opts.oldOnClickCell = opts.onClickCell;
opts.onClickCell = function(index, field){
if (opts.editIndex != undefined){
if (dg.datagrid('validateRow', opts.editIndex)){
dg.datagrid('endEdit', opts.editIndex);
opts.editIndex = undefined;
} else {
return;
}
}
dg.datagrid('selectRow', index).datagrid('editCell', {
index: index,
field: field
});
opts.editIndex = index;
opts.oldOnClickCell.call(this, index, field);
}
});
}
});
$.extend($.fn.datagrid.defaults.editors, {
condition: {
init: function(container, options){
// 行数
var rowIndex=parseInt(container.closest(".datagrid-row").attr("datagrid-row-index"));
// 列名
var field=container.closest("td[field]").attr("field");
// 获取回传的值
var grid = options.getGrid();
var usdType;// 1:CRM帐套 2:微信公众号
var usdStatus;// 1: 可见范围的条件 2:可编辑范围
var opts={
showGrid:true,
singleSelect:false,
refresh:true
};
if(rowIndex == '0' && field== 'edit'){// CRM可编辑范围
opts.id='1b8accf2-36d5-11e6-a09d-6c626db0ae88';
usdType = 1;
usdStatus = 2;
} else if(rowIndex=='1' && field =='edit'){// 顾客移动平台可编辑范围
opts.id='4f9f35dd-3748-11e6-a09d-6c626db0ae88';
usdType = 2;
usdStatus = 2;
} else if(rowIndex=='0' && field== 'view'){// CRM账套见范围
opts.id='1b8accf2-36d5-11e6-a09d-6c626db0ae88';
usdType = 1;
usdStatus = 1;
} else if(rowIndex =='1' && field == 'view'){// 顾客移动平台可见范围
opts.id='4f9f35dd-3748-11e6-a09d-6c626db0ae88';
usdType = 2;
usdStatus = 1;
}
var input = $('<input class="datagrid-editable-input"/>').appendTo(container);
input.searchbox({
rowIndex:rowIndex,
prompt:'不限',
searcher:function(){
var index=$(this).searchbox("options").rowIndex;
showCondObject(opts,function(rows){
var extIds = "";
var name = "";
if(usdType == 1){
for (var i = 0; i < rows.length; i++) {
extIds += rows[i].ACT_ID + ",";
name += rows[i].ACT_NAME + ",";
}
} else if (usdType == 2){
for (var i = 0; i < rows.length; i++) {
extIds += rows[i].GZH_ID + ",";
name += rows[i].NICK_NAME + ",";
}
}
name = name.substring(0, name.length - 1);
extIds = extIds.substring(0, extIds.length - 1);
var now = grid.datagrid('getData').rows;
var row = now[index];
if(usdStatus == 1){// 可见
row.view = name;
row.viewIds = extIds;
} else if (usdStatus == 2){// 可编辑
row.edit = name;
row.editIds = extIds;
}
grid.datagrid('updateRow',{
index: index,
row: row
});
});
}
});
return input;
},
getValue: function(target){
// 行数
var rowIndex=$(target).searchbox("options").rowIndex;
// 列名
var field=target.closest("td[field]").attr("field");
var opts={
showGrid:true,
singleSelect:false,
refresh:true
};
if(rowIndex == '0' && field== 'edit'){// CRM可编辑范围
opts.id='1b8accf2-36d5-11e6-a09d-6c626db0ae88';
} else if(rowIndex=='1' && field =='edit'){// 顾客移动平台可编辑范围
opts.id='4f9f35dd-3748-11e6-a09d-6c626db0ae88';
} else if(rowIndex=='0' && field== 'view'){// CRM账套见范围
opts.id='1b8accf2-36d5-11e6-a09d-6c626db0ae88';
} else if(rowIndex =='1' && field == 'view'){// 顾客移动平台可见范围
opts.id='4f9f35dd-3748-11e6-a09d-6c626db0ae88';
}
return $(target).searchbox("getValue");
},
setValue: function(target, value){
return $(target).searchbox("setValue",value);
},
resize: function(target, width){
$(target).searchbox("resize",width);
}
}
});
/**
* 字符串转日期
* @param dateStr 要转换的字符串,字符串格式要求:yyyy-MM-dd HH:mm:ss.SSS、yyyy/MM/dd HH:mm:ss.SSS
* 不一定年月日时分秒都有,但是各个位数、顺序、分隔符等要跟格式中保持一致,例如yyyy-MM也可以
* @returns 转换后的日期
*/
Date.parseDate = function(dateStr) {
if(dateStr!=undefined){
return new Date(Date.parse(dateStr.replace(/-/g,"/")));
}
return dateStr;
};
/**
* 字符串转日期
* @param dateStr 要转换的字符串
* @param pattern 格式,默认yyyy-MM-dd
* @returns 转换后的日期
*/
Date.parseDateByPattern = function(dateStr, pattern) {
pattern = pattern || "yyyy-MM-dd";
var yearStart = pattern.indexOf("y");
var yearEnd = pattern.lastIndexOf("y");
var monthStart = pattern.indexOf("M");
var monthEnd = pattern.lastIndexOf("M");
var dateStart = pattern.indexOf("d");
var dateEnd = pattern.lastIndexOf("d");
var hourStart = pattern.indexOf("H");
var hourEnd = pattern.lastIndexOf("H");
var minuteStart = pattern.indexOf("m");
var minuteEnd = pattern.lastIndexOf("m");
var secondStart = pattern.indexOf("s");
var secondEnd = pattern.lastIndexOf("s");
// var miliSecondStart = pattern.indexOf("S");
// var miliSecondEnd = pattern.lastIndexOf("S");
var yearStr = dateStr.substring(yearStart, yearEnd + 1);
var monthStr = dateStr.substring(monthStart, monthEnd + 1);
var dayStr = dateStr.substring(dateStart, dateEnd + 1);
var hourStr = dateStr.substring(hourStart, hourEnd + 1);
var minuteStr = dateStr.substring(minuteStart, minuteEnd + 1);
var secondStr = dateStr.substring(secondStart, secondEnd + 1);
// var miliSecondStr = dateStr.substring(miliSecondStart, miliSecondEnd);
var result = (yearStr==""?"2000":yearStr) + "/" + (monthStr==""?"01":monthStr)
+ "/" + (dayStr==""?"01":dayStr) + " " + (hourStr==""?"00":hourStr)
+ ":" + (minuteStr==""?"00":minuteStr) + ":" + (secondStr==""?"00":secondStr);
// + "." + (miliSecondStr==""?"000":miliSecondStr);
return Date.parseDate(result);
};
/**
* 日期格式化:yyyy-MM-dd HH:mm:ss.SSS
* @pattern 格式
* @return 格式化后的字符串
*/
Date.prototype.format = function(pattern) {
pattern = pattern || "";
if (pattern == "") {
return this.toString();
}
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"H+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(pattern)) {
pattern = pattern.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(pattern)) {
pattern = pattern.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return pattern;
};
/**
* 日期加减
* @param diff 加减的值,正数为加, 负数为减
* @returns 计算后的结果Date
*/
Date.prototype.addDays = function(diff) {
if (!$.isNumeric(diff)) {
return this;
}
return new Date(this.getTime() + 86400000 * diff);
};
/**
* 取得当前日期
* @returns {Date}
*/
Date.nowDate = function(){
return new Date(+new Date()+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
}
/**
* 日期计算
* @param strInterval
* @param Number
* @returns {Date}
*/
Date.prototype.addYears = function(y){
return new Date.setFullYear(this.getFullYear() + y);
};
/**
* 两个时间差
* @param sDate1
* @param sDate2
* @returns
*/
function DateDiff(sDate1, sDate2){ //sDate1和sDate2是2006-12-18格式
var aDate, oDate1, oDate2, iDays
aDate = sDate1.split("-")
oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2006格式
aDate = sDate2.split("-")
oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒数转换为天数
return iDays
}
/**
* 时间加年份
* @param date
* @param number
* @returns
*/
function DateAddYear(date,number){
var d1=new Date(date);
var d2=new Date(d1);
d2.setFullYear(d2.getFullYear()+parseInt(number));
return d2.format("yyyy-MM-dd");
}
/**
*转换日期对象为日期字符串
* @param date 日期对象
* @param isFull 是否为完整的日期数据,
* 为true时, 格式如"2000-03-05 01:05:04"
* 为false时, 格式如 "2000-03-05"
* @return 符合要求的日期字符串
*/
function getSmpFormatDate(date, isFull) {
var pattern = "";
if (isFull == true || isFull == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
} else {
pattern = "yyyy-MM-dd";
}
return getFormatDate(date, pattern);
}
/**
* 转换日期对象为日期字符串
* @param l long值
* @param pattern 格式字符串,例如:yyyy-MM-dd hh:mm:ss
* @return 符合要求的日期字符串
*/
function getFormatDate(date, pattern) {
if (date == undefined) {
date = new Date();
}
if (pattern == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
}
return date.format(pattern);
}
/**
* 日期大小比较
*/
function compareDate(strDate1,strDate2){
var date1 = new Date(strDate1.replace(/\-/g, "\/"));
var date2 = new Date(strDate2.replace(/\-/g, "\/"));
return date1-date2;
}
/**
* 判断是否null
*/
function isNull(data){
return (data == "" || data == undefined || data == null) ? true : false;
}
/**
* 获取QiNiu域名
*/
function getQiNiuDomain(){
return resource.cn_runsa_qiniu.domain;
}
/**
* 获取QiNiu上传凭证
*/
function getQiNiuUpToken(){
return resource.cn_runsa_qiniu.uptoken_url;
}
/**
* 获取qiniu图库素材
*/
function listQiNiuPics(){
return resource.cn_runsa_qiniu.listQiNiuPics;
}
/**
* 图片上传
*/
function imgUpload(btn, container, mxsize, type, typeFlag, iType, iTypeClassName){
/**
* 默认上传限制2M
*/
var filesize_default = 2*1024*1024;
if(!isNull(mxsize)){
filesize_default = mxsize;
}
var uploader = Qiniu.uploader({
runtimes: 'html5,flash,html4',
filters: {
mime_types : [
{ title : "Image files", extensions : "jpg,jpeg,gif,png" }
]
},
browse_button: btn,
uptoken_url: getQiNiuUpToken(),
get_new_uptoken: false,
domain: getQiNiuDomain(),
container: container,
max_file_size: filesize_default,
flash_swf_url: 'js/third/plupload/Moxie.swf',
max_retries: 3,
dragdrop: true,
drop_element: container,
chunk_size: '4mb',
auto_start: true,
init: {
'FilesAdded': function(up, files) {
plupload.each(files, function(file) {});
},
'BeforeUpload': function(up, file) {},
'UploadProgress': function(up, file) {
$.messager.progress({
title:'图片上传',
msg:'正在上传中, 请耐心等待...'
});
},
'FileUploaded': function(up, file, info) {
var domain = up.getOption('domain');
var res = JSON.parse(info);
var sourceLink = domain + res.key;
/**
* html标签判断
*/
if(!isNull(iType)&&!isNull(iTypeClassName)){
switch (iType) {
case 'input':
$(iTypeClassName).val(sourceLink);
break;
case 'textarea':
$(iTypeClassName).val($(iTypeClassName).val()+'&{'+sourceLink+'}&');
break;
case 'img':
$(iTypeClassName).attr('src',sourceLink);
$(iTypeClassName).show();
break;
}
}
console.log("------------------sourceLink = "+sourceLink);
},
'Error': function(up, err, errTip) {
if(-600 == err.code){
$.messager.alert(resource.msg_title, "上传的图片大小超出限制!");
}
},
'UploadComplete': function() {
$.messager.progress('close');
},
'Key': function(up, file) {
var prefix = type+'-'+typeFlag+'-';
var timestamp = new Date().getTime();
var fileName = file.name;
var fileExt = fileName.substring(fileName.lastIndexOf('.'));
return prefix+timestamp+fileExt;
}
}
});
}
//上传图片库
//格式: showImgsLib(resource.cn_runsa_qiniu.market_type,resource.cn_runsa_qiniu.market_MMS_typeFlag,'textarea',$('.groupId_1').find('.MMSContent'));
function showImgsLib(type,typeFlag,iType,iTypeClassName) {
var imgsLib = $('.imgsLib');
if(imgsLib.length > 0 ) {
imgsLib.dialog("destroy");
}
$(document.body).append('<div class="imgsLib"></div>');
var pageArray = [];
getMtral($('.imgsLib'),type,typeFlag,'',pageArray);
imgsLib = $('.imgsLib');
imgsLib.dialog({
title:'选择图片',
width:'840',
height:'550',//auto
buttons:[{
text: resource.btn.confirm,
handler:function() {
var selectedPic = imgsLib.find('.selected');
if(selectedPic.length==0){
$.messager.alert(resource.msg_title, "请选择图片");
return false;
}else{
var picSrc = selectedPic.find('img').attr('src');
var picName = selectedPic.find('span').text();
//alert(picSrc);
if(!isNull(iType)&&!isNull(iTypeClassName)){
switch (iType) {
case 'input':
$(iTypeClassName).val(picSrc);
break;
case 'textarea':
$(iTypeClassName).val($(iTypeClassName).val()+'&{'+picSrc+'}&');
break;
case 'img':
$(iTypeClassName).attr('src',picSrc);
$(iTypeClassName).show();
break;
}
}
}
imgsLib.dialog("close");
}
},
{
text: resource.btn.cancel,
handler:function() {
imgsLib.dialog("close");
}
}]
});
};
function getMtral(mainHtml,type,typeFlag,m,arrays) {
var param = {
prefix:type+'-'+typeFlag+'-',
marker:m
};
arrays.push(param.marker);
$.post(listQiNiuPics(),param,function(result) {
if(result){
//console.log('-----------statusCode = '+result.statusCode);
console.log('-----------marker = '+result.marker);
//console.log('-----------key = '+result.key);
//console.log(result);
var resultCount = result.key;
var picNameLenght = (type+typeFlag).length+2;
var resi = 0;
var yumin = getQiNiuDomain();
var imgAddUrl = '<div id="container111"><div id="pickfiles111" style="margin:10px auto 5px 700px;border:1px solid rgb(231,231,235);"><input class="picture_input" style="display: none;" value="" /><button style="font-size: 22px;background-color: rgb(68,181,73);color: #fff;cursor: pointer;border: 2px solid;border-radius: 8px;">本地上传</button></div></div>';
mainHtml.append(imgAddUrl);
var maxsize = 2*1024*1024;
imgUpload('pickfiles111', 'container111', maxsize, type, typeFlag, 'input',$('#container111').find('.picture_input')); // 图片上传
var picHtmlUl = '<ul>';
for (resi;resi<resultCount.length;resi++) {
var picHtmlLi = '<li class="img_item" style="float:left;display: inline-block;margin: 10px;position:relative"><label class="img_item_bd"><img style="width: 140px;height: 140px;" src="'+yumin+resultCount[resi].key+'"><span style="display: block;padding: 0 9px;width:120px;height: 32px;line-height: 32px;overflow: hidden;text-align: left;text-overflow:ellipsis;' +
'white-space: nowrap;">'+resultCount[resi].key.substring(picNameLenght)+'</span><div class="selected_mask"> <div class="selected_mask_inner" ></div> <div class="selected_mask_icon" ></div></div></label></li>';
picHtmlUl += picHtmlLi;
};
picHtmlUl +='</ul>';
//$('#container_main').find('button').bind('click',)
}
mainHtml.append(picHtmlUl);
mainHtml.append('<div style="display: inline-block;"><button class="picture_previous_page" style="font-size: 22px;background-color: rgb(68,181,73);color: #fff;cursor: pointer;border: 2px solid;border-radius: 8px;margin-left: 600px">上一页</button></div><div style="display: inline-block;"><button class="picture_next_page" style="font-size: 22px;background-color: rgb(68,181,73);color: #fff;cursor: pointer;border: 2px solid;border-radius: 8px;margin-left: 1px">下一页</button></div>')
$('.selected_mask').hide();
$('.img_item').bind('click', function () {
var itemThis = $(this);
$('.selected_mask').hide();
$('label').removeClass('selected');
itemThis.find('label').addClass('selected');
itemThis.find('.selected_mask').show();
});
$('.imgsLib').find('.picture_previous_page').bind('click',function() {
if(m!="") {
for(var i = 0;i<arrays.length;i++) {
if(arrays[i]==m) {
m = arrays[i-1];
mainHtml.empty();
getMtral(mainHtml,type,typeFlag,m,arrays);
break;
}
};
}
});
$('.imgsLib').find('.picture_next_page').bind('click',function() {
if(result.marker){
for(var i = 0;i<arrays.length;i++) {
if(arrays[i]==result.marker) {
break
}
};
arrays.push(result.marker);
}
if(result.marker){
m = result.marker;
mainHtml.empty();
getMtral(mainHtml,type,typeFlag,m,arrays);
}
});
});
}
//全局导出
function exportAllData(urls,param,fileName){
$.ajax({
type : "POST",
anysc :false,
url : urls,
data : param,
dataType : "json",
success : function(result) {
if (result.list == ''){
return;
}else{
JSONToCSVConvertor(result.list, fileName, true);
}
}
})
}
//json转csv格式
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for ( var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for ( var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURI(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//form验证:
function initValidateboxForm() {
$.extend($.fn.validatebox.defaults.rules, { // 表单验证扩展
// 数字验证
chkNumber: {
validator: function(value,param){
var reg = new RegExp("^[0-9]*$");
if(!reg.test(value)){
return false;
}else{
return true;
}
},
message: '请输入有效数字'
},
chkNumbers: {
validator: function(value,param){
var reg = /^\+?[1-9]\d*$/;
if(!reg.test(value)){
return false;
}else{
return true;
}
},
message: '请输入大于1的有效数字'
},
chkDiscount:{
validator:function(value,param){
var reg=new RegExp("^[1-9][0-9]*$");
if(!reg.test(value)){
return false
}else{
if(parseInt(value)<=parseInt(param)){
return false
}else{
return true
}
}
},message:'输入两位正整数'
} ,// 折数
intOrFloat : {// 验证整数或小数
validator : function(value) {
return /^\d+(\.\d+)?$/i.test(value);
},
message : '请输入非负数'
},
// 数字不能超过五验证
chkNumberWithFive: {
validator: function(value,param){
var reg = new RegExp("^[0-9]*$");
if(!reg.test(value) || Number(value) > 5){
return false;
}else{
return true;
}
},
message: '名次必须为正整数且不超过5'
},
chkNumberdouhao: {
validator: function(value,param){
var reg = /^\d+(,\d+)*$/;
if(!reg.test(value)){
return false;
}else{
return true;
}
},
message: '请输入以逗号分开的有效数字'
},
chkPoints: { // 积点值验证
validator: function(value,param){
var reg = new RegExp("^-?[1-9][0-9]*$");
if(!reg.test(value)){
return false;
}else{
return true;
}
},
message: '请输入有效积点值'
},
//移动手机号码验证
Mobile: {//value值为文本框中的值
validator: function (value) {
var reg = /(^1[3|4|5|7|8][0-9]{9}$)/;
return reg.test(value);
},
message: resource.employee.mobileValid
},
//邮箱验证
emailCheck:{//value值为文本框中的值
validator: function (value) {
var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
return reg.test(value);
},
message: "请输入正确的邮箱地址。"
},
// 推送起始日
chkIsuSTime: {
validator: function(value){
if(compareDate(value, getSmpFormatDate(new Date(), false))<0){
return false;
}else{
return true;
}
},
message: '开始日期不能早于今天'
},
// 结束时间
chkUseSTime: {
validator: function(value){
if(compareDate(value, $('.startDate2').datebox('getValue'))<0){
return false;
}else{
return true;
}
},
message: '结束日期不能早于开始日期'
},
// 结束时间
chkUseSETime: {
validator: function(value){
if(value-($.fn.getDistanceDay($('.startDate2').datebox('getValue'),$('.endDate').datebox('getValue')))>0){
return false;
}else{
return true;
}
},
message: '不能大于开始到结束天数!'
},
chkDate: { // 日期格式: 2016-01-01
validator: function(value){
var re = /((^((1[8-9]\d{2})|([2-9]\d{3}))(-)(10|12|0?[13578])(-)(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(11|0?[469])(-)(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\d{2})|([2-9]\d{3}))(-)(0?2)(-)(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)(-)(0?2)(-)(29)$)|(^([3579][26]00)(-)(0?2)(-)(29)$)|(^([1][89][0][48])(-)(0?2)(-)(29)$)|(^([2-9][0-9][0][48])(-)(0?2)(-)(29)$)|(^([1][89][2468][048])(-)(0?2)(-)(29)$)|(^([2-9][0-9][2468][048])(-)(0?2)(-)(29)$)|(^([1][89][13579][26])(-)(0?2)(-)(29)$)|(^([2-9][0-9][13579][26])(-)(0?2)(-)(29)$))/;
if (!re.test(value)) {
return false;
}
return true;
},
message: '请输入正确的日期'
},
// 当前数量
chkUseNum: {
validator: function(value){
if(!(($('.sendCoupons').find('.everyQtyHide').val()=="")) && (value-($('.sendCoupons').find('.everyQtyHide').val()))>0){
return false;
}else{
return true;
}
},
message: '不能多于券的余量!'
},
chkIsBlank: { // 空判断
validator: function(value){
if(isNull($.trim(value))){
return false;
}
return true;
},
message: '请输入有效内容'
},
//数字 编号只能输入数字、字母或其组合
NumberLetter: {
validator: function (value) {
var reg =/^[0-9a-zA-Z]*$/g;
return reg.test(value);
},
message: resource.bizentity.check.numberLetterValid
},
//decimal(5.4) 只能输入1位整数并且小数位最多4位小数,例如:1.1234
Decimal: {
validator: function (value) {
var reg =/^(\d|9)(\.\d{1,4})?$/g;
return reg.test(value);
},
message: resource.bizentity.check.decimalValid
},
//0-100整数 '税率范围0-100%'
Integer: {
validator: function (value) {
var reg =/^(?:0|[1-9][0-9]?|100)$/g;
return reg.test(value);
},
message: resource.bizentity.check.integer
},
// 字母或者数字
LetterOrNumber : {
validator : function(value) {
return /^[a-zA-Z0-9]+$/.test(value);
},
message : resource.company.letterOrNumberValid
},
//电话号码
ptphone: {//value值为文本框中的值
validator: function (value) {
var reg = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
return reg.test(value);
},
message: resource.bizentity.check.ptphone
},
double: {
validator: function (value) {
var reg = /^(:?(:?\d+.\d+)|(:?\d+))$/;
return reg.test(value);
},
message: resource.bizentity.check.double
}
});
}
//easyui官方验证命令:
//邮箱验证: validtype="email" invalidMessage="邮箱格式不正确"
//网址验证: validtype="url" invalidMessage="url格式不正确[http://www.example.com]"
//长度验证: validtype="length[8,20]" invalidMessage="有效长度8-20"
//手机验证: validtype="mobile"
//邮编验证:validtype="zipcode"
//账号验证: validtype="account[8,20]"
//汉子验证: validtype="CHS"
//远程验证: validtype="remote['checkname.aspx','name']" invalidMessage="用户名已存在"
// 导出错误EXCEL文件
function download(filePath, fileName){
var url = "./excelImport/downloadError";
inputs='<input type="hidden" name="fileName" value="'+fileName+'".xlsx" />';
inputs+='<input type="hidden" name="filePath" value="'+filePath+'" />';
jQuery('<form action="'+ url +'" method="post">'+inputs+'</form>')
.appendTo('body').submit().remove();
}
// 导出模板
function downloadExcel(fileName){
var url = "./excelImport/downloadExcelTemplate";
inputs='<input type="hidden" name="fileName" value="'+fileName+'" />';
jQuery('<form action="'+ url +'" method="post">'+inputs+'</form>')
.appendTo('body').submit().remove();
}