akshare 0.1.0

100% pure Rust implementation of akshare — unified access to Chinese and global financial market data APIs
Documentation
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
//! China macro-economic data from Eastmoney datacenter and Jin10.

use crate::client::AkShareClient;
use crate::error::Result;
use crate::types::MacroDataPoint;

use super::shared::{fetch_em_industry_index, fetch_em_report, fetch_jin10_report};

/// Strip HTML tags and extract text content.
fn extract_html_text(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;
    for ch in html.chars() {
        match ch {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => result.push(ch),
            _ => {}
        }
    }
    result.trim().to_string()
}

/// Fetch macro data from Sina Finance JSONP API (新浪财经-中国宏观经济数据).
async fn fetch_sina_macro(
    client: &AkShareClient,
    cate: &str,
    event: &str,
    name_label: &str,
) -> Result<Vec<MacroDataPoint>> {
    let url = "https://quotes.sina.cn/mac/api/jsonp_v3.php/SINAREMOTECALLCALLBACK/MacPage_Service.get_pagedata";
    let resp_text = client
        .get(url)
        .query(&[
            ("cate", cate),
            ("event", event),
            ("from", "0"),
            ("num", "500"),
            ("condition", ""),
        ])
        .send()
        .await?
        .text()
        .await?;

    // Extract JSON from JSONP wrapper: SINAREMOTECALLCALLBACK({...});
    let json_start = resp_text.find('{').unwrap_or(0);
    let json_end = resp_text.rfind('}').unwrap_or(resp_text.len());
    if json_start >= json_end {
        return Ok(Vec::new());
    }
    let json_str = &resp_text[json_start..=json_end];
    let data: serde_json::Value = serde_json::from_str(json_str)?;

    let mut items = Vec::new();
    if let Some(data_arr) = data.get("data").and_then(|d| d.as_array()) {
        for row in data_arr {
            if let Some(row_obj) = row.as_object() {
                // Try to find a date-like key and a numeric value
                let mut date = String::new();
                let mut value = 0.0f64;
                for (key, val) in row_obj {
                    if key.contains("时间") || key.contains("月份") || key.contains("统计") {
                        date = val.as_str().unwrap_or("").to_string();
                    }
                }
                // Get first numeric value
                for (_key, val) in row_obj {
                    if let Some(v) = val.as_str().and_then(|s| s.parse::<f64>().ok()) {
                        value = v;
                        break;
                    } else if let Some(v) = val.as_f64() {
                        value = v;
                        break;
                    }
                }
                if !date.is_empty() {
                    items.push(MacroDataPoint {
                        date: date.get(..10).unwrap_or(&date).to_string(),
                        value,
                        name: name_label.to_string(),
                    });
                }
            }
        }
    } else if let Some(data_obj) = data.get("data").and_then(|d| d.as_object()) {
        // Handle object-style data (non-cumulative)
        if let Some(arr) = data_obj.get("非累计").and_then(|v| v.as_array()) {
            for row in arr {
                if let Some(row_obj) = row.as_object() {
                    let mut date = String::new();
                    let mut value = 0.0f64;
                    for (key, val) in row_obj {
                        if key.contains("时间") || key.contains("月份") || key.contains("统计")
                        {
                            date = val.as_str().unwrap_or("").to_string();
                        }
                    }
                    for (_key, val) in row_obj {
                        if let Some(v) = val.as_str().and_then(|s| s.parse::<f64>().ok()) {
                            value = v;
                            break;
                        } else if let Some(v) = val.as_f64() {
                            value = v;
                            break;
                        }
                    }
                    if !date.is_empty() {
                        items.push(MacroDataPoint {
                            date: date.get(..10).unwrap_or(&date).to_string(),
                            value,
                            name: name_label.to_string(),
                        });
                    }
                }
            }
        }
    }
    items.sort_by(|a, b| a.date.cmp(&b.date));
    Ok(items)
}

// ---------------------------------------------------------------------------
// Eastmoney datacenter — direct reportName functions
// ---------------------------------------------------------------------------

