loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
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
//! 模板卡片消息。

use std::fmt;

use serde::Serialize;

use crate::messaging::MessagingError;

use super::{invalid_message, require_non_empty};

const MAX_HORIZONTAL_CONTENT: usize = 6;
const MAX_JUMP_ITEMS: usize = 3;
const MAX_VERTICAL_CONTENT: usize = 4;

/// 卡片来源文字颜色。
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum WeComSourceColor {
    /// 灰色。
    #[default]
    Gray,
    /// 黑色。
    Black,
    /// 红色。
    Red,
    /// 绿色。
    Green,
}

impl WeComSourceColor {
    const fn code(self) -> u8 {
        match self {
            Self::Gray => 0,
            Self::Black => 1,
            Self::Red => 2,
            Self::Green => 3,
        }
    }
}

/// URL 或小程序跳转动作。
#[derive(Clone, Serialize)]
pub struct WeComCardAction {
    #[serde(rename = "type")]
    action_type: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    appid: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pagepath: Option<String>,
}

impl WeComCardAction {
    /// 创建 URL 跳转动作。
    #[must_use]
    pub fn url(url: impl Into<String>) -> Self {
        Self {
            action_type: 1,
            url: Some(url.into()),
            appid: None,
            pagepath: None,
        }
    }

    /// 创建小程序跳转动作。
    #[must_use]
    pub fn mini_program(appid: impl Into<String>) -> Self {
        Self {
            action_type: 2,
            url: None,
            appid: Some(appid.into()),
            pagepath: None,
        }
    }

    /// 设置小程序页面路径。
    #[must_use]
    pub fn with_page_path(mut self, page_path: impl Into<String>) -> Self {
        self.pagepath = some_non_empty(page_path.into());
        self
    }

    fn validate(&self, name: &str) -> Result<(), MessagingError> {
        match self.action_type {
            1 => require_non_empty(name, self.url.as_deref().unwrap_or_default()),
            2 => require_non_empty(name, self.appid.as_deref().unwrap_or_default()),
            _ => Err(invalid_message(format!("{name}类型无效"))),
        }
    }
}

/// 卡片来源样式。
#[derive(Clone, Default, Serialize)]
pub struct WeComCardSource {
    #[serde(skip_serializing_if = "Option::is_none")]
    icon_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc_color: Option<u8>,
}

impl WeComCardSource {
    /// 创建空的来源样式。
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置来源图标 URL。
    #[must_use]
    pub fn with_icon_url(mut self, icon_url: impl Into<String>) -> Self {
        self.icon_url = some_non_empty(icon_url.into());
        self
    }

    /// 设置来源描述。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.desc = some_non_empty(description.into());
        self
    }

    /// 设置来源文字颜色。
    #[must_use]
    pub const fn with_color(mut self, color: WeComSourceColor) -> Self {
        self.desc_color = Some(color.code());
        self
    }
}

/// 模板卡片主标题。
#[derive(Clone, Serialize)]
pub struct WeComMainTitle {
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc: Option<String>,
}

impl WeComMainTitle {
    /// 创建主标题。
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            desc: None,
        }
    }

    /// 设置标题辅助信息。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.desc = some_non_empty(description.into());
        self
    }
}

/// 关键数据样式。
#[derive(Clone, Default, Serialize)]
pub struct WeComEmphasisContent {
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc: Option<String>,
}

impl WeComEmphasisContent {
    /// 创建空的关键数据样式。
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置关键数据。
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = some_non_empty(title.into());
        self
    }

    /// 设置关键数据说明。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.desc = some_non_empty(description.into());
        self
    }
}

/// 引用文献样式。
#[derive(Clone, Default, Serialize)]
pub struct WeComQuoteArea {
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    action: Option<WeComCardAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    quote_text: Option<String>,
}

impl WeComQuoteArea {
    /// 创建空的引用区域。
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置引用区域点击动作。
    #[must_use]
    pub fn with_action(mut self, action: WeComCardAction) -> Self {
        self.action = Some(action);
        self
    }

