-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathSGCC.js
More file actions
2479 lines (2267 loc) · 86.2 KB
/
Copy pathSGCC.js
File metadata and controls
2479 lines (2267 loc) · 86.2 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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: teal; icon-glyph: project-diagram;
/*
* @author: 脑瓜
* @feedback: https://t.me/Scriptable_CN
* telegram: @anker1209
* version: 2.3.3
* update: 2026/08/11
* 原创UI,修改套用请注明来源
* 使用该脚本需DmYY依赖及添加重写,重写修改自作者@Yuheng0101
* 重写: https://raw.githubusercontent.com/dompling/Script/master/wsgw/index.js
* 依赖: https://raw.githubusercontent.com/dompling/Scriptable/master/Scripts/DmYY.js
*/
if (typeof require === 'undefined') require = importModule;
const {DmYY, Runing} = require('./DmYY');
class Widget extends DmYY {
constructor(arg) {
super(arg);
this.name = '国家电网';
this.en = 'wsgw_ng';
this.index = 0;
this.data = null;
this.Run();
};
version = '2.3.3';
fm = FileManager.local();
CACHE_FOLDER = Script.name();
cachePath = null;
isOverdue = false;
isPostPaid = false;
remainFee = 0;
balance = 0;
monthUsage = 0;
monthFee = 0;
yearUsage = 0;
yearFee = 0;
dayFee = 0;
stepEle = 0;
currentMonthEle = 0;
SCALE = 1;
barHeight = 12;
update = this.formatDate();
smallStackColor = '#3A9690';
endColor = '#3A9690';
lastColor = '#00CC99'
widgetStyle = '1';
dayElePq = [];
monthElePq = [];
size = {
logo : 48 * 0.95,
leftStack : 130 * 0.95,
smallFont : 12 * 0.95,
bigFont : 18 * 0.95,
balance : 20 * 0.95,
subSpacer : 6.5 * 0.95,
};
wsgw = {
step_2 : 2520,
step_3 : 4800,
interval : 360,
};
setRow(stack, key) {
const itemStack = stack.addStack();
switch (key) {
case '组合一' :
this.rowUnit(itemStack, this.settings.group1Left || '上期电费');
itemStack.addSpacer();
this.rowUnit(itemStack, this.settings.group1Right || '上期电量', true);
break;
case '组合二' :
this.rowUnit(itemStack, this.settings.group2Left || '年度电费');
itemStack.addSpacer();
this.rowUnit(itemStack, this.settings.group2Right || '年度电量', true);
break;
case '组合三' :
this.rowUnit(itemStack, this.settings.group3Left || '近日用电');
itemStack.addSpacer();
this.rowUnit(itemStack, this.settings.group3Right || '本月电量', true);
break;
case '阶梯电量':
this.stepEleStack(itemStack);
default:
return;
}
};
getWidgetData(key) {
switch (key) {
case '上期电费' :
return [key, `${this.monthFee}`, '元'];
case '上期电量' :
return [key, `${this.monthUsage}`, '度'];
case '年度电费':
return [key, `${this.yearFee}`, '元'];
case '年度电量':
return [key, `${this.yearUsage}`, '度'];
case '本月电量':
return [key, `${this.currentMonthEle}`, '度'];
case '近日用电':
const arr = this.dayElePq.map((item) => item.elePq).reverse();
this.dayFee = arr[arr.length - 1] || 0;
return [key, `${this.dayFee}`, '度'];
case '电费余额':
return [key, `${this.remainFee}`, '元'];
case '阶梯电量':
return key;
case '自定户名':
return key;
default:
return null;
}
};
rowUnit(stack, key, right = false){
const bodyStack = stack.addStack();
bodyStack.layoutVertically();
const h = this.size.smallFont + this.size.bigFont + 3;
const scale = h / 50;
switch (key) {
case '上期电费' :
this.unitContent(bodyStack, '上期电费', `${this.monthFee}`, true, right);
break;
case '上期电量' :
this.unitContent(bodyStack, '上期电量', `${this.monthUsage}`,false, right);
break;
case '年度电费':
this.unitContent(bodyStack, '年度电费', `${this.yearFee}`, true, right);
break;
case '年度电量':
this.unitContent(bodyStack, '年度电量', `${this.yearUsage}`, false, right);
break;
case '本月电量':
this.unitContent(bodyStack, '本月电量', `${this.currentMonthEle}`, false, right);
break;
case '近日用电':
const arr = this.dayElePq.map((item) => item.elePq).reverse();
this.dayFee = arr[arr.length - 1] || 0;
this.unitContent(bodyStack, '近日用电', `${this.dayFee}`, false, right);
break;
case '电费余额':
this.unitContent(bodyStack, '电费余额', `${this.remainFee}`, true, right);
break;
case '日用电图表':
if (!this.data[this.index]) return;
const dayAmount = parseFloat(this.settings.dayAmount) || 5;
const dayOpt = this.dayElePq.map((item) => item.elePq).reverse();
if (dayOpt.every(num => num === 0)) return;
const result = [...dayOpt].slice(-dayAmount);
if (result.every(num => num === 0)) return;
const dayChart = bodyStack.addImage(this.chartBar(dayOpt, dayAmount));
dayChart.imageSize = new Size((dayAmount * 18 - 10) * scale, 50 * scale);
break;
case '月用电图表':
if (!this.data[this.index]) return;
const monthAmount = parseFloat(this.settings.monthAmount) || 5;
const monthOpt = this.monthElePq.map((item) => item.cost);
if (monthOpt.every(num => num === 0)) return;
const monthChart = bodyStack.addImage(this.chartBar(monthOpt, monthAmount));
monthChart.imageSize = new Size((monthAmount * 18 - 10) * scale, 50 * scale);
break;
case '不显示':
return;
default:
return;
}
};
unitContent(stack, upText, downText, fee = false, right = false) {
const titleStack = stack.addStack();
if (right) titleStack.addSpacer();
const smallText = titleStack.addText(upText);
const valueStack = stack.addStack();
if (right) valueStack.addSpacer();
const bigText = valueStack.addText(downText);
fee ? this.unit(valueStack, '元', this.size.subSpacer) : this.unit(valueStack, '度', this.size.subSpacer);
smallText.textColor = this.widgetColor;
smallText.font = Font.semiboldSystemFont(this.size.smallFont);
smallText.textOpacity = 0.5;
bigText.textColor = this.widgetColor;
bigText.font = Font.mediumRoundedSystemFont(this.size.bigFont)
};
// 阶梯电量Stack
stepEleStack(stack) {
stack.layoutVertically();
const textStack = stack.addStack();
const leftTitle = textStack.addText('阶梯电量');
textStack.addSpacer();
const step = this.stepEleText();
const rightTitle = textStack.addText(step.text);
stack.addSpacer(4);
stack.addImage(this.progressBar());
leftTitle.textColor = this.widgetColor;
rightTitle.textColor = step.color;
[leftTitle, rightTitle].map(t => {
t.font = Font.semiboldSystemFont(this.size.smallFont);
t.textOpacity = 0.5
});
};
// 阶梯电量状态文本
stepEleText() {
let step = {
text: '一档·0%',
color: this.widgetColor,
progress: 0,
icon: '1.square',
level: 1
};
const isMonthly = this.settings.stepMode === '月';
const currentUsage = parseFloat(this.currentMonthEle);
const totalUsage = parseFloat(this.stepEle);
const per_step_1 = isMonthly
? ((currentUsage / this.wsgw.step_2) * 100).toFixed(2)
: ((totalUsage / this.wsgw.step_2) * 100).toFixed(2);
const per_step_2 = isMonthly
? ((currentUsage / this.wsgw.step_3) * 100).toFixed(2)
: ((totalUsage / this.wsgw.step_3) * 100).toFixed(2);
if ((isMonthly && currentUsage < this.wsgw.step_2) || (!isMonthly && totalUsage < this.wsgw.step_2)) {
step = {
text: `第一阶梯·${per_step_1}%`,
color: this.widgetColor,
progress: `${per_step_1}%`,
icon: '1.square',
level: 1
};
} else if ((isMonthly && currentUsage > this.wsgw.step_3) || (!isMonthly && totalUsage > this.wsgw.step_3)) {
const per_step_3 = (per_step_2 - 100).toFixed(2);
step = {
text: `第三阶梯·${per_step_3}%`,
color: new Color('#DE2A18'),
progress: `${per_step_3}%`,
icon: '3.square',
level: 3
};
} else {
step = {
text: `第二阶梯·${per_step_2}%`,
color: this.widgetColor,
progress: `${per_step_2}%`,
icon: '2.square',
level: 2
};
}
return step;
};
// 单位
unit(stack, text, spacer, corlor = this.widgetColor, overDue = false) {
stack.addSpacer(1);
const unitStack = stack.addStack();
unitStack.layoutVertically();
unitStack.addSpacer(spacer);
const unitTitle = unitStack.addText(text);
unitTitle.font = Font.semiboldRoundedSystemFont(10 * this.SCALE);
unitTitle.textColor = overDue ? new Color('DE2A18') : corlor;
};
addChineseUnit(stack, text, color, size) {
let textElement = stack.addText(text);
textElement.textColor = color;
textElement.font = Font.mediumSystemFont(size);
return textElement;
};
// 分栏
split(stack, width, height, ver = false) {
const splitStack = stack.addStack();
splitStack.size = new Size(width, height);
if (ver) splitStack.layoutVertically();
splitStack.addSpacer();
splitStack.backgroundColor = Color.dynamic(new Color('#B6B5BA'), new Color('#414144'));
};
// 标题
setTitle (stack, iconColor, nameColor) {
const nameStack = stack.addStack();
const iconSFS = SFSymbol.named('house.fill');
iconSFS.applyHeavyWeight();
let icon = nameStack.addImage(iconSFS.image);
icon.imageSize = new Size(20 * this.SCALE, 20 * this.SCALE);
icon.tintColor = iconColor;
nameStack.addSpacer(2);
let name = nameStack.addText(this.name || '国家电网');
name.font = Font.mediumSystemFont(16.5 * this.SCALE);
name.textColor = nameColor;
};
setList(stack, data, color) {
const rowStack = stack.addStack();
rowStack.centerAlignContent();
const lineStack = rowStack.addStack();
lineStack.size = new Size(8 * this.SCALE, 30 * this.SCALE);
lineStack.cornerRadius = 4 * this.SCALE;
lineStack.backgroundColor = new Color(color);
rowStack.addSpacer(10 * this.SCALE);
const leftStack = rowStack.addStack();
leftStack.layoutVertically();
leftStack.addSpacer(2 * this.SCALE);
const titleStack = leftStack.addStack();
const title = titleStack.addText(data[0]);
title.font = Font.systemFont(10 * this.SCALE);
title.textColor = this.widgetColor;
title.textOpacity = 0.5;
const valueStack = leftStack.addStack();
valueStack.centerAlignContent();
const value = valueStack.addText(data[1]);
value.font = Font.semiboldRoundedSystemFont(16 * this.SCALE);
value.textColor = this.widgetColor;
valueStack.addSpacer();
const unitStack = valueStack.addStack();
unitStack.cornerRadius = 4 * this.SCALE;
unitStack.borderWidth = 1;
unitStack.borderColor = new Color(color);
unitStack.setPadding(1, 3 * this.SCALE, 1, 3 * this.SCALE);
unitStack.size = new Size(30 * this.SCALE, 0)
unitStack.backgroundColor = Color.dynamic(new Color(color), new Color(color, 0.3));
const unit = unitStack.addText(data[2]);
unit.font = Font.mediumRoundedSystemFont(10 * this.SCALE);
unit.textColor = Color.dynamic(Color.white(), new Color(color));
};
// 更新时间
setUpdateStack (stack, color) {
const updateStack = stack.addStack();
updateStack.addSpacer();
updateStack.centerAlignContent();
const updataIcon = SFSymbol.named('arrow.2.circlepath');
updataIcon.applyHeavyWeight();
const updateImg = updateStack.addImage(updataIcon.image);
updateImg.tintColor = color;
updateImg.imageOpacity = 0.5;
updateImg.imageSize = new Size(10, 10);
updateStack.addSpacer(3);
const updateText = updateStack.addText(this.getTime());
updateText.font = Font.mediumSystemFont(10);
updateText.textColor = color;
updateText.textOpacity = 0.5;
updateStack.addSpacer();
};
// 余额
setBalanceStack (stack, color, padding, balanceSize, titleSize, spacer) {
let balance = this.balance;
let balanceTitle = this.isOverdue ? '电费欠费' : '电费余额';
if (!this.isOverdue && this.isPostPaid) {
balance = this.settings.showBalance === 'true' ? this.remainFee : this.monthFee;
balanceTitle = this.settings.showBalance === 'true' ? '电费余额' : '上期电费';
};
const bodyStack = stack.addStack();
bodyStack.layoutVertically();
bodyStack.cornerRadius = 10;
bodyStack.backgroundColor = color;
bodyStack.addSpacer(padding * this.SCALE);
// 余额Stack
const balanceStack = bodyStack.addStack();
balanceStack.centerAlignContent();
balanceStack.addSpacer();
const balanceText = balanceStack.addText(`${balance}`);
balanceText.font = Font.semiboldRoundedSystemFont(balanceSize);
balanceText.lineLimit = 1;
balanceText.minimumScaleFactor = 0.5;
balanceText.textColor = this.isOverdue ? new Color('DE2A18') : this.widgetColor;
this.unit(balanceStack, "元", spacer * this.SCALE, this.widgetColor, this.isOverdue);
balanceStack.addSpacer();
bodyStack.addSpacer(3 * this.SCALE);
// 余额标题Stack
const balanceTitleStack = bodyStack.addStack();
balanceStack.url = "com.wsgw.e.zsdl://platformapi/";
balanceTitleStack.addSpacer();
const balanceTitleText = balanceTitleStack.addText(balanceTitle);
balanceTitleStack.addSpacer();
bodyStack.addSpacer(padding * this.SCALE);
balanceTitleText.textColor = this.isOverdue ? new Color('DE2A18') : this.widgetColor;
balanceTitleText.font = Font.semiboldSystemFont(titleSize);
balanceTitleText.textOpacity = 0.5;
};
getLogo = async () => {
var logo;
if (this.settings.logoImg ==='铁塔') {
logo = await this.getImageByUrl('https://raw.githubusercontent.com/anker1209/icon/main/gjdw2.png', 'tower.png');
} else if (this.settings.logoImg ==='不显示') {
let context = new DrawContext();
context.size = new Size(1, 1);
context.opaque = false; context.setFillColor(new Color('#FFFFFF', 0));
context.fillRect(new Rect(0, 0, 1, 1));
logo = context.getImage();
} else if (this.settings.logoImg ==='国家电网' || !this.settings.logoImg || !this.settings.customizeUrl) {
logo = await this.getImageByUrl('https://raw.githubusercontent.com/anker1209/icon/main/gjdw.png', 'wsgw.png');
} else {
logo = await this.getImageByUrl(this.settings.customizeUrl, 'customize.png');
};
return logo
};
// ######################################
// ######################################
// 画画的BABY
makeCanvas(w, h) {
const drawing = new DrawContext();
drawing.opaque = false;
drawing.respectScreenScale = true;
drawing.size = new Size(w, h);
return drawing;
};
fillRect(drawing, x, y, width, height, cornerradio, color) {
let path = new Path();
let rect = new Rect(x, y, width, height);
path.addRoundedRect(rect, cornerradio, cornerradio);
drawing.addPath(path);
drawing.setFillColor(color);
drawing.fillPath();
};
drawLine(drawing, x1, y1, x2, y2, color, width) {
const path = new Path();
path.move(new Point(Math.round(x1),Math.round(y1)));
path.addLine(new Point(Math.round(x2),Math.round(y2)));
drawing.addPath(path);
drawing.setStrokeColor(color);
drawing.setLineWidth(width);
drawing.strokePath();
};
drawArc(context, center, radius, startAngle, endAngle, segments, fillColor, lineWidth, dir = 1) {
const path = new Path();
const startX = center.x + radius * Math.cos(startAngle);
const startY = center.y + radius * Math.sin(startAngle);
path.move(new Point(startX, startY));
for (let i = 1; i <= segments; i++) {
const t = i / segments;
const angle = startAngle + (endAngle - startAngle) * t;
const x = center.x + radius * Math.cos(angle);
const y = center.y + radius * Math.sin(angle);
path.addLine(new Point(x, y));
}
context.setStrokeColor(fillColor);
context.setLineWidth(lineWidth);
context.addPath(path);
context.strokePath();
};
drawHalfCircle(centerX, centerY, startAngle, circleRadius, context, fillColor, direction = 1) {
const halfCirclePath = new Path();
const startX = centerX + circleRadius * Math.cos(startAngle);
const startY = centerY + circleRadius * Math.sin(startAngle);
halfCirclePath.move(new Point(startX, startY));
for (let i = 0; i <= 10; i++) {
const t = i / 10;
const angle = startAngle + direction * Math.PI * t;
const x = centerX + circleRadius * Math.cos(angle);
const y = centerY + circleRadius * Math.sin(angle);
halfCirclePath.addLine(new Point(x, y));
}
context.setFillColor(fillColor);
context.addPath(halfCirclePath);
context.fillPath();
};
drawTickMarks(radius, color, startBgAngle, totalBgAngle, center, context) {
const tickRadius = radius - 8;
const tickLength = 4;
const totalTicks = 20;
for (let i = 0; i <= totalTicks; i++) {
const t = i / totalTicks;
const angle = startBgAngle + totalBgAngle * t;
const x1 = center.x + tickRadius * Math.cos(angle);
const y1 = center.y + tickRadius * Math.sin(angle);
const x2 = center.x + (tickRadius - tickLength) * Math.cos(angle);
const y2 = center.y + (tickRadius - tickLength) * Math.sin(angle);
const tickPath = new Path();
tickPath.move(new Point(x1, y1));
tickPath.addLine(new Point(x2, y2));
context.setStrokeColor(color);
context.setLineWidth(1);
context.addPath(tickPath);
context.strokePath();
}
};
progressBar() {
const W = 200, H = this.barHeight , r = 6, h = 6;
const drawing = this.makeCanvas(W, H);
const progress = this.settings.stepMode === '月' ? this.currentMonthEle / this.wsgw.step_3 * W : parseFloat(this.stepEle) / this.wsgw.step_3 * W;
const circle = progress - 2 * r;
const fgColor = new Color(this.settings.barColor || '#0db38e', 1);
const bgColor = new Color(this.settings.barColor || '#0db38e', 0.3);
const pointerColor = new Color(this.settings.pointerColor || '#0db38e', 1);
this.drawLine(drawing, r, H, r, 0, bgColor, 2);
this.drawLine(drawing, W - r, H, W - r, 0, bgColor, 2);
this.drawLine(drawing, this.wsgw.step_2 / this.wsgw.step_3 * W, H, this.wsgw.step_2 / this.wsgw.step_3 * W, 0, bgColor, 2);
this.fillRect(drawing, 0, (H - h) / 2, W, h, h / 2, bgColor);
this.fillRect(drawing, 0, (H - h) / 2, progress > W ? W : progress < r * 2 ? r * 2 : progress, h, h / 2, fgColor);
this.fillRect(drawing, circle > W - r * 2 ? W - r * 2 : circle < 0 ? 0 : circle, H / 2 - r, r * 2, r * 2, r, pointerColor);
return drawing.getImage();
};
wideProgressBar() {
const width = 200;
const height = 22;
const progress = this.settings.stepMode === '月' ? this.currentMonthEle / this.wsgw.step_3 * width : parseFloat(this.stepEle) / this.wsgw.step_3 * width;
const drawing = this.makeCanvas(width, height);
this.drawLine(drawing, this.wsgw.step_2 / this.wsgw.step_3 * width, height, this.wsgw.step_2 / this.wsgw.step_3 * width, 0, new Color(this.smallStackColor, 0.3), 2);
this.fillRect(drawing, 0, 0, width, height, 6, new Color(this.smallStackColor, 0.3));
this.fillRect(drawing, 0, 0, progress > width? width : progress, height, 6, new Color(this.smallStackColor, 1));
return drawing.getImage();
};
chartBar (opt, n) {
let chartColor = new Color(this.settings.chartColor || '#0db38e', 1);
const drawing = this.makeCanvas(n * 18 - 10, 50);
let data = opt;
if (data.length > n) {
data = data.slice(data.length - n);
}
const max = Math.max(...data);
const min = max / 2;
if (data.length < n) {
const gap = n - data.length;
const newArr = [];
for (let i = 0; i < gap; i++) {
newArr.push(Math.floor(Math.random() * (max - min + 1)) + min);
}
data = [...data, ...newArr]
};
const deltaY = 50 / max;
for (let i = 0; i < n; i++) {
let temp = data[i] * deltaY;
if (i + 1 > opt.length) {
chartColor = new Color(this.settings.chartColor || '#0db38e', 0.3);
};
this.fillRect(drawing, i * 18, 50 - temp, 8, temp, 4, chartColor)
}
return drawing.getImage();
};
gaugeChart() {
const w = 150, h = 150;
const drawing = this.makeCanvas(w, h);
const center = new Point(w / 2, h / 2);
const radius = w / 2 - 10;
const circleRadius = 6;
const startBgAngle = (11 * Math.PI) / 12;
const endBgAngle = (25 * Math.PI) / 12;
const totalBgAngle = endBgAngle - startBgAngle;
const gapAngle = Math.PI / 15;
const lineWidth = circleRadius * 2;
const colors = [
{ base: new Color("#00CC99", 0.1), progress: new Color("#00CC99") },
{ base: new Color("#FFD700", 0.1), progress: new Color("#FFD700") },
{ base: new Color("#FF4500", 0.1), progress: new Color("#FF4500") },
{ base: new Color("#800020", 0.1), progress: new Color("#800020") }
];
const segmentAngle = (totalBgAngle - 2 * gapAngle) / 3;
const step = this.stepEleText();
const level = step.level;
let progress = parseFloat(step.progress.slice(0, -1)) / 100;
progress = progress > 1 ? 1 : progress;
for (let i = 0; i < 3; i++) {
const segmentStartAngle = startBgAngle + i * (segmentAngle + gapAngle);
const segmentEndAngle = segmentStartAngle + segmentAngle;
this.drawArc(
drawing,
center,
radius,
segmentStartAngle,
segmentEndAngle,
100,
colors[i].base,
lineWidth
);
this.drawHalfCircle(
center.x + radius * Math.cos(segmentStartAngle),
center.y + radius * Math.sin(segmentStartAngle),
segmentStartAngle,
circleRadius,
drawing,
colors[i].base,
-1
);
this.drawHalfCircle(
center.x + radius * Math.cos(segmentEndAngle),
center.y + radius * Math.sin(segmentEndAngle),
segmentEndAngle,
circleRadius,
drawing,
colors[i].base,
1
);
if (level > i) {
const stepColors = this.gradientColor([`#${colors[i].progress.hex}`, `#${colors[i+1].progress.hex}`], 51);
const isCurrentLevel = level === i + 1;
const progressEndAngle = isCurrentLevel
? segmentStartAngle + progress * segmentAngle
: segmentEndAngle;
const p = isCurrentLevel ? progress * 50 : 50; // 插值因子
this.lastColor = this.gradientColor([`#${colors[level - 1].progress.hex}`, `#${colors[level].progress.hex}`], 51)[Math.round(p)];
for (let j = 0; j <= p; j++) {
const t = j / p;
const angle = segmentStartAngle + t * (progressEndAngle - segmentStartAngle);
const x = center.x + radius * Math.cos(angle);
const y = center.y + radius * Math.sin(angle);
const circleRect = new Rect(
x - circleRadius,
y - circleRadius,
circleRadius * 2,
circleRadius * 2
);
drawing.setFillColor(new Color(stepColors[j]));
drawing.fillEllipse(circleRect);
}
}
}
return drawing.getImage();
}
// ######################################
// ######################################
formatDate() {
let theDate = Date.now();
let dF = new DateFormatter();
dF.dateFormat = 'yyyy-MM-dd HH:mm:ss';
theDate = new Date(theDate);
return dF.string(theDate);
};
getTime = () => {
const dateTime = this.update;
const parts = dateTime.split(' ');
const datePart = parts[0].split('-');
const timePart = parts[1].split(':');
return `${datePart[1]}-${datePart[2]} ${timePart[0]}:${timePart[1]}`;
};
// 获取缩放比例
getWidgetScaleFactor() {
const referenceScreenSize = { width: 430, height: 932, widgetSize: 170 };
const screenData = [
{ width: 440, height: 956, widgetSize: 170 }, // 16 Pro Max
{ width: 430, height: 932, widgetSize: 170 }, // 16 Plus, 15 Plus, 15 Pro Max, 14 Pro Max
{ width: 428, height: 926, widgetSize: 170 }, // 14 Plus, 13 Pro Max, 12 Pro Max
{ width: 414, height: 896, widgetSize: 169 }, // 11 Pro Max, XS Max, 11, XR
{ width: 402, height: 874, widgetSize: 162 }, // 16 Pro
{ width: 414, height: 736, widgetSize: 159 }, // Home button Plus phones
{ width: 393, height: 852, widgetSize: 158 }, // 16, 15, 15 Pro, 14 Pro
{ width: 390, height: 844, widgetSize: 158 }, // 14, 13, 13 Pro, 12, 12 Pro
{ width: 375, height: 812, widgetSize: 155 }, // 13 mini, 12 mini / 11 Pro, XS, X
{ width: 375, height: 667, widgetSize: 148 }, // SE3, SE2, Home button Plus in Display Zoom mode
{ width: 360, height: 780, widgetSize: 155 }, // 11 and XR in Display Zoom mode
{ width: 320, height: 568, widgetSize: 141 } // SE1
];
const deviceScreenWidth = Device.screenSize().width;
const deviceScreenHeight = Device.screenSize().height;
const matchingScreen = screenData.find(screen =>
(screen.width === deviceScreenWidth && screen.height === deviceScreenHeight) ||
(screen.width === deviceScreenHeight && screen.height === deviceScreenWidth)
);
if (!matchingScreen) {
return 1;
};
const scaleFactor = (matchingScreen.widgetSize - 30 ) / (referenceScreenSize.widgetSize - 30);
return Math.floor(scaleFactor * 100) / 100;
};
gradientColor(colors, step) {
var startRGB = this.colorToRgb(colors[0]),
startR = startRGB[0],
startG = startRGB[1],
startB = startRGB[2];
var endRGB = this.colorToRgb(colors[1]),
endR = endRGB[0],
endG = endRGB[1],
endB = endRGB[2];
var sR = (endR - startR) / step,
sG = (endG - startG) / step,
sB = (endB - startB) / step;
var colorArr = [];
for (var i = 0;i < step; i++) {
var hex = this.colorToHex('rgb(' + parseInt((sR * i + startR)) + ',' + parseInt((sG * i + startG)) + ',' + parseInt((sB * i + startB)) + ')');
colorArr.push(hex);
}
return colorArr;
}
colorToRgb(sColor) {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var sColor = sColor.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return sColorChange;
} else {
return sColor;
}
};
colorToHex(rgb) {
var _this = rgb;
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
if (/^(rgb|RGB)/.test(_this)) {
var aColor = _this.replace(/(?:\(|\)|rgb|RGB)*/g,"").split(",");
var strHex = "#";
for (var i = 0; i < aColor.length; i++) {
var hex = Number(aColor[i]).toString(16);
hex = hex.length < 2 ? 0 + '' + hex : hex;
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = _this;
}
return strHex;
} else if (reg.test(_this)) {
var aNum = _this.replace(/#/,"").split("");
if (aNum.length === 6) {
return _this;
} else if (aNum.length === 3) {
var numHex = "#";
for (var i = 0; i < aNum.length; i+=1) {
numHex += (aNum[i] + aNum[i]);
}
return numHex;
}
} else {
return _this;
}
}
createCenteredText(stack, content, unit, fontIndex, fontSize, color, opacity = 1, icon) {
const systemFonts = [
// 0, Default
Font.systemFont(fontSize),
// 1, Light
Font.lightSystemFont(fontSize),
// 2, Medium
Font.mediumSystemFont(fontSize),
// 3, Bold
Font.boldSystemFont(fontSize),
// 4, Medium Rounded
Font.mediumRoundedSystemFont(fontSize),
// 5, Semibold Rounded
Font.semiboldRoundedSystemFont(fontSize),
// 6, Bold Rounded
Font.boldRoundedSystemFont(fontSize)
];
const rowStack = stack.addStack();
rowStack.centerAlignContent();
rowStack.addSpacer();
if(icon) {
const sfs = SFSymbol.named(icon);
const sfsImg = rowStack.addImage(sfs.image);
sfsImg.tintColor = color;
sfsImg.imageSize = new Size(15 * this.SCALE, 15 * this.SCALE);
rowStack.addSpacer(3);
}
let textElement = rowStack.addText(content);
textElement.font = systemFonts[fontIndex] || Font.systemFont(fontSize);
textElement.textColor = color;
textElement.textOpacity = opacity;
this.addChineseUnit(rowStack, unit, color, 13 * this.SCALE);
rowStack.addSpacer();
return rowStack;
};
createCenteredStack(stack, text, bgColor) {
const outStack = stack.addStack();
outStack.addSpacer();
const innerStack = outStack.addStack();
innerStack.setPadding(1, 1, 1, 1);
innerStack.backgroundColor = bgColor;
innerStack.cornerRadius = 3;
const textElement = innerStack.addText(text);
textElement.textColor = Color.white();
textElement.font = Font.mediumSystemFont(10 * this.SCALE);
outStack.addSpacer();
return outStack;
};
// ######################################
// ######################################
httpRequest = async(dataName, url, json = true, options, key, method = 'GET', retryCount = 2) => {
let cacheKey = key;
let localCache = this.loadStringCache(cacheKey);
const lastCacheTime = this.getCacheModificationDate(cacheKey);
const timeInterval = Math.floor((this.getCurrentTimeStamp() - lastCacheTime) / 60);
console.log(`${dataName}:读取缓存${timeInterval}分钟前,刷新 ${this.wsgw.interval}分钟`);
// 如果缓存有效,直接返回缓存
if (timeInterval < this.wsgw.interval && localCache != null && localCache.length > 0) {
return json ? JSON.parse(localCache) : localCache;
}
// 尝试在线请求(带重试)
let data = null;
let lastError = null;
for (let attempt = 0; attempt <= retryCount; attempt++) {
try {
let req = new Request(url);
req.method = method;
Object.keys(options).forEach((key) => {
req[key] = options[key];
});
data = await (json ? req.loadJSON() : req.loadString());
// 验证数据有效性
if (json && (!data || typeof data !== 'object')) {
throw new Error('返回数据格式无效');
}
// 保存缓存
this.saveStringCache(cacheKey, json ? JSON.stringify(data) : data);
console.log(`${dataName}:在线请求成功`);
return data;
} catch (e) {
lastError = e;
if (attempt < retryCount) {
console.log(`${dataName}:请求失败,重试中...`);
}
}
}
// 所有重试失败,尝试使用缓存
localCache = this.loadStringCache(cacheKey);
if (localCache != null && localCache.length > 0) {
console.log(`${dataName}:请求失败,使用缓存`);
try {
return json ? JSON.parse(localCache) : localCache;
} catch (e) {
console.error(`${dataName}:缓存解析失败`);
}
}
// 没有可用数据
console.error(`${dataName}:加载失败 (${lastError?.message || '网络错误'})`);
throw new Error(`无法获取${dataName}`);
};
loadStringCache(cacheKey) {
const cacheFile = this.fm.joinPath(this.cachePath, cacheKey);
const fileExists = this.fm.fileExists(cacheFile);
let cacheString = '';
if (fileExists) {
cacheString = this.fm.readString(cacheFile);
}
return cacheString;
};
saveStringCache(cacheKey, content) {
if (!this.fm.fileExists(this.cachePath)) {
this.fm.createDirectory(this.cachePath, true);
};
const cacheFile = this.fm.joinPath(this.cachePath, cacheKey);
this.fm.writeString(cacheFile, content);
};
getCacheModificationDate(cacheKey) {
const cacheFile = this.fm.joinPath(this.cachePath, cacheKey);
const fileExists = this.fm.fileExists(cacheFile);
if (fileExists) {
return this.fm.modificationDate(cacheFile).getTime() / 1000;
} else {
return 0;
}
};
getCurrentTimeStamp() {
return new Date().getTime() / 1000;
};
getImageByUrl = async(url, cacheKey) => {
const cacheImg = this.loadImgCache(cacheKey);
if (cacheImg != undefined && cacheImg != null) {
// 使用缓存图片(不输出日志)
return this.loadImgCache(cacheKey);
}
try {
console.log(`在线请求:${cacheKey}`);
const req = new Request(url);
const imgData = await req.load();
const img = Image.fromData(imgData);
this.saveImgCache(cacheKey, img);
return img;
} catch (e) {
console.error(`图片加载失败:${e}`);
let cacheImg = this.loadImgCache(cacheKey);
if (cacheImg != undefined) {
// 使用缓存图片(不输出日志)
return cacheImg;
}
console.log(`使用预设图片`);
let ctx = new DrawContext();
ctx.size = new Size(80, 80);
ctx.setFillColor(Color.darkGray());
ctx.fillRect(new Rect(0, 0, 80, 80));
return await ctx.getImage();
}
};
loadImgCache(cacheKey) {
const cacheFile = this.fm.joinPath(this.cachePath, cacheKey);
const fileExists = this.fm.fileExists(cacheFile);
let img = undefined;
if (fileExists) {
if (this.settings.useICloud ==='true') this.fm.downloadFileFromiCloud(this.cachePath);
img = Image.fromFile(cacheFile);
}
return img;
};
saveImgCache(cacheKey, img) {
if (!this.fm.fileExists(this.cachePath)) {
this.fm.createDirectory(this.cachePath, true);
};
const cacheFile = this.fm.joinPath(this.cachePath, cacheKey);
this.fm.writeImage(cacheFile, img);
};
async checkAndUpdateScript() {
const updateUrl = "https://raw.githubusercontent.com/anker1209/Scriptable/main/upcoming.json";
const scriptName = Script.name() + '.js'
const request = new Request(updateUrl);
const response = await request.loadJSON();
const latestVersion = response.find(i => i.name === "sgcc").version;
const downloadUrl = response.find(i => i.name === "sgcc").downloadUrl;
const isUpdateAvailable = this.version !== latestVersion;
if (isUpdateAvailable) {
const alert = new Alert();
alert.title = "检测到新版本";
alert.message = `新版本:${latestVersion},是否更新?`;
alert.addAction("更新");
alert.addCancelAction("取消");