impl AkShareClient {
    /// China GDP data.
    pub async fn china_gdp(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_GDP", "REPORT_DATE", "China GDP").await
    }

    /// China CPI (Consumer Price Index).
    pub async fn china_cpi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_CPI", "REPORT_DATE", "China CPI").await
    }

    /// China PPI (Producer Price Index).
    pub async fn china_ppi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_PPI", "REPORT_DATE", "China PPI").await
    }

    /// China PMI (Purchasing Managers' Index).
    pub async fn china_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_PMI", "REPORT_DATE", "China PMI").await
    }

    /// China money supply (M0, M1, M2).
    pub async fn china_money_supply(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_CURRENCY_SUPPLY",
            "REPORT_DATE",
            "China Money Supply",
        )
        .await
    }

    /// China trade balance data.
    pub async fn china_trade(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_CUSTOMS", "REPORT_DATE", "China Trade").await
    }

    /// Enterprise commodity price index (企业商品价格指数).
    pub async fn china_goods_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_GOODS_INDEX",
            "REPORT_DATE",
            "China Goods Index",
        )
        .await
    }

    /// Foreign direct investment (外商直接投资).
    pub async fn china_fdi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_FDI", "REPORT_DATE", "China FDI").await
    }

    /// Loan Prime Rate (LPR, 贷款市场报价利率).
    pub async fn china_lpr(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPTA_WEB_RATE", "REPORT_DATE", "China LPR").await
    }

    /// New house price index (新建住宅价格指数).
    pub async fn china_new_house_price(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_HOUSE_PRICE",
            "REPORT_DATE",
            "China New House Price",
        )
        .await
    }

    /// Enterprise boom index (企业景气指数).
    pub async fn china_enterprise_boom_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_BOOM_INDEX",
            "REPORT_DATE",
            "China Enterprise Boom Index",
        )
        .await
    }

    /// National tax receipts (全国税收收入).
    pub async fn china_national_tax_receipts(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(self, "RPT_ECONOMY_TAX", "REPORT_DATE", "China Tax Receipts").await
    }

    /// New financial credit (新增信贷).
    pub async fn china_new_financial_credit(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_RMB_LOAN",
            "REPORT_DATE",
            "China New Credit",
        )
        .await
    }

    /// Foreign exchange and gold reserves (外汇和黄金储备).
    pub async fn china_fx_gold(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_GOLD_CURRENCY",
            "REPORT_DATE",
            "China FX Gold",
        )
        .await
    }

    /// Stock market statistics (股市统计).
    pub async fn china_stock_market_cap(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_STOCK_STATISTICS",
            "REPORT_DATE",
            "China Stock Market Cap",
        )
        .await
    }

    /// Fixed asset investment (固定资产投资).
    pub async fn china_fixed_asset_investment(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_ASSET_INVEST",
            "REPORT_DATE",
            "China Fixed Asset Investment",
        )
        .await
    }

    /// Fiscal revenue (财政收入).
    pub async fn china_fiscal_revenue(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_INCOME",
            "REPORT_DATE",
            "China Fiscal Revenue",
        )
        .await
    }

    /// Foreign exchange loans (外汇贷款).
    pub async fn china_fx_loans(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_FOREX_LOAN",
            "REPORT_DATE",
            "China FX Loans",
        )
        .await
    }

    /// Foreign exchange deposits (外汇存款).
    pub async fn china_fx_deposits(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_FOREX_DEPOSIT",
            "REPORT_DATE",
            "China FX Deposits",
        )
        .await
    }

    /// Consumer confidence index (消费者信心指数).
    pub async fn china_consumer_confidence(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_FAITH_INDEX",
            "REPORT_DATE",
            "China Consumer Confidence",
        )
        .await
    }

    /// Industrial value-added growth (工业增加值).
    pub async fn china_industrial_growth(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_INDUS_GROW",
            "REPORT_DATE",
            "China Industrial Growth",
        )
        .await
    }

    /// Deposit reserve ratio (存款准备金率).
    pub async fn china_reserve_requirement_ratio(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_DEPOSIT_RESERVE",
            "REPORT_DATE",
            "China RRR",
        )
        .await
    }

    /// Total retail sales of consumer goods (社会消费品零售总额).
    pub async fn china_consumer_goods_retail(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_report(
            self,
            "RPT_ECONOMY_TOTAL_RETAIL",
            "REPORT_DATE",
            "China Consumer Goods Retail",
        )
        .await
    }
}

