import { Injectable, signal } from '@angular/core';
import { Observable, of, delay, switchMap, catchError } from 'rxjs';

export interface MiniprogramPaymentResult {
  success: boolean;
  transactionId: string;
  amount: number;
  paymentTime: Date;
  payerInfo: {
    openId: string;
    nickname?: string;
    avatar?: string;
  };
  settlementId: string;
  error?: string;
}

export interface ImageDecryptionResult {
  success: boolean;
  decryptedImageUrl: string;
  originalImageId: string;
  decryptionTime: Date;
  error?: string;
}

export interface NotificationResult {
  success: boolean;
  messageId: string;
  sentTime: Date;
  recipient: string;
  error?: string;
}

@Injectable({
  providedIn: 'root'
})
export class MiniprogramPaymentService {
  private isProcessing = signal(false);
  private paymentQueue = signal<string[]>([]);

  constructor() {}

  /**
   * 监听小程序支付完成事件
   */
  onPaymentCompleted(): Observable<MiniprogramPaymentResult> {
    // 模拟支付完成事件监听
    return new Observable(observer => {
      // 实际实现中会监听微信小程序支付回调
      console.log('开始监听小程序支付完成事件...');
      
      // 模拟支付完成事件
      setTimeout(() => {
        const mockPaymentResult: MiniprogramPaymentResult = {
          success: true,
          transactionId: `MP${Date.now()}`,
          amount: Math.floor(Math.random() * 50000) + 10000,
          paymentTime: new Date(),
          payerInfo: {
            openId: `openid_${Date.now()}`,
            nickname: '客户用户',
            avatar: 'https://example.com/avatar.jpg'
          },
          settlementId: `settlement_${Date.now()}`
        };
        
        observer.next(mockPaymentResult);
      }, 2000);
    });
  }

  /**
   * 处理支付完成后的自动化流程
   */
  processPaymentCompletedFlow(paymentResult: MiniprogramPaymentResult): Observable<boolean> {
    if (!paymentResult.success) {
      return of(false);
    }

    this.isProcessing.set(true);
    this.paymentQueue.update(queue => [...queue, paymentResult.settlementId]);

    console.log(`开始处理支付完成流程: ${paymentResult.transactionId}`);

    return this.decryptAndSendImages(paymentResult).pipe(
      switchMap(decryptResult => {
        if (decryptResult.success) {
          return this.sendPaymentCompletedNotification(paymentResult, decryptResult);
        }
        return of({ success: false, error: '图片解密失败' });
      }),
      switchMap(notificationResult => {
        if (notificationResult.success) {
          return this.updateSettlementStatus(paymentResult.settlementId, 'completed');
        }
        return of(false);
      }),
      catchError(error => {
        console.error('支付完成流程处理失败:', error);
        return of(false);
      }),
      delay(1000), // 模拟处理时间
      switchMap(result => {
        this.isProcessing.set(false);
        this.paymentQueue.update(queue => 
          queue.filter(id => id !== paymentResult.settlementId)
        );
        return of(result);
      })
    );
  }

  /**
   * 解密并发送大图给客户
   */
  private decryptAndSendImages(paymentResult: MiniprogramPaymentResult): Observable<ImageDecryptionResult> {
    console.log(`开始解密图片，结算ID: ${paymentResult.settlementId}`);

    return new Observable<ImageDecryptionResult>(observer => {
      // 模拟图片解密过程
      setTimeout(() => {
        const decryptResult: ImageDecryptionResult = {
          success: true,
          decryptedImageUrl: `https://example.com/decrypted/${paymentResult.settlementId}/high-res-image.jpg`,
          originalImageId: `img_${paymentResult.settlementId}`,
          decryptionTime: new Date()
        };

        console.log('图片解密完成:', decryptResult);
        observer.next(decryptResult);
        observer.complete();
      }, 1500);
    }).pipe(
      catchError(error => {
        console.error('图片解密失败:', error);
        return of({
          success: false,
          decryptedImageUrl: '',
          originalImageId: '',
          decryptionTime: new Date(),
          error: error.message
        });
      })
    );
  }

