import storage from './storage'
import { STORAGE_KEYS } from './constants'

/**
 * 用户标识管理模块
 */
class Identity {
  constructor() {
    this.distinctId = null
    this.anonymousId = null
    this.userId = null // 真实用户ID（如OpenID）
    this.userProperties = {}
  }

  /**
   * 初始化
   */
  init() {
    this._loadFromStorage()
  }

  /**
   * 从本地存储加载标识
   */
  _loadFromStorage() {
    // 加载匿名ID
    this.anonymousId = storage.get(STORAGE_KEYS.ANONYMOUS_ID)
    if (!this.anonymousId) {
      this.anonymousId = this._generateAnonymousId()
      storage.set(STORAGE_KEYS.ANONYMOUS_ID, this.anonymousId)
    }

    // 加载distinct_id（可能是匿名ID或用户ID）
    this.distinctId = storage.get(STORAGE_KEYS.DISTINCT_ID) || this.anonymousId

    // 加载用户属性缓存
    this.userProperties = storage.getJSON(STORAGE_KEYS.USER_PROPERTIES, {})
  }

  /**
   * 生成匿名ID
   */
  _generateAnonymousId() {
    const timestamp = Date.now().toString(36)
    const random = Math.random().toString(36).substring(2, 10)
    return `anon_${timestamp}_${random}`
  }

  /**
   * 获取当前distinct_id
   */
  getDistinctId() {
    return this.distinctId || this.anonymousId
  }

  /**
   * 获取匿名ID
   */
  getAnonymousId() {
    return this.anonymousId
  }

  /**
   * 设置用户标识（登录时调用）
   * @param {string} userId - 用户ID（如OpenID）
   * @param {object} properties - 用户属性
   * @returns {object} - 返回用于$identify事件的数据
   */
  identify(userId, properties = {}) {
    const previousDistinctId = this.distinctId

    this.userId = userId
    this.distinctId = userId
    storage.set(STORAGE_KEYS.DISTINCT_ID, userId)

    // 更新用户属性
    this.setUserProperties(properties)

    // 返回identify事件所需数据
    return {
      distinctId: userId,
      previousDistinctId: previousDistinctId !== userId ? previousDistinctId : null,
      properties: {
        $set: properties,
        $anon_distinct_id: this.anonymousId,
      },
    }
  }

  /**
   * 设置用户属性
   */
  setUserProperties(properties) {
    this.userProperties = {
      ...this.userProperties,
      ...properties,
    }
    storage.setJSON(STORAGE_KEYS.USER_PROPERTIES, this.userProperties)
  }

  /**
   * 获取用户属性
   */
  getUserProperties() {
    return this.userProperties
  }

  /**
   * 重置用户标识（登出时调用）
   */
  reset() {
    this.userId = null
    this.userProperties = {}

    // 生成新的匿名ID
    this.anonymousId = this._generateAnonymousId()
    this.distinctId = this.anonymousId

    // 更新存储
    storage.set(STORAGE_KEYS.ANONYMOUS_ID, this.anonymousId)
    storage.set(STORAGE_KEYS.DISTINCT_ID, this.distinctId)
    storage.remove(STORAGE_KEYS.USER_PROPERTIES)
  }

  /**
   * 检查用户是否已登录
   */
  isIdentified() {
    return this.userId !== null
  }

  /**
   * 获取用户ID（OpenID等）
   */
  getUserId() {
    return this.userId
  }

  /**
   * 关联匿名ID与用户ID（用于$identify事件）
   */
  getAliasData() {
    return {
      distinct_id: this.distinctId,
      $anon_distinct_id: this.anonymousId,
    }
  }
}

// 导出单例
export default new Identity()