// ---------------------------------------------------------------------------
// Eastmoney datacenter — RPT_INDUSTRY_INDEX with INDICATOR_ID filter
// ---------------------------------------------------------------------------

impl AkShareClient {
    /// Bank financing products (银行理财产品发行数量).
    pub async fn china_bank_financing(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI01516267", "China Bank Financing").await
    }

    /// Insurance income (原保险保费收入).
    pub async fn china_insurance_income(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMM00088870", "China Insurance Income").await
    }

    /// Mobile phone shipments (手机出货量).
    pub async fn china_mobile_number(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00225823", "China Mobile Shipments").await
    }

    /// Vegetable basket index (菜篮子指数).
    pub async fn china_vegetable_basket(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00009275", "China Vegetable Basket").await
    }

    /// Agricultural product price index (农产品批发价格指数).
    pub async fn china_agricultural_product(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00009274", "China Agricultural Product").await
    }

    /// Agricultural index (农业指数).
    pub async fn china_agricultural_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00662543", "China Agricultural Index").await
    }

    /// Energy index (能源指数).
    pub async fn china_energy_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00662539", "China Energy Index").await
    }

    /// Commodity price index (大宗商品价格指数).
    pub async fn china_commodity_price_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00662535", "China Commodity Price Index").await
    }

    /// Yiwu small commodity index (义乌小商品指数).
    pub async fn china_yw_electronic_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00055551", "China Yiwu Index").await
    }

    /// Construction industry index (建筑业指数).
    pub async fn china_construction_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00662541", "China Construction Index").await
    }

    /// Construction material price index (建材价格指数).
    pub async fn china_construction_price_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00237146", "China Construction Price Index").await
    }

    /// Logistics prosperity index (物流景气指数).
    pub async fn china_lpi_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00352262", "China LPI Index").await
    }

    /// BDTI (原油运输指数).
    pub async fn china_bdti_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00107668", "China BDTI Index").await
    }

    /// BSI (超灵便型船运价指数).
    pub async fn china_bsi_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMI00107667", "China BSI Index").await
    }

    /// Real estate index (房地产指数).
    pub async fn china_real_estate(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_em_industry_index(self, "EMM00121987", "China Real Estate").await
    }
}

// ---------------------------------------------------------------------------
// Jin10 datacenter — macro indicators with attr_id
// ---------------------------------------------------------------------------

impl AkShareClient {
    /// China GDP yearly rate (中国GDP年率报告).
    pub async fn china_gdp_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "57", "China GDP Yearly").await
    }

    /// China CPI yearly rate (中国CPI年率报告).
    pub async fn china_cpi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "56", "China CPI Yearly").await
    }

    /// China CPI monthly rate (中国CPI月率报告).
    pub async fn china_cpi_monthly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "72", "China CPI Monthly").await
    }

    /// China PPI yearly rate (中国PPI年率报告).
    pub async fn china_ppi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "60", "China PPI Yearly").await
    }

    /// China exports YoY (以美元计算出口年率).
    pub async fn china_exports_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "66", "China Exports YoY").await
    }

    /// China imports YoY (以美元计算进口年率).
    pub async fn china_imports_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "77", "China Imports YoY").await
    }

    /// China trade balance (以美元计算贸易帐).
    pub async fn china_trade_balance_jin10(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "61", "China Trade Balance").await
    }

    /// China industrial production YoY (规模以上工业增加值年率).
    pub async fn china_industrial_production_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "58", "China Industrial Production YoY").await
    }

    /// China official manufacturing PMI (官方制造业PMI).
    pub async fn china_pmi_jin10(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "65", "China Official PMI").await
    }

    /// China Caixin manufacturing PMI (财新制造业PMI终值).
    pub async fn china_caixin_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "73", "China Caixin PMI").await
    }

    /// China Caixin services PMI (财新服务业PMI).
    pub async fn china_caixin_services_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "67", "China Caixin Services PMI").await
    }

    /// China non-manufacturing PMI (非制造业PMI).
    pub async fn china_non_man_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "75", "China Non-Man PMI").await
    }

    /// China FX reserves yearly (外汇储备).
    pub async fn china_fx_reserves_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "76", "China FX Reserves").await
    }

    /// China M2 yearly (M2年率).
    pub async fn china_m2_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_jin10_report(self, "59", "China M2 Yearly").await
    }
}