    /// 设置引用标题。
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = some_non_empty(title.into());
        self
    }

    /// 设置引用文案。
    #[must_use]
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.quote_text = some_non_empty(text.into());
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        if let Some(action) = &self.action {
            action.validate("引用区域跳转参数")?;
        }
        if self.title.is_none() && self.quote_text.is_none() {
            return Err(invalid_message("引用区域标题和文案至少需要一项"));
        }
        Ok(())
    }
}

/// 二级标题与文本条目。
#[derive(Clone, Serialize)]
pub struct WeComHorizontalContent {
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    content_type: Option<u8>,
    keyname: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    value: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    media_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    userid: Option<String>,
}

impl WeComHorizontalContent {
    /// 创建普通文本条目。
    #[must_use]
    pub fn text(key: impl Into<String>, value: impl Into<String>) -> Self {
        Self::new(None, key, Some(value.into()), None, None, None)
    }

    /// 创建 URL 条目。
    #[must_use]
    pub fn url(key: impl Into<String>, value: impl Into<String>, url: impl Into<String>) -> Self {
        Self::new(
            Some(1),
            key,
            Some(value.into()),
            Some(url.into()),
            None,
            None,
        )
    }

    /// 创建文件附件条目。
    #[must_use]
    pub fn file(
        key: impl Into<String>,
        file_name: impl Into<String>,
        media_id: impl Into<String>,
    ) -> Self {
        Self::new(
            Some(2),
            key,
            Some(file_name.into()),
            None,
            Some(media_id.into()),
            None,
        )
    }

    /// 创建成员详情条目。
    #[must_use]
    pub fn user(
        key: impl Into<String>,
        value: impl Into<String>,
        user_id: impl Into<String>,
    ) -> Self {
        Self::new(
            Some(3),
            key,
            Some(value.into()),
            None,
            None,
            Some(user_id.into()),
        )
    }

    fn new(
        content_type: Option<u8>,
        key: impl Into<String>,
        value: Option<String>,
        url: Option<String>,
        media_id: Option<String>,
        userid: Option<String>,
    ) -> Self {
        Self {
            content_type,
            keyname: key.into(),
            value: value.and_then(some_non_empty),
            url: url.and_then(some_non_empty),
            media_id: media_id.and_then(some_non_empty),
            userid: userid.and_then(some_non_empty),
        }
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("卡片水平条目标题", &self.keyname)?;
        match self.content_type {
            None => Ok(()),
            Some(1) => {
                require_non_empty("卡片水平条目 URL", self.url.as_deref().unwrap_or_default())
            }
            Some(2) => require_non_empty(
                "卡片水平条目媒体 ID",
                self.media_id.as_deref().unwrap_or_default(),
            ),
            Some(3) => require_non_empty(
                "卡片水平条目用户 ID",
                self.userid.as_deref().unwrap_or_default(),
            ),
            Some(_) => Err(invalid_message("卡片水平条目类型无效")),
        }
    }
}

/// 卡片跳转指引条目。
#[derive(Clone, Serialize)]
pub struct WeComJumpItem {
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    action: Option<WeComCardAction>,
    title: String,
}

impl WeComJumpItem {
    /// 创建无跳转的指引条目。
    #[must_use]
    pub fn text(title: impl Into<String>) -> Self {
        Self {
            action: None,
            title: title.into(),
        }
    }

    /// 创建 URL 跳转条目。
    #[must_use]
    pub fn url(title: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            action: Some(WeComCardAction::url(url)),
            title: title.into(),
        }
    }

    /// 创建小程序跳转条目。
    #[must_use]
    pub fn mini_program(title: impl Into<String>, appid: impl Into<String>) -> Self {
        Self {
            action: Some(WeComCardAction::mini_program(appid)),
            title: title.into(),
        }
    }

    /// 设置小程序页面路径。
    #[must_use]
    pub fn with_page_path(mut self, page_path: impl Into<String>) -> Self {
        if let Some(action) = self.action.take() {
            self.action = Some(action.with_page_path(page_path));
        }
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("卡片跳转条目标题", &self.title)?;
        if let Some(action) = &self.action {
            action.validate("卡片跳转条目参数")?;
        }
        Ok(())
    }
}

