import { defineStore } from 'pinia'
import { ListFrameThrottler } from '@/utils/ListFrameThrottler.ts'
import { ref } from 'vue'
import { formatDate } from '@/utils/timeUtils.ts'

interface PositionObj {
  id?: string
  account?: string
  typeCode?: string
  orderNo?: string
  direction?: string
  lots?: string
  takeProfit?: string
  stopLoss?: string
  entryPrice?: string
  currentPrice?: string
  floatingPL?: string
  margin?: string
  commission?: string
  overnightFee?: string
  timestamp?: string
  singleId?: string | number
  sort?: number
}

export const useOrderPositionStore = defineStore('orderPosition', () => {
  const positionOrderList = ref<PositionObj[]>([])

  const handleInfoListData = (list: PositionObj[]) => {
    if (list?.length) {
      for (let i = 0; i < list.length; i++) {
        const idx = positionOrderList.value.findIndex((item)=>item.id === list[i]?.id)
        if (idx !== -1) {
          positionOrderList.value.splice(idx, 1, list[i] as PositionObj)
        }else{
          positionOrderList.value.push(list[i] as PositionObj)
        }
        
      }
    }

    positionOrderList.value.sort((a: PositionObj, b: PositionObj) => b.sort - a.sort)
  }

  const listFrameThrottler = new ListFrameThrottler(handleInfoListData)

  const handlePositionOrderList = async (item:string) => {
    const fields = item.split(':')
    console.log(fields)
    const positionObj: PositionObj = {
      id: fields[2], // 订单号
      account: fields[0], // 账户id
      typeCode: fields[1], // 品种代码
      orderNo: fields[2], // 订单号
      direction: fields[3], // 1 做多 2 做空
      lots: fields[4], // 手数
      takeProfit: fields[5], // 止盈
      stopLoss: fields[6], // 止损
      entryPrice: fields[7], // 买入价格
      currentPrice: fields[8], // 当前价格
      floatingPL: (fields[9] * 1).toFixed(2), // 浮动盈亏
      margin: (fields[10] * 1).toFixed(2), // 保证金
      commission: (fields[11] * 1).toFixed(2), // 手续费
      overnightFee: (fields[12] * 1).toFixed(2), // 隔夜费
      timestamp:
        fields[13] === -1 || fields[13] === '' || fields[13] === '-1'
          ? ''
          : formatDate(fields[13] * 1000, 'YYYY-MM-DD HH:mm:ss'), // 时间戳
      singleId: fields[14] * 1 === 0 ? '--' : fields[14], // 带单人id
      sort: fields[13] * 1,
    }
    listFrameThrottler.push(positionObj)
  }

  return {
    positionOrderList,
    handlePositionOrderList,
  }
})