  /**
   * 发送支付完成通知
   */
  private sendPaymentCompletedNotification(
    paymentResult: MiniprogramPaymentResult, 
    decryptResult: ImageDecryptionResult
  ): Observable<NotificationResult> {
    console.log('发送支付完成通知...');

    const notificationContent = {
      title: '尾款支付成功',
      message: `您的尾款 ¥${paymentResult.amount} 已成功支付，大图已解锁并发送至您的微信。`,
      imageUrl: decryptResult.decryptedImageUrl,
      paymentInfo: {
        amount: paymentResult.amount,
        transactionId: paymentResult.transactionId,
        paymentTime: paymentResult.paymentTime
      }
    };

    return new Observable<NotificationResult>(observer => {
      // 模拟发送通知
      setTimeout(() => {
        const notificationResult: NotificationResult = {
          success: true,
          messageId: `msg_${Date.now()}`,
          sentTime: new Date(),
          recipient: paymentResult.payerInfo.openId
        };

        console.log('通知发送成功:', notificationResult);
        console.log('通知内容:', notificationContent);
        
        observer.next(notificationResult);
        observer.complete();
      }, 800);
    }).pipe(
      catchError(error => {
        console.error('通知发送失败:', error);
        return of({
          success: false,
          messageId: '',
          sentTime: new Date(),
          recipient: paymentResult.payerInfo.openId,
          error: error.message
        });
      })
    );
  }

  /**
   * 更新结算状态
   */
  private updateSettlementStatus(settlementId: string, status: string): Observable<boolean> {
    console.log(`更新结算状态: ${settlementId} -> ${status}`);

    return new Observable<boolean>(observer => {
      // 模拟更新结算状态
      setTimeout(() => {
        console.log('结算状态更新成功');
        observer.next(true);
        observer.complete();
      }, 500);
    }).pipe(
      catchError(error => {
        console.error('结算状态更新失败:', error);
        return of(false);
      })
    );
  }

  /**
   * 启动自动化监听
   */
  startAutomationListener(): void {
    console.log('启动小程序支付自动化监听...');
    
    this.onPaymentCompleted().subscribe(paymentResult => {
      console.log('检测到支付完成事件:', paymentResult);
      
      this.processPaymentCompletedFlow(paymentResult).subscribe(success => {
        if (success) {
          console.log('自动化流程处理成功');
        } else {
          console.error('自动化流程处理失败');
        }
      });
    });
  }

  /**
   * 停止自动化监听
   */
  stopAutomationListener(): void {
    console.log('停止小程序支付自动化监听');
    this.isProcessing.set(false);
    this.paymentQueue.set([]);
  }

  /**
   * 获取处理状态
   */
  getProcessingStatus(): boolean {
    return this.isProcessing();
  }

  /**
   * 获取处理队列
   */
  getProcessingQueue(): string[] {
    return this.paymentQueue();
  }

  /**
   * 手动触发支付完成流程（用于测试）
   */
  triggerTestPaymentFlow(settlementId: string, amount: number): Observable<boolean> {
    const mockPaymentResult: MiniprogramPaymentResult = {
      success: true,
      transactionId: `TEST_${Date.now()}`,
      amount: amount,
      paymentTime: new Date(),
      payerInfo: {
        openId: `test_openid_${Date.now()}`,
        nickname: '测试用户',
        avatar: 'https://example.com/test-avatar.jpg'
      },
      settlementId: settlementId
    };

    return this.processPaymentCompletedFlow(mockPaymentResult);
  }

  /**
   * 获取支持的支付方式
   */
  getSupportedPaymentMethods(): string[] {
    return ['微信小程序支付', '微信H5支付', '微信扫码支付'];
  }

  /**
   * 验证支付结果
   */
  validatePaymentResult(paymentResult: MiniprogramPaymentResult): { valid: boolean, errors: string[] } {
    const errors: string[] = [];

    if (!paymentResult.transactionId) {
      errors.push('缺少交易ID');
    }

    if (!paymentResult.amount || paymentResult.amount <= 0) {
      errors.push('支付金额无效');
    }

    if (!paymentResult.payerInfo?.openId) {
      errors.push('缺少支付者信息');
    }

    if (!paymentResult.settlementId) {
      errors.push('缺少结算ID');
    }

    return {
      valid: errors.length === 0,
      errors
    };
  }
}