/// 图文展示卡片的图片样式。
#[derive(Clone, Serialize)]
pub struct WeComCardImage {
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    aspect_ratio: Option<f64>,
}

impl WeComCardImage {
    /// 创建卡片图片。
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            aspect_ratio: None,
        }
    }

    /// 设置图片宽高比。
    #[must_use]
    pub const fn with_aspect_ratio(mut self, aspect_ratio: f64) -> Self {
        self.aspect_ratio = Some(aspect_ratio);
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("卡片图片 URL", &self.url)?;
        if let Some(ratio) = self.aspect_ratio
            // 官方示例使用 2.25,因此边界按可用值处理。
            && (!(1.3..=2.25).contains(&ratio) || !ratio.is_finite())
        {
            return Err(invalid_message("卡片图片宽高比必须在 1.3 至 2.25 之间"));
        }
        Ok(())
    }
}

/// 左图右文样式。
#[derive(Clone, Serialize)]
pub struct WeComImageTextArea {
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    action: Option<WeComCardAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc: Option<String>,
    image_url: String,
}

impl WeComImageTextArea {
    /// 创建左图右文样式。
    #[must_use]
    pub fn new(image_url: impl Into<String>) -> Self {
        Self {
            action: None,
            title: None,
            desc: None,
            image_url: image_url.into(),
        }
    }

    /// 设置点击动作。
    #[must_use]
    pub fn with_action(mut self, action: WeComCardAction) -> Self {
        self.action = Some(action);
        self
    }

    /// 设置标题。
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = some_non_empty(title.into());
        self
    }

    /// 设置描述。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.desc = some_non_empty(description.into());
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("左图右文图片 URL", &self.image_url)?;
        if let Some(action) = &self.action {
            action.validate("左图右文跳转参数")?;
        }
        Ok(())
    }
}

/// 图文卡片的二级垂直内容。
#[derive(Clone, Serialize)]
pub struct WeComVerticalContent {
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    desc: Option<String>,
}

impl WeComVerticalContent {
    /// 创建垂直内容。
    #[must_use]
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            desc: None,
        }
    }

    /// 设置描述。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.desc = some_non_empty(description.into());
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("卡片垂直内容标题", &self.title)
    }
}

/// 文本通知模板卡片。
#[derive(Clone, Serialize)]
pub struct WeComTextNoticeCard {
    card_type: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    source: Option<WeComCardSource>,
    main_title: WeComMainTitle,
    #[serde(skip_serializing_if = "Option::is_none")]
    emphasis_content: Option<WeComEmphasisContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    quote_area: Option<WeComQuoteArea>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sub_title_text: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    horizontal_content_list: Vec<WeComHorizontalContent>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    jump_list: Vec<WeComJumpItem>,
    card_action: WeComCardAction,
}

impl WeComTextNoticeCard {
    /// 创建文本通知卡片。
    #[must_use]
    pub const fn new(main_title: WeComMainTitle, card_action: WeComCardAction) -> Self {
        Self {
            card_type: "text_notice",
            source: None,
            main_title,
            emphasis_content: None,
            quote_area: None,
            sub_title_text: None,
            horizontal_content_list: Vec::new(),
            jump_list: Vec::new(),
            card_action,
        }
    }

    /// 设置卡片来源。
    #[must_use]
    pub fn with_source(mut self, source: WeComCardSource) -> Self {
        self.source = Some(source);
        self
    }

    /// 设置关键数据。
    #[must_use]
    pub fn with_emphasis(mut self, emphasis: WeComEmphasisContent) -> Self {
        self.emphasis_content = Some(emphasis);
        self
    }

