import { defineStore } from 'pinia'
import { ref } from 'vue'
import { MQTTClient } from '@/utils/mqttClient'
import { useUserStore } from './user'
import { useOrderPositionStore } from '@/stores/modules/orderPosition.ts'
import { formatDate } from '@/utils/timeUtils'
import { initMqttKeyApi } from '@/api/modules/user'

// ============================================================
// 类型声明
// ============================================================

/** 持仓单项数据结构（根据实际业务接口调整字段） */
export interface PositionItem {
  id: string
  code: string
  name?: string
  volume?: number
  direction?: number // 1-做多, 2-做空
  open_price?: number
  current_price?: number
  profit?: number
  take_profit?: number
  stop_loss?: number
  open_time?: string
  [key: string]: any
}

/** 做市商浮动盈亏数据 */
export interface MarketFloatProfitData {
  account_id: string
  float_profit_loss: string
  update_time: string
}

// ============================================================
// Store 定义
// ============================================================

export const useTransactionStore = defineStore('transaction', () => {
  // ------------------ 依赖注入 ------------------
  const mqttClient = new MQTTClient()
  const userStore = useUserStore()
  const orderStore = useOrderPositionStore()

  // ------------------ 状态 ------------------
  /** 持仓列表 */
  const positionList = ref<PositionItem[]>([])
  /** 做市商浮动盈亏数据 Map<account_id, float_profit_loss> */
  const marketFloatProfitMap = ref<Map<string, string>>(new Map())
  /** 做市商平仓盈亏数据 Map<account_id, close_profit_loss> */
  const marketCloseProfitMap = ref<Map<string, string>>(new Map())

  // ------------------ 初始化 ------------------

  /**
   * 初始化行情 MQTT 连接
   * 建立连接 → 订阅主题 → 注册消息回调
   */
  const initMarketConditionsMQTT = async (): Promise<void> => {
    const { redis_key, token } = userStore.userInfo as any
    console.log("initMarketConditionsMQTT", redis_key, token)
    
    try {
      // 先调用 initMqttKey 接口获取 MQTT key
        
      const foreignDeviceNo = sessionStorage.getItem('foreign_device_no') || ''
      const mqttKey = await initMqttKeyApi({ device_no: foreignDeviceNo })
      // 使用 mqttKey 连接
      await mqttClient.connect(import.meta.env.VITE_MQTT_TRANSACTION_HOST as string, {
        username: `${redis_key}`,
        password: `${token}`,
      }) 
    } catch (error) {
      console.error('初始化 MQTT 连接失败:', error)
      return
    }

    await subscribeTheme()
  }

  /**
   * 订阅主题并注册消息处理器
   * 仅保留持仓列表推送（POSITION_FLOATING_BACK）
   */
  const subscribeTheme = async (): Promise<void> => {
    const { id } = userStore.userInfo as any

    if (mqttClient.getConnected()) {
      const topic = `push/${id}`
      await mqttClient.subscribe([topic])

      mqttClient.onTopicMessages({
        [topic]: (_topic: string, msg: string): void => {
          console.log(_topic, msg)

          let [type, data] = msg.split('|')
          switch (type) {
            case 'POSITION_FLOATING_BACK': {
              // 持仓列表回调：交由 orderStore 处理
              orderStore.handlePositionOrderList(data)
              break
            }
            case 'SUBSCRIBE_AMOUNT_FLOATING_BACK': { 
              handleMarketFloatProfit(data)
              break
            }
            default:
              break
          }
        },
      })
    } else {
      setTimeout(subscribeTheme, 30)
    }
  }

  /**
   * 处理做市商浮动盈亏数据
   * 格式：account_id:float_profit_loss:close_profit_loss (例：84:0.000000:0.000000)
   */
  const handleMarketFloatProfit = (data: string): void => {

    if (!data) return
    
    const fields = data.split(':')
    if (fields.length < 3) return

    const account_id = fields[0]
    const float_profit_loss = fields[1] as string
    const close_profit_loss = fields[2] as string

    // 更新浮动盈亏 Map
    marketFloatProfitMap.value.set(account_id, float_profit_loss)
    marketFloatProfitMap.value = new Map(marketFloatProfitMap.value)
    
    // 更新平仓盈亏 Map
    marketCloseProfitMap.value.set(account_id, close_profit_loss)
    marketCloseProfitMap.value = new Map(marketCloseProfitMap.value)
 
  }

  // ------------------ 持仓列表 ------------------

  /**
   * 向服务端请求持仓列表
   * 服务端通过 POSITION_FLOATING_BACK 推送结果
   */
  const getPositionList = (account_id: string): void => {

    console.log('mqttClient.getConnected():', mqttClient.getConnected());
    if (mqttClient.getConnected()) { 
      console.log('持仓 POSITION 持仓列表数据', `POSITION::${account_id}`)
      mqttClient.publish('server/trade', `POSITION::${account_id}`)
    } else {
      setTimeout(getPositionList, 30)
    }
  }

  /**
   * 请求做市商浮动盈亏数据
   * 服务端通过 SUBSCRIBE_AMOUNT_FLOATING 推送结果
   * @param account_id 做市商账户ID
   */
  const requestMarketFloatProfit = (): void => {
    console.log('mqttClient.getConnected():', mqttClient.getConnected());
    if (mqttClient.getConnected()) { 
      mqttClient.publish('server/trade', `SUBSCRIBE_AMOUNT_FLOATING`)
    } else {
      setTimeout(() => requestMarketFloatProfit(), 300)
    }
  }

  /**
   * 关闭订阅，清空数组
   * */
  const disconnect = () => {
    mqttClient?.disconnect()
    positionList.value = []
    marketFloatProfitMap.value.clear()
    marketCloseProfitMap.value.clear()
  }

  /**
   * 检查 MQTT 连接状态
   */
  const isConnected = (): boolean => {
    return mqttClient.getConnected()
  }

  // ------------------ 暴露 ------------------
  return {
    mqttClient,
    positionList,
    marketFloatProfitMap,
    marketCloseProfitMap,
    initMarketConditionsMQTT,
    getPositionList,
    requestMarketFloatProfit,
    disconnect,
    isConnected
  }
})
