import { v4 as uuidv4 } from 'uuid';
import db from '../config/database';
import UsageService from './UsageService';

interface BillingRecord {
  id: string;
  merchantId: string;
  totalAmount: number;
  status: string;
  createdAt: Date;
  paidAt?: Date;
}

interface BillingItem {
  id: string;
  billingId: string;
  feature: string;
  amount: number;
  quantity: number;
  unitPrice: number;
}

interface FeaturePrice {
  [key: string]: number;
}

export class BillingService {
  // 功能价格映射
  private featurePrices: FeaturePrice = {
    'AI_OPTIMIZE': 0.1,
    'ADS_AUTO': 0.2,
    'SYNC_INVENTORY': 0.05,
    'CALCULATE_PROFIT': 0.02
  };
  
  /**
   * 生成商户账单
   */
  async generateBill(merchantId: string): Promise<BillingRecord | null> {
    try {
      // 获取商户的使用量记录
      const usageRecords = await UsageService.getUsageByMerchant(merchantId);
      
      if (usageRecords.length === 0) {
        console.log(`[BillingService] No usage records for merchant ${merchantId}`);
        return null;
      }
      
      // 计算总金额和明细
      let totalAmount = 0;
      const billingItems: BillingItem[] = [];
      
      // 按功能分组计算
      const featureUsageMap = new Map<string, number>();
      
      for (const record of usageRecords) {
        const currentUsage = featureUsageMap.get(record.feature) || 0;
        featureUsageMap.set(record.feature, currentUsage + record.usage);
      }
      
      // 生成账单明细
      for (const [feature, usage] of featureUsageMap.entries()) {
        const unitPrice = this.featurePrices[feature] || 0;
        const amount = usage * unitPrice;
        totalAmount += amount;
        
        billingItems.push({
          id: uuidv4(),
          billingId: '', // 稍后填充
          feature,
          amount,
          quantity: usage,
          unitPrice
        });
      }
      
      // 创建账单记录
      const billingRecord: BillingRecord = {
        id: uuidv4(),
        merchantId,
        totalAmount,
        status: 'pending',
        createdAt: new Date()
      };
      
      // 开始事务
      await db.transaction(async (trx: any) => {
        // 插入账单记录
        await trx('billing_records').insert({
          id: billingRecord.id,
          merchant_id: billingRecord.merchantId,
          total_amount: billingRecord.totalAmount,
          status: billingRecord.status,
          created_at: billingRecord.createdAt
        });
        
        // 插入账单明细
        for (const item of billingItems) {
          item.billingId = billingRecord.id;
          await trx('billing_items').insert({
            id: item.id,
            billing_id: item.billingId,
            feature: item.feature,
            amount: item.amount,
            quantity: item.quantity,
            unit_price: item.unitPrice
          });
        }
      });
      
      console.log(`[BillingService] Generated bill for merchant ${merchantId}: $${totalAmount}`);
      return billingRecord;
    } catch (error) {
      console.error('[BillingService] Error generating bill:', error);
      throw error;
    }
  }
  
  /**
   * 获取商户的账单记录
   */
  async getBillsByMerchant(merchantId: string): Promise<BillingRecord[]> {
    try {
      const records = await db('billing_records')
        .where({ merchant_id: merchantId })
        .orderBy('created_at', 'desc');
      
      return records.map((record: any) => ({
        id: record.id,
        merchantId: record.merchant_id,
        totalAmount: record.total_amount,
        status: record.status,
        createdAt: record.created_at,
        paidAt: record.paid_at
      }));
    } catch (error) {
      console.error('[BillingService] Error getting bills:', error);
      throw error;
    }
  }
  
  /**
   * 获取账单明细
   */
  async getBillItems(billingId: string): Promise<BillingItem[]> {
    try {
      const items = await db('billing_items').where({ billing_id: billingId });
      
      return items.map((item: any) => ({
        id: item.id,
        billingId: item.billing_id,
        feature: item.feature,
        amount: item.amount,
        quantity: item.quantity,
        unitPrice: item.unit_price
      }));
    } catch (error) {
      console.error('[BillingService] Error getting bill items:', error);
      throw error;
    }
  }
  