// ---------------------------------------------------------------------------
// Jin10 CDN — China interbank rates and FX
// ---------------------------------------------------------------------------

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Jin10CdnCdnResp {
    values: Option<serde_json::Value>,
}

impl AkShareClient {
    /// Shibor rates (上海银行业同业拆借报告).
    pub async fn china_shibor(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/il_1.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(cols) = row.as_object() {
                    for (tenor, col_data) in cols {
                        if let Some(arr) = col_data.as_array() {
                            if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                                items.push(MacroDataPoint {
                                    date: date.clone(),
                                    value: val,
                                    name: format!("Shibor {}", tenor),
                                });
                            }
                        }
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// HIBOR rates (香港同业拆借报告).
    pub async fn china_hibor(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/il_2.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(cols) = row.as_object() {
                    for (tenor, col_data) in cols {
                        if let Some(arr) = col_data.as_array() {
                            if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                                items.push(MacroDataPoint {
                                    date: date.clone(),
                                    value: val,
                                    name: format!("HIBOR {}", tenor),
                                });
                            }
                        }
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// RMB central parity rates (人民币汇率中间价报告).
    pub async fn china_rmb_central_parity(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/exchange_rate.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(cols) = row.as_object() {
                    for (pair, col_data) in cols {
                        if let Some(arr) = col_data.as_array() {
                            if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                                items.push(MacroDataPoint {
                                    date: date.clone(),
                                    value: val,
                                    name: format!("RMB {}", pair),
                                });
                            }
                        }
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// Shenzhen margin trading report (深圳融资融券报告).
    pub async fn china_margin_sz(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/fs_2.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(arr) = row.as_array() {
                    // First element is margin buy amount
                    if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                        items.push(MacroDataPoint {
                            date: date.clone(),
                            value: val,
                            name: "SZ Margin Buy".to_string(),
                        });
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// Shanghai margin trading report (上海融资融券报告).
    pub async fn china_margin_sh(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/fs_1.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(arr) = row.as_array() {
                    if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                        items.push(MacroDataPoint {
                            date: date.clone(),
                            value: val,
                            name: "SH Margin Buy".to_string(),
                        });
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// Shanghai Gold Exchange report (上海黄金交易所报告).
    pub async fn china_sge_report(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://cdn.jin10.com/data_center/reports/sge.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, products) in obj {
                if let Some(arr) = products.as_array() {
                    for product in arr {
                        if let Some(parr) = product.as_array() {
                            // First element is product name, last numeric is volume
                            let name = parr.first().and_then(|v| v.as_str()).unwrap_or("unknown");
                            let volume = parr.get(8).and_then(|v| v.as_f64()).unwrap_or(0.0);
                            items.push(MacroDataPoint {
                                date: date.clone(),
                                value: volume,
                                name: format!("SGE {}", name),
                            });
                        }
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }
}

// Python-compatible aliases
impl AkShareClient {
    pub async fn macro_china_agricultural_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_agricultural_index().await
    }

    pub async fn macro_china_agricultural_product(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_agricultural_product().await
    }

    pub async fn macro_china_bank_financing(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_bank_financing().await
    }

    pub async fn macro_china_bdti_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_bdti_index().await
    }

    pub async fn macro_china_bsi_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_bsi_index().await
    }

    pub async fn macro_china_commodity_price_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_commodity_price_index().await
    }

    pub async fn macro_china_construction_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_construction_index().await
    }

    pub async fn macro_china_construction_price_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_construction_price_index().await
    }

    pub async fn macro_china_consumer_goods_retail(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_consumer_goods_retail().await
    }

    pub async fn macro_china_cpi(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_cpi().await
    }

    pub async fn macro_china_cpi_monthly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_cpi_monthly().await
    }

    pub async fn macro_china_cpi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_cpi_yearly().await
    }

    pub async fn macro_china_energy_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_energy_index().await
    }

    pub async fn macro_china_enterprise_boom_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_enterprise_boom_index().await
    }

    pub async fn macro_china_exports_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_exports_yoy().await
    }

    pub async fn macro_china_fdi(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fdi().await
    }

    pub async fn macro_china_fx_gold(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fx_gold().await
    }

    pub async fn macro_china_fx_reserves_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fx_reserves_yearly().await
    }

