/**
 * 公共参数管理模块
 * 管理API请求的公共参数和签名生成
 */

import md5 from 'md5';

/**
 * 公共参数配置接口
 */
export interface CommonParamsConfig {
  device?: string;
  source?: string;
  appversion?: string;
  signatureKey?: string;
  enableSignature?: boolean;
}

/**
 * 默认公共参数配置
 */
export const DEFAULT_COMMON_PARAMS_CONFIG: CommonParamsConfig = {
  device: 'wap',
  source: 'xinxiuweb',
  appversion: '1.0.0',
  signatureKey: 'asdasgfdwqew',
  enableSignature: true
};

/**
 * 公共参数管理类
 */
export class CommonParamsManager {
  private config: CommonParamsConfig;
  private token: string = '';

  constructor(config?: CommonParamsConfig) {
    this.config = { ...DEFAULT_COMMON_PARAMS_CONFIG, ...config };
  }

  /**
   * 设置配置
   */
  setConfig(config: CommonParamsConfig): void {
    this.config = { ...this.config, ...config };
  }

  /**
   * 设置Token
   */
  setToken(token: string): void {
    this.token = token;
  }

  /**
   * 获取Token
   */
  getToken(): string {
    return this.token;
  }

  /**
   * 生成请求编号
   */
  private generateRequestNumber(): string {
    return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  }

  /**
   * 生成时间戳
   */
  private generateTimestamp(): string {
    return Math.floor(Date.now() / 1000).toString();
  }

  /**
   * 生成签名
   */
  private generateSignature(params: Record<string, any>): string {
    if (!this.config.enableSignature) {
      return '';
    }

    // 复制参数并排序
    const tempParams = { ...params };
    const keys = Object.keys(tempParams).sort();
    
    let signature = '';
    
    // 拼接参数值
    keys.forEach(key => {
      const value = tempParams[key];
      if (value !== undefined && value !== null) {
        if (typeof value === 'object') {
          signature += JSON.stringify(value);
        } else {
          signature += value.toString();
        }
      }
    });

    // 添加签名密钥
    signature += this.config.signatureKey || 'asdasgfdwqew';

    // 双重MD5加密
    return md5(md5(signature));
  }

  /**
   * 获取基础公共参数
   */
  getBaseCommonParams(): Record<string, string> {
    return {
      device: this.config.device || 'wap',
      source: this.config.source || 'xinxiuweb',
      request_number: this.generateRequestNumber(),
      timestamp: this.generateTimestamp(),
      appversion: this.config.appversion || '1.0.0',
      token: this.token
    };
  }

  /**
   * 生成完整的公共参数（包含签名）
   */
  generateCommonParams(customParams?: Record<string, any>, signName?: string): Record<string, any> {
    // 获取基础公共参数
    const baseParams = this.getBaseCommonParams();
    
    // 合并自定义参数
    const allParams = { ...baseParams, ...customParams };
    
    // 生成签名
    if (this.config.enableSignature) {
      allParams.signature = this.generateSignature(allParams);
      
      // 添加签名名称
      if (signName) {
        allParams.sign_name = signName;
      }
    }

    return allParams;
  }

  /**
   * 为请求头添加公共参数
   */
  addCommonParamsToHeaders(headers: Record<string, any>, customParams?: Record<string, any>, signName?: string): Record<string, any> {
    const commonParams = this.generateCommonParams(customParams, signName);
    
    return {
      ...headers,
      ...commonParams
    };
  }

  /**
   * 为请求数据添加公共参数
   */
  addCommonParamsToData(data: any, customParams?: Record<string, any>, signName?: string): any {
    const commonParams = this.generateCommonParams(customParams, signName);
    
    if (typeof data === 'object' && data !== null) {
      return {
        ...data,
        ...commonParams
      };
    }
    
    return {
      data: data,
      ...commonParams
    };
  }
}

/**
 * 默认公共参数管理器实例
 */
export const defaultCommonParamsManager = new CommonParamsManager();

/**
 * 创建公共参数管理器实例
 */
export const createCommonParamsManager = (config?: CommonParamsConfig): CommonParamsManager => {
  return new CommonParamsManager(config);
};

export default CommonParamsManager;