  /**
   * 标记账单为已支付
   */
  async markBillAsPaid(billingId: string): Promise<BillingRecord> {
    try {
      const now = new Date();
      
      await db('billing_records')
        .where({ id: billingId })
        .update({
          status: 'paid',
          paid_at: now
        });
      
      const updatedBill = await db('billing_records').where({ id: billingId }).first();
      
      console.log(`[BillingService] Marked bill ${billingId} as paid`);
      return {
        id: updatedBill.id,
        merchantId: updatedBill.merchant_id,
        totalAmount: updatedBill.total_amount,
        status: updatedBill.status,
        createdAt: updatedBill.created_at,
        paidAt: updatedBill.paid_at
      };
    } catch (error) {
      console.error('[BillingService] Error marking bill as paid:', error);
      throw error;
    }
  }
  
  /**
   * 获取功能的价格
   */
  getFeaturePrice(feature: string): number {
    return this.featurePrices[feature] || 0;
  }
  
  /**
   * 设置功能价格
   */
  setFeaturePrice(feature: string, price: number): void {
    this.featurePrices[feature] = price;
    console.log(`[BillingService] Updated price for feature ${feature}: $${price}`);
  }
  
  /**
   * 初始化数据库表
   */
  static async initTable(): Promise<void> {
    try {
      // 检查billing_records表是否存在
      const hasBillingTable = await db.schema.hasTable('billing_records');
      if (!hasBillingTable) {
        await db.schema.createTable('billing_records', (table: any) => {
          table.string('id').primary();
          table.string('merchant_id').notNullable();
          table.decimal('total_amount', 10, 2).notNullable();
          table.string('status').notNullable();
          table.timestamp('created_at').notNullable();
          table.timestamp('paid_at');
          table.index('merchant_id');
          table.index('status');
        });
        console.log('[BillingService] Created billing_records table');
      }
      
      // 检查billing_items表是否存在
      const hasBillingItemsTable = await db.schema.hasTable('billing_items');
      if (!hasBillingItemsTable) {
        await db.schema.createTable('billing_items', (table: any) => {
          table.string('id').primary();
          table.string('billing_id').notNullable();
          table.string('feature').notNullable();
          table.decimal('amount', 10, 2).notNullable();
          table.integer('quantity').notNullable();
          table.decimal('unit_price', 10, 2).notNullable();
          table.foreign('billing_id').references('id').inTable('billing_records').onDelete('cascade');
          table.index('billing_id');
          table.index('feature');
        });
        console.log('[BillingService] Created billing_items table');
      }
    } catch (error) {
      console.error('[BillingService] Error initializing tables:', error);
      throw error;
    }
  }

  /**
   * 创建账单
   */
  static async createBill(data: any): Promise<any> {
    try {
      const billId = `bill_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // 创建账单记录
      await db('billing_records').insert({
        id: billId,
        merchant_id: data.merchantId || data.shopId || 'anonymous',
        total_amount: data.totalAmount || data.amount || 0,
        status: 'pending',
        created_at: new Date(),
        paid_at: null
      });
      
      // 创建账单项目
      const items = data.items || [{ feature: data.type || 'FEATURE', amount: data.amount || 0, quantity: 1, unit_price: data.amount || 0 }];
      for (const item of items) {
        await db('billing_items').insert({
          id: `bill_item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          billing_id: billId,
          feature: item.feature,
          amount: item.amount || 0,
          quantity: item.quantity || 1,
          unit_price: item.unitPrice || 0
        });
      }
      
      return { 
        success: true, 
        bill: { id: billId } 
      };
    } catch (error) {
      console.error('[BillingService] Error creating bill:', error);
      return { success: false, error: error instanceof Error ? error.message : 'Unknown error' };
    }
  }
}

export default new BillingService();
