Repository navigation
Expand file tree
/
Copy pathChinaGas.js
More file actions
2123 lines (1869 loc) · 75.5 KB
/
Copy pathChinaGas.js
File metadata and controls
2123 lines (1869 loc) · 75.5 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: yellow; icon-glyph: fire;
/**
* 组件名称: 中燃在线 (China Gas)
* 版本号: v2.8.1
* 依赖框架: DmYY
* 使用说明: 根据 UI 账户设置教程
* 其他说明: UI 套用请说明来源,其他地区修改接口即可
*/
if (typeof require === 'undefined') require = importModule;
const { DmYY, Runing } = require('./DmYY');
class Widget extends DmYY {
version = '2.8.1';
SCALE = 1;
gasData = null;
isOffline = false;
constructor(arg) {
super(arg);
this.name = '中燃在线';
this.en = 'ChinaGas';
this.logo = 'https://raw.githubusercontent.com/githubdulong/Script/master/Images/ChinaGas_logo.png';
this.fm = FileManager.local();
this.cachePath = this.fm.joinPath(this.fm.documentsDirectory(), 'ChinaGas_Cache');
if (typeof this.Run === 'function') {
this.Run();
}
}
loadCache(key) {
try {
const file = this.fm.joinPath(this.cachePath, key);
if (this.fm.fileExists(file)) {
return this.fm.readString(file);
}
} catch (_) {}
return null;
}
saveCache(key, content) {
try {
if (!this.fm.fileExists(this.cachePath)) {
this.fm.createDirectory(this.cachePath, true);
}
if (!this.fm.fileExists(this.cachePath)) {
console.warn('[ChinaGas] 缓存目录创建失败: ' + this.cachePath);
return false;
}
const file = this.fm.joinPath(this.cachePath, key);
this.fm.writeString(file, content);
return true;
} catch (e) {
console.warn('[ChinaGas] 写入缓存失败 ' + key + ': ' + e);
return false;
}
}
clearStorage() {
try {
if (this.fm.fileExists(this.cachePath)) {
this.fm.remove(this.cachePath);
}
} catch (_) {}
}
async init() {
this.settings.alias = this.settings.alias || '中燃在线';
this.settings.themeColor = this.settings.themeColor || '#FF9500';
if (this.settings.balanceTextColor !== undefined) {
delete this.settings.balanceTextColor;
this.saveSettings(false);
}
if (this.settings.balanceColor !== undefined) {
delete this.settings.balanceColor;
this.saveSettings(false);
}
this.settings.interval = this.settings.interval || '360';
this.settings.balanceLimit = this.settings.balanceLimit || '500';
// 只保留三种稳定款式;旧版曾存过 gradient,已废弃,回落到一体无缝条
const VALID_STYLES = ['square', 'capsule', 'smooth'];
if (!VALID_STYLES.includes(this.settings.progressStyle)) {
this.settings.progressStyle = this.settings.progressStyle === 'gradient' ? 'smooth' : 'square';
}
if (this.settings.useGradientBar === undefined) {
this.settings.useGradientBar = 'true';
}
if (this.settings.useGradientBalance === undefined) {
this.settings.useGradientBalance = 'true';
}
if (this.settings.maskCustCode === undefined) {
this.settings.maskCustCode = 'false';
}
if (this.settings.maskCompName === undefined) {
this.settings.maskCompName = 'false';
}
const uiScale = parseFloat(this.settings.uiScale);
this.SCALE = this.getWidgetScaleFactor() * (isFinite(uiScale) && uiScale > 0 ? uiScale : 1);
await this.fetchGasInfo(false);
}
getWidgetScaleFactor() {
try {
const deviceSize = Device.screenSize();
const screenData = [
{ width: 440, height: 956, scale: 1.0 },
{ width: 430, height: 932, scale: 0.98 },
{ width: 428, height: 926, scale: 0.97 },
{ width: 414, height: 896, scale: 0.95 },
{ width: 402, height: 874, scale: 0.93 },
{ width: 393, height: 852, scale: 0.90 },
{ width: 390, height: 844, scale: 0.89 },
{ width: 375, height: 812, scale: 0.85 },
];
const match = screenData.find(
d => (d.width === deviceSize.width && d.height === deviceSize.height) ||
(d.width === deviceSize.height && d.height === deviceSize.width)
);
return match ? match.scale : 0.95;
} catch (_) {
return 0.95;
}
}
getWidgetSmallWidth() {
try {
const deviceSize = Device.screenSize();
const screenW = Math.round(Math.min(deviceSize.width, deviceSize.height));
const screenH = Math.round(Math.max(deviceSize.width, deviceSize.height));
const sizes = [
{ w: 440, h: 956, smallW: 170 },
{ w: 430, h: 932, smallW: 170 },
{ w: 428, h: 926, smallW: 170 },
{ w: 414, h: 896, smallW: 169 },
{ w: 414, h: 736, smallW: 159 },
{ w: 402, h: 874, smallW: 162 },
{ w: 393, h: 852, smallW: 158 },
{ w: 390, h: 844, smallW: 158 },
{ w: 375, h: 812, smallW: 155 },
{ w: 375, h: 667, smallW: 148 },
{ w: 360, h: 780, smallW: 155 },
];
const match = sizes.find(s => Math.abs(s.w - screenW) <= 3 && Math.abs(s.h - screenH) <= 3);
if (match) return match.smallW;
if (screenW >= 420) return 170;
if (screenW >= 398) return 162;
if (screenW >= 385) return 158;
return 155;
} catch (_) {
return 158;
}
}
getWidgetLargeWidth() {
try {
const deviceSize = Device.screenSize();
const screenW = Math.round(Math.min(deviceSize.width, deviceSize.height));
const screenH = Math.round(Math.max(deviceSize.width, deviceSize.height));
const sizes = [
{ w: 440, h: 956, largeW: 368 },
{ w: 430, h: 932, largeW: 364 },
{ w: 428, h: 926, largeW: 364 },
{ w: 414, h: 896, largeW: 360 },
{ w: 414, h: 736, largeW: 348 },
{ w: 402, h: 874, largeW: 348 },
{ w: 393, h: 852, largeW: 338 },
{ w: 390, h: 844, largeW: 338 },
{ w: 375, h: 812, largeW: 329 },
{ w: 375, h: 667, largeW: 321 },
{ w: 360, h: 780, largeW: 348 },
];
const match = sizes.find(s => Math.abs(s.w - screenW) <= 3 && Math.abs(s.h - screenH) <= 3);
if (match) return match.largeW;
if (screenW >= 435) return 368;
if (screenW >= 420) return 364;
if (screenW >= 405) return 355;
if (screenW >= 398) return 348;
if (screenW >= 385) return 338;
return 329;
} catch (_) {
return 338;
}
}
drawGlowDot(hexColor, size = 36) {
const ctx = new DrawContext();
ctx.size = new Size(size, size);
ctx.opaque = false;
ctx.respectScreenScale = true;
const drawLayer = (ratio, color, alpha) => {
const d = size * ratio;
const offset = (size - d) / 2;
ctx.setFillColor(new Color(color, alpha));
ctx.fillEllipse(new Rect(offset, offset, d, d));
};
drawLayer(1.00, hexColor, 0.26);
drawLayer(0.74, hexColor, 0.55);
drawLayer(0.52, hexColor, 1.00);
drawLayer(0.30, '#FFFFFF', 1.00);
return ctx.getImage();
}
getColor() {
const light = (this.settings && this.settings.lightColor) || '#000000';
const dark = (this.settings && this.settings.darkColor) || '#FFFFFF';
return Color.dynamic(new Color(light), new Color(dark));
}
getWidgetBgColor() {
const light = (this.settings && this.settings.lightBgColor) || '#FFFFFF';
const dark = (this.settings && this.settings.darkBgColor) || '#000000';
return Color.dynamic(new Color(light), new Color(dark));
}
async fetchGasInfo(force = false) {
const custCode = (this.settings.custCode || '').trim();
const custName = (this.settings.custName || '').trim();
const userId = (this.settings.userId || '').trim();
const xMasAppInfo = (this.settings.xMasAppInfo || '').trim();
const cacheKey = `gas_cache_${custCode || 'default'}.json`;
const intervalMin = parseInt(this.settings.interval) || 360;
let cachedData = null;
const cacheStr = this.loadCache(cacheKey);
if (cacheStr) {
try {
cachedData = JSON.parse(cacheStr);
} catch (_) {
cachedData = null;
}
}
if (!custCode || !xMasAppInfo) {
if (cachedData) {
this.gasData = cachedData;
this.isOffline = true;
} else {
this.gasData = null;
}
return;
}
if (!force && cachedData && cachedData._updateTimestamp) {
const elapsedMin = Math.floor((Date.now() - cachedData._updateTimestamp) / 1000 / 60);
if (elapsedMin >= 0 && elapsedMin < intervalMin) {
console.log(`[ChinaGas] 命中沙盒缓存:上次更新于 ${elapsedMin} 分钟前(数据读取间隔: ${intervalMin} 分钟),直接读取本地数据,跳过网络请求`);
this.gasData = cachedData;
this.isOffline = false;
return;
}
console.log(`[ChinaGas] 本地数据已超出读取周期(已过 ${elapsedMin} 分钟,设定间隔: ${intervalMin} 分钟),正在联网拉取最新数据...`);
}
const url = 'https://zrds.95007.com/crm_controller/user/findCustInfoByCustCodeAndCustName';
const now = Date.now();
const bodyStr = [
`custCode=${encodeURIComponent(custCode)}`,
`custName=${encodeURIComponent(custName)}`,
`timeStamp=${now}`,
`signature=gas_sig_${now}`
].join('&');
try {
const res = await this.$request.post(url, {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'userId': userId,
'x-mas-app-info': xMasAppInfo,
'accessFrom': 'yphpaymp',
'platform': 'mp-weixin'
},
body: bodyStr,
timeoutInterval: 10
});
if (res && res.status === '1' && res.data) {
this.gasData = typeof res.data === 'object' ? res.data : {};
let comp = this.gasData.compName || this.gasData.companyName || this.gasData.orgName || this.gasData.filialeName || this.gasData.branchName || this.gasData.unitName;
if (!comp) {
comp = this.detectCompanyName(this.gasData) || this.detectCompanyName(res);
}
if (comp) {
this.gasData.compName = comp;
}
const dateObj = new Date();
this.gasData._fetchTime = dateObj.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
this.gasData._fetchDate = dateObj.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
this.gasData._updateTimestamp = Date.now();
this.saveCache(cacheKey, JSON.stringify(this.gasData));
this.recordDailyBalance();
this.isOffline = false;
console.log(`[ChinaGas] 成功获取最新燃气数据并写入沙盒,更新时间: ${this.gasData._fetchTime}`);
} else {
throw new Error((res && (res.message || res.msg)) || '接口返回异常状态');
}
} catch (e) {
console.warn('[ChinaGas] 联网请求失败或微信凭据异常,安全回退本地缓存: ' + e);
if (cachedData) {
this.gasData = cachedData;
this.isOffline = true;
} else {
this.gasData = null;
}
}
}
async parseClipboardCurl() {
const paste = Pasteboard.paste();
if (!paste || !paste.trim()) {
const a = new Alert();
a.title = '剪贴板为空';
a.message = '请先在 Surge / Loon 抓包软件中复制请求 cURL 或请求头,再点击此功能。';
a.addAction('知道了');
await a.presentAlert();
return;
}
const str = paste.trim();
let modified = false;
const userMatch = str.match(/(?:userId|userid)['":\s=]+([0-9a-zA-Z_-]+)/i);
if (userMatch && userMatch[1]) {
this.settings.userId = userMatch[1].trim();
modified = true;
}
const tokenMatch = str.match(/x-mas-app-info['":\s=]+([^'"\r\n&]+)/i);
if (tokenMatch && tokenMatch[1]) {
this.settings.xMasAppInfo = tokenMatch[1].trim();
modified = true;
}
const custMatch = str.match(/(?:custCode|custcode)['":\s=]+([0-9]{6,12})/i);
if (custMatch && custMatch[1]) {
this.settings.custCode = custMatch[1].trim();
modified = true;
}
const nameRegex = /(?:custName|custname)['":\s=]+([^'"&\r\n\s]+)/gi;
let nMatch;
while ((nMatch = nameRegex.exec(str)) !== null) {
let rawName = nMatch[1].trim();
if (!/^https?:\/\//i.test(rawName) && !/^HTTP\/\d/i.test(rawName) && rawName !== 'undefined' && rawName !== 'null') {
try {
rawName = decodeURIComponent(rawName);
} catch (_) {}
this.settings.custName = rawName;
modified = true;
break;
}
}
const compMatch = str.match(/(?:compName|companyName|company|corpName)['":\s=]+([^'"&\r\n]+)/i);
if (compMatch && compMatch[1]) {
let rawComp = compMatch[1].trim();
try {
rawComp = decodeURIComponent(rawComp);
} catch (_) {}
this.settings.customCompName = rawComp;
modified = true;
}
const a = new Alert();
if (modified) {
this.saveSettings(false);
await this.fetchGasInfo(true);
a.title = '凭据解析成功';
a.message = `已自动提取并保存:\n• 用户ID: ${this.settings.userId || '未找到'}\n• 燃气户号: ${this.settings.custCode || '未找到'}\n• 户名: ${this.settings.custName || '未找到'}\n• 登录凭据: 已更新\n• 服务单位: ${this.settings.customCompName || '自动获取'}`;
} else {
a.title = '未识别到中燃请求参数';
a.message = '未能从剪贴板解析出有效凭据,请确认复制的是 zrds.95007.com 的请求。';
}
a.addAction('确定');
await a.presentAlert();
this.reopenScript();
}
formatMoney(num) {
const val = parseFloat(num);
return isNaN(val) ? '0.00' : val.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
detectCompanyName(obj) {
if (!obj || typeof obj !== 'object') return '';
try {
for (const [k, v] of Object.entries(obj)) {
if (typeof v === 'string' && (v.includes('燃气') || v.includes('中燃') || v.includes('公司')) && !v.includes('http') && v.length < 50) {
return v.trim();
}
}
} catch (_) {}
return '';
}
formatCustCode(code, isShort = false) {
if (!code) return '--';
if (this.settings.maskCustCode === 'true') {
if (code.length >= 8) {
return code.slice(0, 3) + '****' + code.slice(-2);
}
return '****' + code.slice(-2);
}
if (isShort) {
return code.length > 5 ? code.slice(-5) : code;
}
return code;
}
formatCompName(name, isFull = false) {
const raw = (name || (this.gasData && this.gasData.compName) || this.settings.customCompName || '').trim();
if (this.settings.maskCompName === 'true') {
return '中国燃气';
}
if (!raw || raw === 'undefined' || raw === 'null') {
return '中国燃气';
}
if (isFull) {
return raw;
}
return raw.replace(/城市燃气发展有限公司|燃气发展有限公司|有限责任公司|有限公司/g, '');
}
recordDailyBalance() {
try {
const d = this.gasData || {};
const owe = parseFloat(d.oweMoney || '0');
if (owe > 0) return;
const bal = parseFloat(d.countMoney || d.newCountMoney || '0');
if (!isFinite(bal) || bal < 0) return;
const now = new Date();
const key = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
let hist = {};
const raw = this.loadCache('gas_balance.json');
if (raw) {
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === 'object') hist = parsed;
} catch (_) {}
}
hist[key] = Math.round(bal * 100) / 100;
const keys = Object.keys(hist).sort();
if (keys.length > 7) {
keys.slice(0, keys.length - 7).forEach(k => { delete hist[k]; });
}
const ok = this.saveCache('gas_balance.json', JSON.stringify(hist));
if (ok) {
console.log(`[ChinaGas] 余额快照已记录 ${key} = ${hist[key]}(共 ${Object.keys(hist).length} 天)`);
}
} catch (e) {
console.warn('[ChinaGas] 余额快照记录异常: ' + e);
}
}
getYesterdayUsage() {
try {
const d = this.gasData || {};
const owe = parseFloat(d.oweMoney || '0');
if (owe > 0) return null;
const cur = parseFloat(d.countMoney || d.newCountMoney || '0');
if (!isFinite(cur) || cur <= 0) return null;
const now = new Date();
let prev = null;
const y = new Date(now.getTime() - 86400000);
const yKey = `${y.getFullYear()}-${String(y.getMonth() + 1).padStart(2, '0')}-${String(y.getDate()).padStart(2, '0')}`;
const raw = this.loadCache('gas_balance.json');
if (raw) {
try {
const hist = JSON.parse(raw);
if (hist && hist[yKey] !== undefined) {
prev = parseFloat(hist[yKey]);
}
} catch (_) {}
}
if (prev === null || !isFinite(prev)) {
const manual = parseFloat(this.settings.yestBal);
if (isFinite(manual) && manual > 0) prev = manual;
}
if (prev === null || !isFinite(prev)) return null;
const diff = prev - cur;
if (Math.abs(diff) < 0.005) return 0;
return Math.round(diff * 100) / 100;
} catch (_) {
return null;
}
}
getYesterdayUsageInfo() {
if (this.settings.showYestUsage !== 'true') return null;
const v = this.getYesterdayUsage();
if (v === null) return null;
if (v > 0) return { text: v.toFixed(2), isRecharge: false, isZero: false, arrow: '\u2198' };
if (v < 0) {
const a = Math.abs(v);
return { text: String(Math.round(a * 100) / 100), isRecharge: true, isZero: false, arrow: '\u2197' };
}
return { text: '0.00', isRecharge: false, isZero: true, arrow: '\u2192' };
}
getUsageColor(info) {
if (info.isZero) return new Color('#FFB300');
if (info.isRecharge) return new Color('#00D26A');
return new Color('#EF4444');
}
limitUsageDigits(info, maxInt) {
if (!info) return '';
const raw = String(info.text);
const dot = raw.indexOf('.');
const intPart = dot < 0 ? raw : raw.slice(0, dot);
if (intPart.length >= maxInt) return info.arrow + ' ' + intPart;
return info.arrow + ' ' + raw;
}
getBalanceRatio() {
const d = this.gasData || {};
const isOwe = d.oweMoney && parseFloat(d.oweMoney) > 0;
if (isOwe) return 0;
const bal = parseFloat(d.countMoney || d.newCountMoney || '0');
if (isNaN(bal) || bal <= 0) return 0;
const maxLimit = parseFloat(this.settings.balanceLimit) || 500;
return Math.max(0, Math.min(1.0, bal / maxLimit));
}
getCapsuleActiveCount(totalSegments = 10) {
const d = this.gasData || {};
const isOwe = d.oweMoney && parseFloat(d.oweMoney) > 0;
if (isOwe) {
return 1;
}
const ratio = this.getBalanceRatio();
if (ratio <= 0) return 0;
return Math.max(1, Math.round(ratio * totalSegments));
}
getBandStops() {
return ['#B82020', '#F08A1D', '#F5D627', '#F5D627', '#89C853', '#26A67A'];
}
getGlowHex(isOwe) {
// 光晕指示点始终跟随账户状态色带,不受进度条渐变色开关影响
if (isOwe) return '#B82020';
if (this.isOffline) return '#0EA5E9';
return this.sampleBandHex(this.getBalanceRatio());
}
getBalanceTextColor(isOwe) {
if (isOwe) return new Color('#EF4444');
if (this.settings.useGradientBalance === 'false') {
return this.widgetColor || this.getColor();
}
const ratio = this.getBalanceRatio();
return this.colorAt(this.getBarColors(ratio, false), ratio);
}
sampleBandHex(t) {
const stops = this.getBandStops();
// NaN / 非数字一律当作 0,防止索引变 NaN 后取到 undefined 而抛 TypeError
let n = parseFloat(t);
if (!isFinite(n)) n = 0;
const x = Math.max(0, Math.min(1, n)) * (stops.length - 1);
const i = Math.min(stops.length - 2, Math.floor(x));
const f = x - i;
const c1 = parseInt(stops[i].replace('#', ''), 16);
const c2 = parseInt(stops[i + 1].replace('#', ''), 16);
const ch = (shift) => Math.round(((c1 >> shift) & 255) + (((c2 >> shift) & 255) - ((c1 >> shift) & 255)) * f);
return '#' + ((1 << 24) + (ch(16) << 16) + (ch(8) << 8) + ch(0)).toString(16).slice(1).toUpperCase();
}
sampleBand(t) {
return new Color(this.sampleBandHex(t));
}
getBarColors(ratio, isOwe) {
if (isOwe || ratio <= 0) {
return { single: '#B82020', gradient: false };
}
if (this.settings.useGradientBar === 'false') {
const single = this.settings.themeColor || '#FF9500';
return { single: single, gradient: false };
}
return { gradient: true, stops: this.getBandStops() };
}
// 所有进度条样式必须走这里,不得直接调 sampleBand,否则关闭渐变开关会失效
colorAt(colors, t) {
if (!colors || colors.gradient === false) {
const single = (colors && colors.single) || this.settings.themeColor || '#FF9500';
return new Color(single);
}
return this.sampleBand(t);
}
getCardBgColor() {
const userDarkBg = ((this.settings && this.settings.darkBgColor) || '').trim().toUpperCase();
let darkCardHex = '#1C1C1E';
if (userDarkBg === '#1C1C1E' || userDarkBg === '1C1C1E' || userDarkBg === '#1E1E20' || userDarkBg === '#202022') {
darkCardHex = '#242426';
} else if (userDarkBg === '#2C2C2E' || userDarkBg === '2C2C2E') {
darkCardHex = '#343438';
}
return Color.dynamic(new Color('#F4F5F7'), new Color(darkCardHex));
}
getProgressBarBgColor() {
const userDarkBg = ((this.settings && this.settings.darkBgColor) || '').trim().toUpperCase();
let darkHex = '#2C2C2E';
if (userDarkBg === '#1C1C1E' || userDarkBg === '1C1C1E' || userDarkBg === '#1E1E20' || userDarkBg === '#202022') {
darkHex = '#353538';
} else if (userDarkBg === '#2C2C2E' || userDarkBg === '2C2C2E') {
darkHex = '#3E3E42';
}
return Color.dynamic(new Color('#E5E7EB'), new Color(darkHex));
}
addProgressBar(parent, width, height, totalSegments = 10, colors, ratio, thin) {
const style = this.settings.progressStyle || 'square';
const validRatio = Math.max(0, Math.min(1.0, ratio !== undefined ? ratio : this.getBalanceRatio()));
if (style === 'capsule') {
const activeSegs = this.getCapsuleActiveCount(totalSegments);
return this.addCapsuleBar(parent, width, height, totalSegments, activeSegs, colors);
} else if (style === 'smooth') {
return this.addSmoothBar(parent, width, height, colors, validRatio, thin);
} else {
return this.addSquareBar(parent, width, height, totalSegments, colors, validRatio);
}
}
addSquareBar(parent, width, height, totalSegments = 10, colors, ratio) {
let segWidth, blockH;
if (totalSegments <= 10) {
segWidth = width < 135 ? Math.round(10 * this.SCALE) : Math.round(11 * this.SCALE);
blockH = segWidth;
} else {
blockH = Math.round(height * 1.25);
segWidth = Math.floor((width - 3.5 * this.SCALE * (totalSegments - 1)) / totalSegments);
}
const totalSegsW = segWidth * totalSegments;
const gap = totalSegments > 1 ? Math.max(2, (width - totalSegsW) / (totalSegments - 1)) : 0;
const actualTotalW = totalSegsW + gap * (totalSegments - 1);
const bar = parent.addStack();
bar.layoutHorizontally();
bar.centerAlignContent();
bar.size = new Size(actualTotalW, blockH);
bar.setPadding(0, 0, 0, 0);
const corner = Math.max(2.5 * this.SCALE, Math.round(blockH * 0.22));
const bgCol = this.getProgressBarBgColor();
const exact = Math.max(0, Math.min(totalSegments, ratio * totalSegments));
for (let i = 0; i < totalSegments; i++) {
const seg = bar.addStack();
seg.size = new Size(segWidth, blockH);
seg.cornerRadius = corner;
seg.setPadding(0, 0, 0, 0);
const segProgress = Math.max(0, Math.min(1.0, exact - i));
const segColor = this.colorAt(colors, (i + 0.5) / totalSegments);
if (segProgress >= 0.98) {
seg.backgroundColor = segColor;
} else if (segProgress > 0.05) {
seg.layoutHorizontally();
seg.centerAlignContent();
seg.backgroundColor = bgCol;
const fillW = Math.max(1, Math.round(segWidth * segProgress));
const fill = seg.addStack();
fill.size = new Size(fillW, blockH);
fill.cornerRadius = corner;
fill.backgroundColor = segColor;
fill.setPadding(0, 0, 0, 0);
seg.addSpacer();
} else {
seg.backgroundColor = bgCol;
}
if (i < totalSegments - 1) {
bar.addSpacer(gap);
}
}
return bar;
}
addCapsuleBar(parent, width, height, totalSegments = 10, activeSegments = 7, colors) {
const bar = parent.addStack();
bar.layoutHorizontally();
bar.centerAlignContent();
bar.size = new Size(width, height);
const gap = 3.5 * this.SCALE;
const segWidth = (width - gap * (totalSegments - 1)) / totalSegments;
const corner = height / 2;
const bgCol = this.getProgressBarBgColor();
for (let i = 0; i < totalSegments; i++) {
const seg = bar.addStack();
seg.size = new Size(segWidth, height);
seg.cornerRadius = corner;
seg.setPadding(0, 0, 0, 0);
if (i < activeSegments) {
seg.backgroundColor = this.colorAt(colors, (i + 0.5) / totalSegments);
} else {
seg.backgroundColor = bgCol;
}
if (i < totalSegments - 1) {
bar.addSpacer(gap);
}
}
return bar;
}
addSmoothBar(parent, width, height, colors, ratio, thin) {
const slotH = Math.max(1, Math.round(height));
const barW = Math.max(slotH, Math.round(width));
const barH = Math.max(1, Math.round(thin ? slotH * 0.72 : slotH));
const slot = parent.addStack();
slot.layoutHorizontally();
slot.centerAlignContent();
slot.size = new Size(barW, slotH);
slot.setPadding(0, 0, 0, 0);
const bar = slot.addStack();
bar.layoutHorizontally();
bar.centerAlignContent();
bar.size = new Size(barW, barH);
bar.setPadding(0, 0, 0, 0);
bar.cornerRadius = barH / 2;
bar.backgroundColor = this.getProgressBarBgColor();
const validRatio = Math.max(0, Math.min(1, ratio));
const activeWidth = Math.max(barH, Math.round(barW * validRatio));
const img = bar.addImage(
this.drawSmoothGradient(activeWidth, barH, colors, barH / 2, activeWidth)
);
img.imageSize = new Size(activeWidth, barH);
img.respectSizingMode = true;
bar.addSpacer();
return slot;
}
drawSmoothGradient(activeW, h, colors, cornerRadius, totalW) {
const W = totalW || activeW;
const dc = new DrawContext();
dc.size = new Size(W, h);
dc.opaque = false;
dc.respectScreenScale = true;
const r = Math.max(0, Math.min(cornerRadius, h / 2));
const solid = !colors || colors.gradient === false;
const solidColor = solid ? this.colorAt(colors, 0.5) : null;
const COL_STEP = 1;
const rows = Math.max(1, Math.round(h * 2));
const ROW_STEP = h / rows;
const cols = Math.max(1, Math.ceil(W / COL_STEP));
const capsuleInset = (yy, yTop, yBot, rad) => {
if (yy < yTop + rad) {
const dy = yTop + rad - yy;
return rad - Math.sqrt(Math.max(0, rad * rad - dy * dy));
}
if (yy > yBot - rad) {
const dy = yy - (yBot - rad);
return rad - Math.sqrt(Math.max(0, rad * rad - dy * dy));
}
return 0;
};
const fillRad = Math.min(r, activeW / 2);
for (let ri = 0; ri < rows; ri++) {
const y = ri * ROW_STEP;
if (y >= h) break;
const rowH = Math.min(ROW_STEP, h - y);
if (rowH <= 0) continue;
const ySample = Math.min(y + ROW_STEP, h);
const fIn = capsuleInset((y + ySample) / 2, 0, h, fillRad);
const fillL = Math.max(0, fIn);
const fillR = Math.max(fillL, activeW - fIn);
if (fillR <= fillL) continue;
for (let ci = 0; ci < cols; ci++) {
const gx0 = ci * COL_STEP;
const gx1 = Math.min(gx0 + COL_STEP, W);
const fx0 = Math.max(gx0, fillL);
const fx1 = Math.min(gx1, fillR);
if (fx1 <= fx0) continue;
const t = this.colorRatioAt(fx0, fx1, activeW);
dc.setFillColor(solid ? solidColor : this.colorAt(colors, t));
dc.fillRect(new Rect(fx0, y, fx1 - fx0, rowH));
}
}
return dc.getImage();
}
colorRatioAt(x0, x1, activeW) {
if (!(activeW > 0)) return 0;
const t = (x0 + x1) / 2 / activeW;
return t < 0 ? 0 : (t > 1 ? 1 : t);
}
colorRatioAt(x0, x1, activeW) {
if (!(activeW > 0)) return 0;
const t = (x0 + x1) / 2 / activeW;
return t < 0 ? 0 : (t > 1 ? 1 : t);
}
async render() {
await this.init();
const widget = new ListWidget();
await this.getWidgetBackgroundImage(widget);
this.widgetColor = this.getColor();
const intervalMin = parseInt(this.settings.interval) || 360;
widget.refreshAfterDate = new Date(Date.now() + 1000 * 60 * intervalMin);
if (!this.settings.custCode || !this.settings.xMasAppInfo) {
return this.renderGuideWidget(widget);
}
if (!this.gasData) {
return this.renderErrorWidget(widget);
}
if (this.widgetFamily === 'medium') {
return await this.renderMedium(widget);
} else if (this.widgetFamily === 'large') {
return await this.renderLarge(widget);
} else {
return await this.renderSmall(widget);
}
}
async renderSmall(w) {
const pX = 14 * this.SCALE;
const pY = 12 * this.SCALE;
w.setPadding(pY, pX, pY, pX);
w.backgroundColor = this.getWidgetBgColor();
const d = this.gasData || {};
const isOwe = d.oweMoney && parseFloat(d.oweMoney) > 0;
const balanceColor = this.getBalanceTextColor(isOwe);
const subColor = Color.dynamic(new Color('#6B7280'), new Color('#9CA3AF'));
const body = w.addStack();
body.layoutVertically();
const header = body.addStack();
header.centerAlignContent();
const logoImg = await this.getLogoImage(20);
if (logoImg) {
const icon = header.addImage(logoImg);
icon.imageSize = new Size(20 * this.SCALE, 20 * this.SCALE);
icon.cornerRadius = 4 * this.SCALE;
} else {
const flame = SFSymbol.named('flame.fill');
flame.applyHeavyWeight();
const icon = header.addImage(flame.image);
icon.imageSize = new Size(16 * this.SCALE, 16 * this.SCALE);
icon.tintColor = new Color('#FF5722');
}
header.addSpacer(5);
const title = header.addText(this.settings.alias || '中燃在线');
title.font = Font.boldSystemFont(14 * this.SCALE);
title.textColor = this.widgetColor;
header.addSpacer();
const statePill = header.addStack();
statePill.centerAlignContent();
statePill.backgroundColor = this.getCardBgColor();
statePill.cornerRadius = 6 * this.SCALE;
statePill.setPadding(2 * this.SCALE, 6 * this.SCALE, 2 * this.SCALE, 6 * this.SCALE);
const isOweDot = d.oweMoney && parseFloat(d.oweMoney) > 0;
const dotHex = this.getGlowHex(isOweDot);
const glowImg = statePill.addImage(this.drawGlowDot(dotHex, Math.round(36 * this.SCALE)));
glowImg.imageSize = new Size(13 * this.SCALE, 13 * this.SCALE);
statePill.addSpacer(2 * this.SCALE);
const stateText = statePill.addText(isOweDot ? '欠费' : (this.isOffline ? '离线' : '正常'));
stateText.font = Font.systemFont(10.5 * this.SCALE);
stateText.textColor = subColor;
body.addSpacer();
const labelRow = body.addStack();
labelRow.centerAlignContent();
const balLabel = labelRow.addText(isOwe ? '燃气欠费' : '账户余额');
balLabel.font = Font.mediumSystemFont(12 * this.SCALE);
balLabel.textColor = isOwe ? new Color('#EF4444') : subColor;
body.addSpacer(2 * this.SCALE);
const valRow = body.addStack();
valRow.centerAlignContent();
const symText = valRow.addText('¥ ');
symText.font = Font.boldRoundedSystemFont(23 * this.SCALE);
symText.textColor = isOwe ? new Color('#EF4444') : balanceColor;
const valText = valRow.addText(this.formatMoney(d.countMoney || d.newCountMoney || '0.00'));
valText.font = Font.boldRoundedSystemFont(26 * this.SCALE);
valText.textColor = isOwe ? new Color('#EF4444') : balanceColor;
valText.lineLimit = 1;
valText.minimumScaleFactor = 0.6;
const usageS = this.getYesterdayUsageInfo();
if (usageS) {
const uWrap = valRow.addStack();
uWrap.layoutVertically();
uWrap.setPadding(0, 3 * this.SCALE, 0, 0);
uWrap.addSpacer(8 * this.SCALE);
const uTxt = uWrap.addText(this.limitUsageDigits(usageS, 3));
uTxt.font = Font.systemFont(11 * this.SCALE);
uTxt.textColor = this.getUsageColor(usageS);
uTxt.lineLimit = 1;
uTxt.minimumScaleFactor = 0.7;
uTxt.rightAlignText();
}
body.addSpacer(6 * this.SCALE);
const ratio = this.getBalanceRatio();
const barColors = this.getBarColors(ratio, isOwe);
const smallW = this.getWidgetSmallWidth();
const contentW = (smallW - 2 * 14) * this.SCALE;
this.addProgressBar(body, contentW, 6.5 * this.SCALE, 10, barColors, ratio);
body.addSpacer();
const footerCard = body.addStack();
footerCard.layoutVertically();
footerCard.backgroundColor = this.getCardBgColor();
footerCard.cornerRadius = 8 * this.SCALE;
footerCard.setPadding(6 * this.SCALE, 8 * this.SCALE, 6 * this.SCALE, 8 * this.SCALE);
const fRow1 = footerCard.addStack();
fRow1.centerAlignContent();
const gIcon = SFSymbol.named('gauge.badge.plus');
const gImg = fRow1.addImage(gIcon.image);
gImg.imageSize = new Size(11 * this.SCALE, 11 * this.SCALE);
gImg.tintColor = new Color('#3B82F6');
fRow1.addSpacer(3);
const mLabel = fRow1.addText('抄表: ');
mLabel.font = Font.systemFont(10.5 * this.SCALE);
mLabel.textColor = subColor;
const mText = fRow1.addText(`${d.lastRecord || '0'} m³`);
mText.font = Font.systemFont(10.5 * this.SCALE);
mText.textColor = this.widgetColor;
fRow1.addSpacer();
let meterDate = '--';
if (d.lastRecordTime) {
const p = String(d.lastRecordTime).match(/(\d{4})[\-\/\.](\d{1,2})[\-\/\.](\d{1,2})/);
if (p) meterDate = `${p[2]}-${p[3]}`;
else {
const m = String(d.lastRecordTime).match(/(\d{1,2})[\-\/\.](\d{1,2})/);