# All files / modules/subscription subscription.service.ts

41.93% Statements 307/732
87.5% Branches 7/8
13.63% Functions 3/22
41.93% Lines 307/732

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    9491x

    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    6x
    6x

    6x
    6x

    6x

    6x

    6x

    6x
    6x
    6x
    6x
    6x
    6x
    6x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    1x

    1x
    1x
    1x
    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    22x
    22x

    1x
    14x
    14x
    14x

    14x
    14x
    14x
    14x

    14x
    14x
    14x

    14x

    14x
    2x
    12x

    14x

    14x
    14x
    14x
    14x
    14x
    14x
    14x
    14x
    14x
    14x
    14x

    1x

    1x

     import { prisma } from '../../models';
    import { MemberLevel } from '../../types';

    // ============================================
    // TTS服务商成本配置（2026-04-12 更新）
    // ============================================
    export const TTS_COST_CONFIG = {
      // TTS服务商配置
      providers: {
        // 免费方案（科大讯飞基础版）
        iflytek_free: {
          name: '科大讯飞-基础版',
          costPerThousand: 0,  // 免费
          quality: 'standard',
          voiceOptions: 10,
          freeQuota: 100000,  // 10万/月（永久）
          novelRating: 3  // ★★★☆☆
        },
        // 性价比方案（百度基础版）
        baidu_standard: {
          name: '百度智能云-基础版',
          costPerThousand: 3.0,  // ¥3/千字符
          quality: 'standard',
          voiceOptions: 20,
          freeQuota: 2000000,  // 200万/月（首年）
          novelRating: 4  // ★★★★☆
        },
        // 高质量方案（百度精品版）
        baidu_premium: {
          name: '百度智能云-精品版',
          costPerThousand: 15.0,  // ¥15/千字符
          quality: 'premium',
          voiceOptions: 50,
          freeQuota: 0,
          novelRating: 5  // ★★★★★
        },
        // 阿里云方案
        aliyun_plus: {
          name: '阿里云Qwen3-Plus',
          costPerThousand: 12.0,  // ¥12/千字符
          quality: 'high',
          voiceOptions: 30,
          freeQuota: 0,
          novelRating: 5  // ★★★★★
        },
        // 企业方案（火山引擎）
        volcano_premium: {
          name: '火山引擎豆包-标准版',
          costPerThousand: 50.0,  // ¥50/千字符
          quality: 'premium',
          voiceOptions: 40,
          freeQuota: 20000,  // 2万/应用
          novelRating: 5  // ★★★★★
        }
      },

      // AI模型成本配置
      aiModels: {
        deepseek: {
          name: 'DeepSeek V3.2',
          inputCost: 2.0,   // ¥2.0/千token
          outputCost: 8.0,  // ¥8.0/千token
          quality: 'standard',
          default: true
        },
        qwen_plus: {
          name: '通义Qwen Plus',
          inputCost: 4.0,   // ¥4.0/千token
          outputCost: 12.0, // ¥12.0/千token
          quality: 'high'
        },
        doubao_pro: {
          name: '豆包 Pro',
          inputCost: 2.0,   // ¥2.0/千token
          outputCost: 6.0,  // ¥6.0/千token
          quality: 'high'
        }
      },

      // 各等级默认TTS方案
      planTTSProvider: {
        0: 'iflytek_free',      // 免费版：科大讯飞免费
        1: 'baidu_standard',     // 入门版：百度基础
        2: 'baidu_premium',     // 专业版：百度精品
        3: 'volcano_premium'     // 旗舰版：火山引擎
      },

      // 默认AI模型
      defaultAIModel: 'deepseek'
    };

    // ============================================
    // Token成本配置（AI生成成本 + TTS成本）
    // ============================================
    export const TOKEN_COST_CONFIG = {
      // 基础Token成本（DeepSeek V3.2 + 百度基础TTS）
      baseCostPerThousand: 5.0,  // AI: ¥2 + TTS: ¥3 = ¥5/千字符

      // 超额使用单价
      extraPricePerThousand: 6.0,  // 略高于成本价

      // 模型选择
      models: {
        deepseek: {
          name: 'DeepSeek V3.2',
          inputCost: 2.0,      // ¥2.0/千token
          outputCost: 8.0,     // ¥8.0/千token
          quality: 'standard',
          default: true
        },
        qwen_plus: {
          name: '通义 Qwen Plus',
          inputCost: 4.0,      // ¥4.0/千token
          outputCost: 12.0,    // ¥12.0/千token
          quality: 'high',
          extraFee: 1.5        // 每千token额外收费
        },
        doubao_pro: {
          name: '豆包 Pro',
          inputCost: 2.0,      // ¥2.0/千token
          outputCost: 6.0,     // ¥6.0/千token
          quality: 'high'
        }
      }
    };

    // 计算Token生成成本
    export function calculateTokenCost(textLength: number, model: string = 'deepseek'): {
      inputCost: number;
      outputCost: number;
      totalCost: number;
      suggestedPrice: number;
    } {
      const modelConfig = TOKEN_COST_CONFIG.models[model] || TOKEN_COST_CONFIG.models.deepseek;

      // 输入成本
      const inputTokens = textLength; // 1字 ≈ 1 token
      const inputCost = (inputTokens / 1000) * modelConfig.inputCost;

      // 输出成本（音频合成）
      const outputCost = textLength * 0.001 * modelConfig.outputCost * 0.1;

      // 总成本
      const totalCost = inputCost + outputCost;

      // 建议售价（成本 × 1.5，保证50%利润）
      const suggestedPrice = totalCost * 1.5;

      return {
        inputCost: Math.round(inputCost * 100) / 100,
        outputCost: Math.round(outputCost * 100) / 100,
        totalCost: Math.round(totalCost * 100) / 100,
        suggestedPrice: Math.round(suggestedPrice * 100) / 100
      };
    }

    // 默认套餐配置（包月批发+按量零售，2026-04-12定稿）
    export const DEFAULT_PLANS = [
      {
        name: '免费版',
        level: 0,
        priceMonthly: 0,
        priceYearly: 0,
        description: '适合轻度体验',
        features: JSON.stringify([
          '每月10分钟音频',
          '基础音色5种',
          '标准音质'
        ]),
        isRecommended: false,
        sortOrder: 0,
        dailyGenerations: 3,
        perGenerationLimit: 10000,
        monthlyTokens: 1500,
        monthlyMinutes: 10,
        yearlyTokens: null,
        voiceOptions: 5,
        audioQuality: 'standard',
        apiAccess: false,
        batchProcessing: false,
        teamManagement: false,
        overageEnabled: false,
        overagePrice: 0
      },
      {
        name: '入门版',
        level: 1,
        priceMonthly: 19,
        priceYearly: 190,
        description: '适合轻度使用',
        features: JSON.stringify([
          '每月30分钟音频',
          '全部音色',
          '高清音质',
          '超出¥8/分钟'
        ]),
        isRecommended: false,
        sortOrder: 1,
        dailyGenerations: 10,
        perGenerationLimit: 10000,
        monthlyTokens: 4500,
        monthlyMinutes: 30,
        yearlyTokens: null,
        voiceOptions: -1,
        audioQuality: 'high',
        apiAccess: false,
        batchProcessing: false,
        teamManagement: false,
        overageEnabled: true,
        overagePrice: 8.0
      },
      {
        name: '专业版',
        level: 2,
        priceMonthly: 59,
        priceYearly: 590,
        description: '适合内容创作者 ⭐推荐',
        features: JSON.stringify([
          '每月100分钟音频',
          '全部音色+定制音色',
          '高清音质',
          '超出¥7/分钟'
        ]),
        isRecommended: true,
        sortOrder: 2,
        dailyGenerations: -1,
        perGenerationLimit: 10000,
        monthlyTokens: 15000,
        monthlyMinutes: 100,
        yearlyTokens: null,
        voiceOptions: -1,
        audioQuality: 'high',
        apiAccess: false,
        batchProcessing: false,
        teamManagement: false,
        overageEnabled: true,
        overagePrice: 7.0
      },
      {
        name: '旗舰版',
        level: 3,
        priceMonthly: 199,
        priceYearly: 1990,
        description: '适合重度使用',
        features: JSON.stringify([
          '每月400分钟音频',
          '全部音色+定制音色',
          '高清音质',
          'VIP优先队列',
          '超出¥6/分钟'
        ]),
        isRecommended: false,
        sortOrder: 3,
        dailyGenerations: -1,
        perGenerationLimit: 10000,
        monthlyTokens: 60000,
        monthlyMinutes: 400,
        yearlyTokens: null,
        voiceOptions: -1,
        audioQuality: 'high',
        apiAccess: true,
        batchProcessing: false,
        teamManagement: false,
        overageEnabled: true,
        overagePrice: 6.0
      },
      {
        name: '企业版',
        level: 4,
        priceMonthly: 599,
        priceYearly: 5990,
        description: '适合企业用户',
        features: JSON.stringify([
          '每月1500分钟音频',
          '全部功能',
          '专属技术支持',
          '批量处理',
          '团队管理',
          '超出¥5/分钟'
        ]),
        isRecommended: false,
        sortOrder: 4,
        dailyGenerations: -1,
        perGenerationLimit: 10000,
        monthlyTokens: 225000,
        monthlyMinutes: 1500,
        yearlyTokens: null,
        voiceOptions: -1,
        audioQuality: 'high',
        apiAccess: true,
        batchProcessing: true,
        teamManagement: true,
        overageEnabled: true,
        overagePrice: 5.0
      }
    ];

    // 初始化套餐数据
    export async function initializePlans() {
      const existingPlans = await prisma.subscriptionPlan.count();

      if (existingPlans === 0) {
        console.log('初始化订阅套餐数据...');
        for (const plan of DEFAULT_PLANS) {
          await prisma.subscriptionPlan.create({ data: plan });
        }
        console.log('订阅套餐初始化完成');
      }
    }

    // 获取所有套餐列表
    export async function getPlans() {
      const plans = await prisma.subscriptionPlan.findMany({
        where: { isActive: true },
        orderBy: { sortOrder: 'asc' }
      });

      return plans.map(plan => ({
        ...plan,
        priceMonthly: Number(plan.priceMonthly),
        priceYearly: Number(plan.priceYearly),
        features: JSON.parse(plan.features || '[]')
      }));
    }

    // 获取单个套餐详情
    export async function getPlanById(planId: number) {
      const plan = await prisma.subscriptionPlan.findUnique({
        where: { id: planId }
      });

      if (!plan) {
        throw new Error('套餐不存在');
      }

      return {
        ...plan,
        priceMonthly: Number(plan.priceMonthly),
        priceYearly: Number(plan.priceYearly),
        features: JSON.parse(plan.features || '[]')
      };
    }

    // 获取用户当前订阅信息
    export async function getUserSubscription(userId: number) {
      const subscription = await prisma.subscription.findFirst({
        where: {
          userId,
          status: 'active',
          endDate: { gt: new Date() }
        },
        include: {
          plan: true
        },
        orderBy: { endDate: 'desc' }
      });

      return subscription;
    }

    // 获取用户Token余额
    export async function getUserTokenBalance(userId: number) {
      let balance = await prisma.tokenBalance.findUnique({
        where: { userId }
      });

      if (!balance) {
        // 初始化Token余额
        balance = await prisma.tokenBalance.create({
          data: {
            userId,
            totalTokens: 10000, // 默认免费额度
            usedTokens: 0
          }
        });
      }

      const remaining = balance.totalTokens - balance.usedTokens;

      return {
        totalTokens: balance.totalTokens,
        usedTokens: balance.usedTokens,
        remainingTokens: remaining,
        resetDate: balance.resetDate,
        isUnlimited: balance.totalTokens === -1
      };
    }

    // 获取Token使用记录
    export async function getTokenUsageList(userId: number, page: number = 1, pageSize: number = 20) {
      const where = { userId };
      const total = await prisma.tokenUsage.count({ where });

      const list = await prisma.tokenUsage.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize
      });

      return {
        list,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      };
    }

    // 消耗Token
    export async function consumeToken(
      userId: number,
      amount: number,
      type: string,
      contentLength: number,
      description?: string
    ) {
      const balance = await prisma.tokenBalance.findUnique({
        where: { userId }
      });

      if (!balance) {
        throw new Error('用户Token余额不存在');
      }

      if (balance.totalTokens !== -1 && balance.usedTokens + amount > balance.totalTokens) {
        throw new Error('Token余额不足');
      }

      // 更新余额
      await prisma.tokenBalance.update({
        where: { userId },
        data: {
          usedTokens: { increment: amount }
        }
      });

      // 记录使用
      const usage = await prisma.tokenUsage.create({
        data: {
          userId,
          type,
          amount,
          contentLength,
          description
        }
      });

      return usage;
    }

    // 获取用户配额（兼容旧接口）
    export async function getUserQuota(userId: number) {
      const user = await prisma.user.findUnique({
        where: { id: userId }
      });

      if (!user) {
        throw new Error('用户不存在');
      }

      const subscription = await getUserSubscription(userId);
      const tokenBalance = await getUserTokenBalance(userId);

      const memberLevel = user.memberLevel as MemberLevel;
      const levelNames = ['免费版', '基础版', '专业版', '旗舰版'];

      return {
        level: memberLevel,
        levelName: levelNames[memberLevel] || '免费版',
        isValid: subscription !== null,
        expireAt: subscription?.endDate,
        plan: subscription?.plan ? {
          name: subscription.plan.name,
          features: JSON.parse(subscription.plan.features || '[]')
        } : null,
        tokenBalance,
        limits: subscription?.plan ? {
          dailyGenerations: subscription.plan.dailyGenerations,
          perGenerationLimit: subscription.plan.perGenerationLimit,
          monthlyTokens: subscription.plan.monthlyTokens,
          voiceOptions: subscription.plan.voiceOptions,
          audioQuality: subscription.plan.audioQuality
        } : {
          dailyGenerations: 3,
          perGenerationLimit: 2000,
          monthlyTokens: 10000,
          voiceOptions: 5,
          audioQuality: 'standard'
        }
      };
    }

    // 检查用户配额
    export async function checkQuota(userId: number, requiredTokens: number) {
      const quota = await getUserQuota(userId);
      const balance = quota.tokenBalance;

      if (balance.isUnlimited) {
        return { allowed: true, reason: null };
      }

      if (balance.remainingTokens < requiredTokens) {
        return {
          allowed: false,
          reason: 'Token余额不足',
          required: requiredTokens,
          remaining: balance.remainingTokens
        };
      }

      return { allowed: true, reason: null };
    }

    // ============================================
    // 音频时长计费系统（2026-04-12 定稿）
    // ============================================

    export const AUDIO_BILLING_CONFIG = {
      // 成本配置（综合TTS+AI成本）
      costPerMinute: 4.0,  // 成本：¥4/分钟（AI文本生成+TTS合成）

      // 定价策略：包月=批发价，按量=零售价
      pricing: {
        monthly: 5.0,     // 包月批发价：¥5/分钟
        overage: 8.0      // 超额零售价：¥8/分钟
      },

      // 语速配置（字/分钟）
      speakingRate: 150,

      // 各等级每月音频时长配额（分钟）
      monthlyMinutes: {
        0: 10,     // 免费版：10分钟/月
        1: 30,     // 入门版：30分钟/月
        2: 100,    // 专业版：100分钟/月
        3: 400,    // 旗舰版：400分钟/月
        4: 1500    // 企业版：1500分钟/月
      },

      // 各等级超出配额单价（元/分钟），null=不支持超出
      overagePrice: {
        0: null,       // 免费版：不支持超出
        1: 8.0,        // 入门版：¥8/分钟
        2: 7.0,        // 专业版：¥7/分钟
        3: 6.0,        // 旗舰版：¥6/分钟
        4: 5.0         // 企业版：¥5/分钟（最低价）
      }
    };

    // 根据文本长度计算音频时长
    export function calculateAudioDuration(textLength: number): number {
      return Math.ceil(textLength / AUDIO_BILLING_CONFIG.speakingRate);
    }

    // 计算音频生成费用（支持包月配额和按量计费）
    export function calculateAudioCost(
      textLength: number,
      memberLevel: number = 0,
      usedMinutes: number = 0
    ): {
      textLength: number;
      audioMinutes: number;
      inQuotaMinutes: number;
      overageMinutes: number;
      inQuotaPrice: number;      // 配额内价格
      overagePrice: number;       // 超额价格
      totalPrice: number;
      estimatedCost: number;
    } {
      const audioMinutes = calculateAudioDuration(textLength);
      const monthlyMinutes = AUDIO_BILLING_CONFIG.monthlyMinutes[memberLevel] || 10;
      const overagePricePerMinute = AUDIO_BILLING_CONFIG.overagePrice[memberLevel];

      // 计算配额内和超额分钟数
      const remainingQuota = Math.max(0, monthlyMinutes - usedMinutes);
      const inQuotaMinutes = Math.min(audioMinutes, remainingQuota);
      const overageMinutes = Math.max(0, audioMinutes - inQuotaMinutes);

      // 配额内价格（包月批发价）
      const inQuotaPrice = inQuotaMinutes * AUDIO_BILLING_CONFIG.pricing.monthly;

      // 超额价格（按量零售价）
      const overagePrice = overageMinutes > 0 && overagePricePerMinute !== null
        ? overageMinutes * overagePricePerMinute
        : 0;

      const totalPrice = Math.round((inQuotaPrice + overagePrice) * 100) / 100;

      return {
        textLength,
        audioMinutes,
        inQuotaMinutes,
        overageMinutes,
        inQuotaPrice: Math.round(inQuotaPrice * 100) / 100,
        overagePrice: Math.round(overagePrice * 100) / 100,
        totalPrice,
        estimatedCost: audioMinutes * AUDIO_BILLING_CONFIG.costPerMinute
      };
    }

    // 获取用户音频时长余额
    export async function getUserAudioBalance(userId: number) {
      const user = await prisma.user.findUnique({
        where: { id: userId }
      });

      if (!user) {
        throw new Error('用户不存在');
      }

      const memberLevel = user.memberLevel as MemberLevel;
      // 测试账号：memberLevel = -1 表示无限额度
      if (memberLevel === -1) {
        return { memberLevel: -1, totalMinutes: -1, usedMinutes: 0, remainingMinutes: -1, overageEnabled: false, overagePrice: 0, resetDate: null };
      }
      const monthlyMinutes = AUDIO_BILLING_CONFIG.monthlyMinutes[memberLevel] || 10;
      const overageEnabled = AUDIO_BILLING_CONFIG.overagePrice[memberLevel] !== null;
      const overagePrice = AUDIO_BILLING_CONFIG.overagePrice[memberLevel];

      // 检查是否需要重置月度配额
      const now = new Date();
      const resetDate = user.subscriptionResetDate;

      let totalMinutes = monthlyMinutes;
      let usedMinutes = user.usedAudioMinutes || 0;

      // 每月1日重置配额
      if (resetDate) {
        const lastReset = new Date(resetDate);
        if (now.getMonth() !== lastReset.getMonth() || now.getFullYear() !== lastReset.getFullYear()) {
          totalMinutes = monthlyMinutes;
          usedMinutes = 0;
          await prisma.user.update({
            where: { id: userId },
            data: {
              usedAudioMinutes: 0,
              subscriptionResetDate: now
            }
          });
        }
      }

      return {
        memberLevel,
        totalMinutes,
        usedMinutes,
        remainingMinutes: totalMinutes - usedMinutes,
        overageEnabled,
        overagePrice: overagePrice || 0,
        resetDate: user.subscriptionResetDate
      };
    }

    // 检查音频生成配额
    // 检查音频生成配额（只检查月度总配额，无单次限制）
    export async function checkAudioQuota(
      userId: number,
      textLength: number
    ) {
      const audioMinutes = calculateAudioDuration(textLength);
      const balance = await getUserAudioBalance(userId);

      // 测试账号：无限额度
      if (balance.totalMinutes === -1) {
        return { allowed: true, reason: null, audioMinutes, remainingMinutes: -1, totalMinutes: -1 };
      }

      // 免费版不支持超出配额
      if (balance.remainingMinutes < audioMinutes && !balance.overageEnabled) {
        return {
          allowed: false,
          reason: `音频时长不足，本月配额已用完（${balance.totalMinutes}分钟）`,
          audioMinutes,
          remainingMinutes: balance.remainingMinutes,
          totalMinutes: balance.totalMinutes,
          overageEnabled: false
        };
      }

      return {
        allowed: true,
        reason: null,
        audioMinutes,
        inQuotaMinutes: Math.min(audioMinutes, balance.remainingMinutes),
        overageMinutes: Math.max(0, audioMinutes - balance.remainingMinutes),
        remainingMinutes: balance.remainingMinutes,
        totalMinutes: balance.totalMinutes,
        overageEnabled: balance.overageEnabled,
        overagePrice: balance.overagePrice
      };
    }

    // 扣除音频时长（生成完成后调用）
    export async function consumeAudioMinutes(
      userId: number,
      textLength: number,
      description?: string
    ) {
      const audioMinutes = calculateAudioDuration(textLength);
      const balance = await getUserAudioBalance(userId);
      const cost = calculateAudioCost(textLength, balance.memberLevel, balance.usedMinutes);

      // 更新用户已使用时长
      await prisma.user.update({
        where: { id: userId },
        data: {
          usedAudioMinutes: { increment: audioMinutes }
        }
      });

      // 记录使用日志
      const usage = await prisma.tokenUsage.create({
        data: {
          userId,
          type: 'audio_generation',
          amount: audioMinutes,
          contentLength: textLength,
          description: description || `${audioMinutes}分钟音频`
        }
      });

      return {
        usageId: usage.id,
        audioMinutes,
        textLength,
        inQuotaMinutes: cost.inQuotaMinutes,
        overageMinutes: cost.overageMinutes,
        inQuotaPrice: cost.inQuotaPrice,
        overagePrice: cost.overagePrice,
        totalPrice: cost.totalPrice
      };
    }

    // 获取音频生成预估（用于UI展示）
    export async function getAudioEstimate(
      userId: number,
      textLength: number
    ) {
      const balance = await getUserAudioBalance(userId);
      const cost = calculateAudioCost(textLength, balance.memberLevel, balance.usedMinutes);
      const quota = await checkAudioQuota(userId, textLength);

      return {
        // 预估信息
        textLength,
        audioMinutes: cost.audioMinutes,
        inQuotaMinutes: cost.inQuotaMinutes,
        overageMinutes: cost.overageMinutes,
        inQuotaPrice: cost.inQuotaPrice,
        overagePricePerMinute: cost.overagePrice,
        estimatedPrice: cost.totalPrice,
        estimatedCost: cost.estimatedCost,

        // 用户配额
        remainingMinutes: balance.remainingMinutes,
        totalMinutes: balance.totalMinutes,
        usedMinutes: balance.usedMinutes,

        // 计费策略
        overageEnabled: balance.overageEnabled,
        overagePrice: balance.overagePrice,

        // 是否允许生成
        canGenerate: quota.allowed,
        reason: quota.reason,

        // 显示文本
        displayText: quota.allowed
          ? cost.overageMinutes > 0
            ? `预计${cost.audioMinutes}分钟（配额${cost.inQuotaMinutes}分钟+超出${cost.overageMinutes}分钟），约¥${cost.totalPrice}`
            : `预计${cost.audioMinutes}分钟，约¥${cost.totalPrice}`
          : quota.reason
      };
    }

    // ============================================
    // 书籍生成配额系统（字数预估 + 过程监控 + 中断保存）
    // ============================================

    import { estimateBookWords as estimateBookWordsFromConfig, getBookTypeConfig as getBookTypeConfigFromNew } from '../book-generator/book-type-config';

    // 根据书籍规模计算预估字数（使用统一配置）
    export function estimateBookWords(bookScale: string): { min: number; max: number; avg: number } {
      return estimateBookWordsFromConfig(bookScale);
    }

    // 根据预估字数计算预估音频时长
    export function estimateAudioMinutesFromWords(wordCount: number): number {
      return Math.ceil(wordCount / AUDIO_BILLING_CONFIG.speakingRate);
    }

    // 检查书籍生成的配额（生成前预估）
    export async function checkBookGenerationQuota(
      userId: number,
      bookScale: string
    ): Promise<{
      allowed: boolean;
      reason: string | null;
      // 预估信息
      estimatedWords: { min: number; max: number; avg: number };
      estimatedAudioMinutes: { min: number; max: number; avg: number };
      // 配额信息
      quota: {
        totalMinutes: number;
        usedMinutes: number;
        remainingMinutes: number;
        overageEnabled: boolean;
        overagePrice: number;
      };
      // 费用预估
      costEstimate: {
        inQuotaMinutes: number;
        overageMinutes: number;
        estimatedPrice: number;
        displayText: string;
      };
    }> {
      const wordEstimate = estimateBookWords(bookScale);
      const audioMinutes = estimateAudioMinutesFromWords(wordEstimate.avg);
      const balance = await getUserAudioBalance(userId);

      // 免费版且预估超出配额
      if (!balance.overageEnabled && balance.remainingMinutes < audioMinutes) {
        return {
          allowed: false,
          reason: `免费版不支持超出配额，请升级套餐或减少书籍规模`,
          estimatedWords: wordEstimate,
          estimatedAudioMinutes: {
            min: estimateAudioMinutesFromWords(wordEstimate.min),
            max: estimateAudioMinutesFromWords(wordEstimate.max),
            avg: audioMinutes
          },
          quota: {
            totalMinutes: balance.totalMinutes,
            usedMinutes: balance.usedMinutes,
            remainingMinutes: balance.remainingMinutes,
            overageEnabled: balance.overageEnabled,
            overagePrice: balance.overagePrice
          },
          costEstimate: {
            inQuotaMinutes: balance.remainingMinutes,
            overageMinutes: 0,
            estimatedPrice: 0,
            displayText: `预估需要${audioMinutes}分钟，超出您的配额${balance.remainingMinutes}分钟`
          }
        };
      }

      // 计算费用
      const inQuotaMinutes = Math.min(audioMinutes, balance.remainingMinutes);
      const overageMinutes = Math.max(0, audioMinutes - balance.remainingMinutes);
      const estimatedPrice = overageMinutes > 0 && balance.overagePrice
        ? overageMinutes * balance.overagePrice
        : 0;

      return {
        allowed: true,
        reason: null,
        estimatedWords: wordEstimate,
        estimatedAudioMinutes: {
          min: estimateAudioMinutesFromWords(wordEstimate.min),
          max: estimateAudioMinutesFromWords(wordEstimate.max),
          avg: audioMinutes
        },
        quota: {
          totalMinutes: balance.totalMinutes,
          usedMinutes: balance.usedMinutes,
          remainingMinutes: balance.remainingMinutes,
          overageEnabled: balance.overageEnabled,
          overagePrice: balance.overagePrice
        },
        costEstimate: {
          inQuotaMinutes,
          overageMinutes,
          estimatedPrice: Math.round(estimatedPrice * 100) / 100,
          displayText: overageMinutes > 0
            ? `预估${audioMinutes}分钟（配额${inQuotaMinutes}分钟+超出${overageMinutes}分钟），预计额外费用¥${estimatedPrice}`
            : `预估${audioMinutes}分钟，配额内免费`
        }
      };
    }

    // 检查当前额度是否足够生成指定字数（用于生成过程监控）
    export async function checkQuotaForWords(userId: number, wordCount: number): Promise<{
      sufficient: boolean;
      reason: string | null;
      currentWords: number;
      maxAllowedWords: number;
      audioMinutesNeeded: number;
      remainingMinutes: number;
    }> {
      const audioMinutesNeeded = estimateAudioMinutesFromWords(wordCount);
      const balance = await getUserAudioBalance(userId);

      if (!balance.overageEnabled && balance.remainingMinutes < audioMinutesNeeded) {
        return {
          sufficient: false,
          reason: `额度不足：需要${audioMinutesNeeded}分钟，您剩余${balance.remainingMinutes}分钟`,
          currentWords: wordCount,
          maxAllowedWords: balance.remainingMinutes * AUDIO_BILLING_CONFIG.speakingRate,
          audioMinutesNeeded,
          remainingMinutes: balance.remainingMinutes
        };
      }

      return {
        sufficient: true,
        reason: null,
        currentWords: wordCount,
        maxAllowedWords: balance.remainingMinutes * AUDIO_BILLING_CONFIG.speakingRate,
        audioMinutesNeeded,
        remainingMinutes: balance.remainingMinutes
      };
    }

    // 获取当前用户已生成的字数（用于断点续传）
    export async function getGeneratedWordCount(bookId: string): Promise<number> {
      const book = await prisma.book.findUnique({
        where: { id: parseInt(bookId) },
        include: { chapters: true }
      });

      if (!book) return 0;

      // 统计已完成章节的字数（genStage 含内容/音频/视频阶段都算已完成）
      const completedGenStages = ['content_completed', 'audio_completed', 'audio_generating', 'video_generating', 'video_completed'];
      const completedWords = book.chapters
        .filter(c => completedGenStages.includes(c.genStage))
        .reduce((sum, c) => sum + (c.wordCount || 0), 0);

      return completedWords;
    }

    // 记录生成中断状态（用于断点续传）
    export async function markGenerationInterrupted(bookId: string, lastChapterNumber: number, currentWords: number): Promise<void> {
      await prisma.book.update({
        where: { id: parseInt(bookId) },
        data: {
          genStage: 'failed',
          failedStage: 'content_generating',
          errorMsg: `额度不足中断，已生成${currentWords}字`,
          progress: 0 // 重置进度，下次生成时重新计算
        }
      });

      console.log(`[QuotaCheck] 书籍${bookId}生成中断：已完成${currentWords}字，最后章节${lastChapterNumber}`);
    }