    /// 设置引用区域。
    #[must_use]
    pub fn with_quote(mut self, quote: WeComQuoteArea) -> Self {
        self.quote_area = Some(quote);
        self
    }

    /// 设置二级普通文本。
    #[must_use]
    pub fn with_subtitle(mut self, subtitle: impl Into<String>) -> Self {
        self.sub_title_text = some_non_empty(subtitle.into());
        self
    }

    /// 追加二级标题与文本条目。
    #[must_use]
    pub fn with_horizontal_content(mut self, content: WeComHorizontalContent) -> Self {
        self.horizontal_content_list.push(content);
        self
    }

    /// 追加跳转指引。
    #[must_use]
    pub fn with_jump(mut self, jump: WeComJumpItem) -> Self {
        self.jump_list.push(jump);
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        if self.main_title.title.trim().is_empty() && self.sub_title_text.is_none() {
            return Err(invalid_message("文本卡片主标题和二级文本至少需要一项"));
        }
        self.card_action.validate("卡片整体跳转参数")?;
        validate_optional_quote(self.quote_area.as_ref())?;
        validate_horizontal(&self.horizontal_content_list)?;
        validate_jumps(&self.jump_list)
    }
}

/// 图文展示模板卡片。
#[derive(Clone, Serialize)]
pub struct WeComNewsNoticeCard {
    card_type: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    source: Option<WeComCardSource>,
    main_title: WeComMainTitle,
    card_image: WeComCardImage,
    #[serde(skip_serializing_if = "Option::is_none")]
    image_text_area: Option<WeComImageTextArea>,
    #[serde(skip_serializing_if = "Option::is_none")]
    quote_area: Option<WeComQuoteArea>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    vertical_content_list: Vec<WeComVerticalContent>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    horizontal_content_list: Vec<WeComHorizontalContent>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    jump_list: Vec<WeComJumpItem>,
    card_action: WeComCardAction,
}

impl WeComNewsNoticeCard {
    /// 创建图文展示卡片。
    #[must_use]
    pub const fn new(
        main_title: WeComMainTitle,
        card_image: WeComCardImage,
        card_action: WeComCardAction,
    ) -> Self {
        Self {
            card_type: "news_notice",
            source: None,
            main_title,
            card_image,
            image_text_area: None,
            quote_area: None,
            vertical_content_list: Vec::new(),
            horizontal_content_list: Vec::new(),
            jump_list: Vec::new(),
            card_action,
        }
    }

    /// 设置卡片来源。
    #[must_use]
    pub fn with_source(mut self, source: WeComCardSource) -> Self {
        self.source = Some(source);
        self
    }

    /// 设置左图右文区域。
    #[must_use]
    pub fn with_image_text_area(mut self, area: WeComImageTextArea) -> Self {
        self.image_text_area = Some(area);
        self
    }

    /// 设置引用区域。
    #[must_use]
    pub fn with_quote(mut self, quote: WeComQuoteArea) -> Self {
        self.quote_area = Some(quote);
        self
    }

    /// 追加二级垂直内容。
    #[must_use]
    pub fn with_vertical_content(mut self, content: WeComVerticalContent) -> Self {
        self.vertical_content_list.push(content);
        self
    }

    /// 追加二级标题与文本条目。
    #[must_use]
    pub fn with_horizontal_content(mut self, content: WeComHorizontalContent) -> Self {
        self.horizontal_content_list.push(content);
        self
    }

    /// 追加跳转指引。
    #[must_use]
    pub fn with_jump(mut self, jump: WeComJumpItem) -> Self {
        self.jump_list.push(jump);
        self
    }