    pub async fn macro_china_gdp(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_gdp().await
    }

    pub async fn macro_china_gdp_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_gdp_yearly().await
    }

    pub async fn macro_china_imports_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_imports_yoy().await
    }

    pub async fn macro_china_industrial_production_yoy(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_industrial_production_yoy().await
    }

    pub async fn macro_china_insurance_income(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_insurance_income().await
    }

    pub async fn macro_china_lpi_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_lpi_index().await
    }

    pub async fn macro_china_lpr(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_lpr().await
    }

    pub async fn macro_china_m2_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_m2_yearly().await
    }

    pub async fn macro_china_mobile_number(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_mobile_number().await
    }

    pub async fn macro_china_money_supply(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_money_supply().await
    }

    pub async fn macro_china_national_tax_receipts(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_national_tax_receipts().await
    }

    pub async fn macro_china_new_financial_credit(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_new_financial_credit().await
    }

    pub async fn macro_china_new_house_price(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_new_house_price().await
    }

    pub async fn macro_china_non_man_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_non_man_pmi().await
    }

    pub async fn macro_china_pmi(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_pmi().await
    }

    pub async fn macro_china_ppi(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_ppi().await
    }

    pub async fn macro_china_ppi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_ppi_yearly().await
    }

    pub async fn macro_china_real_estate(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_real_estate().await
    }

    pub async fn macro_china_reserve_requirement_ratio(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_reserve_requirement_ratio().await
    }

    pub async fn macro_china_stock_market_cap(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_stock_market_cap().await
    }

    pub async fn macro_china_vegetable_basket(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_vegetable_basket().await
    }

    pub async fn macro_china_yw_electronic_index(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_yw_electronic_index().await
    }

    pub async fn macro_china_au_report(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_sge_report().await
    }

    pub async fn macro_china_shibor_all(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_shibor().await
    }

    pub async fn macro_china_hk_market_info(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_hibor().await
    }

    pub async fn macro_china_rmb(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_rmb_central_parity().await
    }

    pub async fn macro_china_market_margin_sz(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_margin_sz().await
    }

    pub async fn macro_china_market_margin_sh(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_margin_sh().await
    }

    pub async fn macro_china_trade_balance(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_trade_balance_jin10().await
    }

    pub async fn macro_china_pmi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_pmi_jin10().await
    }

    pub async fn macro_china_cx_pmi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_caixin_pmi().await
    }

    pub async fn macro_china_cx_services_pmi_yearly(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_caixin_services_pmi().await
    }

    pub async fn macro_china_czsr(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fiscal_revenue().await
    }

    pub async fn macro_china_gdzctz(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fixed_asset_investment().await
    }

    pub async fn macro_china_gyzjz(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_industrial_growth().await
    }

    pub async fn macro_china_hgjck(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_trade().await
    }

    pub async fn macro_china_whxd(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fx_loans().await
    }

    pub async fn macro_china_wbck(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_fx_deposits().await
    }

    pub async fn macro_china_xfzxx(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_consumer_confidence().await
    }

    pub async fn macro_china_qyspjg(&self) -> Result<Vec<MacroDataPoint>> {
        self.china_goods_index().await
    }

    /// CNBS macro leverage ratio data (中国宏观杠杆率).
    /// NOTE: The CNBS endpoint returns an Excel (.xlsx) file which requires
    /// a dedicated Excel parsing crate (e.g. calamine). This stub returns
    /// an empty vec until that dependency is added.
    pub async fn macro_cnbs(&self) -> Result<Vec<MacroDataPoint>> {
        Ok(Vec::new())
    }

    /// Sina Finance - central bank balance sheet (央行货币当局资产负债).
    pub async fn macro_china_central_bank_balance(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "fininfo", "8", "China Central Bank Balance").await
    }

    /// Sina Finance - insurance industry data (保险业经营情况).
    pub async fn macro_china_insurance(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "fininfo", "19", "China Insurance").await
    }

    /// Sina Finance - money supply (货币供应量).
    pub async fn macro_china_supply_of_money(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "fininfo", "1", "China Supply of Money").await
    }

    /// Sina Finance - foreign exchange and gold reserves (央行黄金和外汇储备).
    pub async fn macro_china_foreign_exchange_gold(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "fininfo", "5", "China FX Gold Sina").await
    }

    /// Sina Finance - retail price index (商品零售价格指数).
    pub async fn macro_china_retail_price_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "price", "12", "China Retail Price Index").await
    }

    /// Sina Finance - society electricity usage (全社会用电分类情况表).
    pub async fn macro_china_society_electricity(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "6", "China Society Electricity").await
    }

    /// Sina Finance - society traffic volume (全社会客货运输量).
    pub async fn macro_china_society_traffic_volume(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "10", "China Society Traffic").await
    }

    /// Sina Finance - postal and telecommunications (邮电业务基本情况).
    pub async fn macro_china_postal_telecommunicational(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "11", "China Postal Telecom").await
    }

    /// Sina Finance - international tourism FX revenue (国际旅游外汇收入构成).
    pub async fn macro_china_international_tourism_fx(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "15", "China Intl Tourism FX").await
    }

    /// Sina Finance - passenger load factor (民航客座率及载运率).
    pub async fn macro_china_passenger_load_factor(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "20", "China Passenger Load Factor").await
    }

    /// Sina Finance - freight index (航贸运价指数).
    pub async fn macro_china_freight_index(&self) -> Result<Vec<MacroDataPoint>> {
        fetch_sina_macro(self, "industry", "22", "China Freight Index").await
    }

    /// Social financing scale (社会融资规模增量统计).
    pub async fn macro_china_shrzgm(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://data.mofcom.gov.cn/datamofcom/front/gnmy/shrzgmQuery";
        let resp: serde_json::Value = self.post(url).send().await?.json().await?;

        let mut items = Vec::new();
        if let Some(arr) = resp.as_array() {
            for row in arr {
                if let Some(arr_inner) = row.as_array() {
                    if arr_inner.len() < 2 {
                        continue;
                    }
                    let date = arr_inner[0].as_str().unwrap_or("").to_string();
                    if date.is_empty() {
                        continue;
                    }
                    if let Some(val) = arr_inner[6].as_f64() {
                        items.push(MacroDataPoint {
                            date,
                            value: val,
                            name: "Social Financing".to_string(),
                        });
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// RMB loan data (新增人民币贷款) from THS.
    pub async fn macro_rmb_loan(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://data.10jqka.com.cn/macro/loan/";
        let body = self
            .get(url)
            .header("User-Agent", "Mozilla/5.0 (compatible; akshare-rust/0.1)")
            .send()
            .await?
            .text()
            .await?;

        let mut items = Vec::new();
        // Parse HTML table - look for rows with date patterns
        for line in body.lines() {
            let trimmed = line.trim();
            if trimmed.contains("<td") && trimmed.contains("-") {
                // Simple extraction from HTML
                let text = extract_html_text(trimmed);
                if text.contains("-") && text.len() <= 10 {
                    // This might be a date cell
                }
            }
        }
        // Fallback: use regex-like approach on the raw HTML
        let re_rows: Vec<&str> = body.split("<tr").collect();
        for row in &re_rows[1..] {
            let cells: Vec<&str> = row.split("<td").collect();
            if cells.len() >= 3 {
                let date_cell = extract_html_text(cells[1]);
                let val_cell = extract_html_text(cells[2]);
                if date_cell.contains("-") {
                    if let Ok(val) = val_cell.replace(',', "").parse::<f64>() {
                        items.push(MacroDataPoint {
                            date: date_cell,
                            value: val,
                            name: "RMB Loan".to_string(),
                        });
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// RMB deposit data (人民币存款余额) from THS.
    pub async fn macro_rmb_deposit(&self) -> Result<Vec<MacroDataPoint>> {
        let url = "https://data.10jqka.com.cn/macro/rmb/";
        let body = self
            .get(url)
            .header("User-Agent", "Mozilla/5.0 (compatible; akshare-rust/0.1)")
            .send()
            .await?
            .text()
            .await?;

        let mut items = Vec::new();
        let re_rows: Vec<&str> = body.split("<tr").collect();
        for row in &re_rows[1..] {
            let cells: Vec<&str> = row.split("<td").collect();
            if cells.len() >= 3 {
                let date_cell = extract_html_text(cells[1]);
                let val_cell = extract_html_text(cells[2]);
                if date_cell.contains("-") {
                    if let Ok(val) = val_cell.replace(',', "").parse::<f64>() {
                        items.push(MacroDataPoint {
                            date: date_cell,
                            value: val,
                            name: "RMB Deposit".to_string(),
                        });
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// Jin10 energy daily report (中国日度沿海六大电库存数据).
    pub async fn macro_china_daily_energy(&self) -> Result<Vec<MacroDataPoint>> {
        // Use Jin10 CDN for energy daily data
        let url = "https://cdn.jin10.com/data_center/reports/energy.json";
        let resp: Jin10CdnCdnResp = self.get(url).send().await?.json().await?;

        let values = resp.values.unwrap_or_default();
        let mut items = Vec::new();
        if let Some(obj) = values.as_object() {
            for (date, row) in obj {
                if let Some(cols) = row.as_object() {
                    for (col_name, col_data) in cols {
                        if let Some(arr) = col_data.as_array() {
                            if let Some(val) = arr.first().and_then(|v| v.as_f64()) {
                                items.push(MacroDataPoint {
                                    date: date.clone(),
                                    value: val,
                                    name: format!("Energy {}", col_name),
                                });
                            }
                        }
                    }
                }
            }
        }
        items.sort_by(|a, b| a.date.cmp(&b.date));
        Ok(items)
    }

    /// 国家统计局-全国数据 (Python: macro_china_nbs_nation)
    pub async fn macro_china_nbs_nation(
        &self,
        kind: &str,
        path: &str,
        period: &str,
    ) -> Result<Vec<MacroDataPoint>> {
        let dbcode = match kind {
            "月度数据" => "hgyd",
            "季度数据" => "hgjd",
            "年度数据" => "hgnd",
            _ => {
                return Err(crate::error::Error::invalid_input(format!(
                    "invalid kind: {kind}"
                )));
            }
        };
        let url = "https://data.stats.gov.cn/easyquery.htm";
        let resp = self
            .post(url)
            .form(&[
                ("m", "QueryData"),
                ("dbcode", dbcode),
                ("rowcode", "zb"),
                ("colcode", "sj"),
                ("wds", "[]"),
                (
                    "dfwds",
                    format!("[{{\"wdcode\":\"zb\",\"valuecode\":\"{}\"}}]", path).as_str(),
                ),
                ("k1", period),
            ])
            .header("User-Agent", "Mozilla/5.0")
            .send()
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?;
        let items = resp
            .get("returndata")
            .and_then(|r| r.get("datanodes"))
            .and_then(|d| d.as_array())
            .cloned()
            .unwrap_or_default();
        Ok(items
            .iter()
            .map(|v| {
                let date = v
                    .get("wds")
                    .and_then(|w| w.as_array())
                    .and_then(|a| a.get(2))
                    .and_then(|w| w.get("valuecode"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let value = v
                    .get("data")
                    .and_then(|d| d.get("data"))
                    .and_then(|d| d.as_f64())
                    .unwrap_or(0.0);
                MacroDataPoint {
                    date: date.to_string(),
                    value,
                    name: path.to_string(),
                }
            })
            .collect())
    }

    /// 国家统计局-地区数据 (Python: macro_china_nbs_region)
    pub async fn macro_china_nbs_region(
        &self,
        kind: &str,
        path: &str,
        indicator: &str,
        period: &str,
    ) -> Result<Vec<MacroDataPoint>> {
        let dbcode = match kind {
            "分省月度数据" => "fsyd",
            "分省季度数据" => "fsjd",
            "分省年度数据" => "fsnd",
            _ => {
                return Err(crate::error::Error::invalid_input(format!(
                    "invalid kind: {kind}"
                )));
            }
        };
        let url = "https://data.stats.gov.cn/easyquery.htm";
        let dfwds = format!(
            "[{{\"wdcode\":\"zb\",\"valuecode\":\"{}\"}},{{\"wdcode\":\"reg\",\"valuecode\":\"{}\"}}]",
            path, indicator
        );
        let resp = self
            .post(url)
            .form(&[
                ("m", "QueryData"),
                ("dbcode", dbcode),
                ("rowcode", "reg"),
                ("colcode", "sj"),
                ("wds", "[]"),
                ("dfwds", dfwds.as_str()),
                ("k1", period),
            ])
            .header("User-Agent", "Mozilla/5.0")
            .send()
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?;
        let items = resp
            .get("returndata")
            .and_then(|r| r.get("datanodes"))
            .and_then(|d| d.as_array())
            .cloned()
            .unwrap_or_default();
        Ok(items
            .iter()
            .map(|v| {
                let date = v
                    .get("wds")
                    .and_then(|w| w.as_array())
                    .and_then(|a| a.get(2))
                    .and_then(|w| w.get("valuecode"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let value = v
                    .get("data")
                    .and_then(|d| d.get("data"))
                    .and_then(|d| d.as_f64())
                    .unwrap_or(0.0);
                MacroDataPoint {
                    date: date.to_string(),
                    value,
                    name: path.to_string(),
                }
            })
            .collect())
    }

    /// 国家统计局-城镇调查失业率 (Python: macro_china_urban_unemployment)
    pub async fn macro_china_urban_unemployment(&self) -> Result<Vec<MacroDataPoint>> {
        let url =
            "https://data.stats.gov.cn/dg/website/publicrelease/web/external/getEsDataByCidAndDt";
        let payload = serde_json::json!({
            "cid": "ee3b7046b390415b9b7745e3d16f6052",
            "indicatorIds": [
                "3888eac6062945a79c8a27e5f13d4953",
                "1d550f3ec77a463bb607d4a3427e1465",
                "1c1b2d9ab24048bfadc5c7d9510dc663"
            ],
            "daCatalogId": "",
            "das": [{"text": "全国", "value": "000000000000"}],
            "dt": "LAST60"
        });
        let resp = self
            .post(url)
            .json(&payload)
            .header("User-Agent", "Mozilla/5.0")
            .send()
            .await?
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?;
        let items = resp
            .get("data")
            .and_then(|d| d.as_array())
            .cloned()
            .unwrap_or_default();
        Ok(items
            .iter()
            .map(|v| {
                let date = v
                    .get("date")
                    .and_then(|d| d.as_str())
                    .unwrap_or("")
                    .to_string();
                let value = v.get("value").and_then(|d| d.as_f64()).unwrap_or(0.0);
                MacroDataPoint {
                    date,
                    value,
                    name: "城镇调查失业率".to_string(),
                }
            })
            .collect())
    }
}