    fn validate(&self) -> Result<(), MessagingError> {
        require_non_empty("图文卡片主标题", &self.main_title.title)?;
        self.card_image.validate()?;
        self.card_action.validate("卡片整体跳转参数")?;
        if let Some(area) = &self.image_text_area {
            area.validate()?;
        }
        validate_optional_quote(self.quote_area.as_ref())?;
        if self.vertical_content_list.len() > MAX_VERTICAL_CONTENT {
            return Err(invalid_message(format!(
                "卡片垂直内容不能超过 {MAX_VERTICAL_CONTENT} 条"
            )));
        }
        self.vertical_content_list
            .iter()
            .try_for_each(WeComVerticalContent::validate)?;
        validate_horizontal(&self.horizontal_content_list)?;
        validate_jumps(&self.jump_list)
    }
}

/// 企业微信模板卡片。
#[derive(Clone, Serialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum WeComTemplateCard {
    /// 文本通知卡片。
    TextNotice(WeComTextNoticeCard),
    /// 图文展示卡片。
    NewsNotice(WeComNewsNoticeCard),
}

impl WeComTemplateCard {
    pub(crate) fn validate(&self) -> Result<(), MessagingError> {
        match self {
            Self::TextNotice(card) => card.validate(),
            Self::NewsNotice(card) => card.validate(),
        }
    }
}

impl fmt::Debug for WeComTemplateCard {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = match self {
            Self::TextNotice(_) => "text_notice",
            Self::NewsNotice(_) => "news_notice",
        };
        formatter
            .debug_struct("WeComTemplateCard")
            .field("kind", &kind)
            .finish_non_exhaustive()
    }
}

impl From<WeComTextNoticeCard> for WeComTemplateCard {
    fn from(card: WeComTextNoticeCard) -> Self {
        Self::TextNotice(card)
    }
}

impl From<WeComNewsNoticeCard> for WeComTemplateCard {
    fn from(card: WeComNewsNoticeCard) -> Self {
        Self::NewsNotice(card)
    }
}

fn validate_optional_quote(quote: Option<&WeComQuoteArea>) -> Result<(), MessagingError> {
    if let Some(quote) = quote {
        quote.validate()?;
    }
    Ok(())
}

fn validate_horizontal(values: &[WeComHorizontalContent]) -> Result<(), MessagingError> {
    if values.len() > MAX_HORIZONTAL_CONTENT {
        return Err(invalid_message(format!(
            "卡片水平内容不能超过 {MAX_HORIZONTAL_CONTENT} 条"
        )));
    }
    values.iter().try_for_each(WeComHorizontalContent::validate)
}

fn validate_jumps(values: &[WeComJumpItem]) -> Result<(), MessagingError> {
    if values.len() > MAX_JUMP_ITEMS {
        return Err(invalid_message(format!(
            "卡片跳转指引不能超过 {MAX_JUMP_ITEMS} 条"
        )));
    }
    values.iter().try_for_each(WeComJumpItem::validate)
}

fn some_non_empty(value: String) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        None
    } else if trimmed.len() == value.len() {
        Some(value)
    } else {
        Some(trimmed.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn text_notice_card_matches_protocol_shape() {
        let card = WeComTemplateCard::from(
            WeComTextNoticeCard::new(
                WeComMainTitle::new("发布完成").with_description("生产环境"),
                WeComCardAction::url("https://example.com/releases/1"),
            )
            .with_horizontal_content(WeComHorizontalContent::text("版本", "1.0.0")),
        );

        assert_eq!(
            serde_json::to_value(card).unwrap(),
            json!({
                "card_type": "text_notice",
                "main_title": { "title": "发布完成", "desc": "生产环境" },
                "horizontal_content_list": [{ "keyname": "版本", "value": "1.0.0" }],
                "card_action": { "type": 1, "url": "https://example.com/releases/1" }
            })
        );
    }

    #[test]
    fn news_card_rejects_invalid_aspect_ratio() {
        let card = WeComTemplateCard::from(WeComNewsNoticeCard::new(
            WeComMainTitle::new("日报"),
            WeComCardImage::new("https://example.com/image.png").with_aspect_ratio(3.0),
            WeComCardAction::url("https://example.com"),
        ));

        let error = card.validate().unwrap_err();
        assert!(error.to_string().contains("宽高比必须在 1.3 至 2.25"));
    }
}