import { defineStore } from 'pinia'
import { ref } from 'vue'
import { get, postForm } from '@/utils/request'

export interface StatementCoin {
  fullName: string
  code: string
  name: string
  sort: number
}

export interface StatementType {
  index: number
  typeId: string
  name: string
}

export interface AssetStatement {
  id: string
  fee: string
  flag: string
  type: string
  amount: string
  symbol: string
  realFee: string
  rebateId: string
  accountId: string
  createTime: string
  direction: string
  discountFee: string
}

export const useStatementStore = defineStore('statement', () => {
  const coins = ref<StatementCoin[]>([])
  const types = ref<StatementType[]>([])
  const records = ref<AssetStatement[]>([])
  const filterLoading = ref(false)
  const recordLoading = ref(false)
  const page = ref(1)
  const hasMore = ref(true)

  const filterCoin = ref('')
  const filterType = ref('')
  const filterStart = ref('')
  const filterEnd = ref('')

  async function loadFilters() {
    if (coins.value.length && types.value.length) return
    filterLoading.value = true
    try {
      const [c, t] = await Promise.all([
        get<StatementCoin[]>('/uc/asset/transaction/coin'),
        get<StatementType[]>('/uc/asset/transaction/type'),
      ])
      coins.value = (c ?? []).sort((a, b) => a.sort - b.sort)
      types.value = (t ?? []).map(item => ({
        ...item,
        typeId: String(item.index),
      }))
    } finally {
      filterLoading.value = false
    }
  }

  /** 与 Flutter AssetService.getStatementList、FuturesStore.fetchFundingRecords 一致：data 为 { content, last? } */
  function unwrapTransactionAllPayload(raw: unknown): { list: AssetStatement[]; last: boolean } {
    if (Array.isArray(raw)) {
      return { list: raw as AssetStatement[], last: false }
    }
    if (raw && typeof raw === 'object') {
      const o = raw as { content?: unknown; last?: unknown }
      const content = o.content
      const list = Array.isArray(content) ? (content as AssetStatement[]) : []
      const last = o.last === true || o.last === 'true'
      return { list, last }
    }
    return { list: [], last: true }
  }

  async function search(refresh = false) {
    if (refresh) {
      page.value = 1
      records.value = []
      hasMore.value = true
    }
    if (!hasMore.value || recordLoading.value) return
    recordLoading.value = true
    try {
      const PAGE_SIZE = 20
      const raw = await postForm<unknown>('/uc/asset/transaction/all', {
        type: filterType.value,
        symbol: filterCoin.value,
        startTime: filterStart.value,
        endTime: filterEnd.value,
        pageNo: String(page.value),
        pageSize: String(PAGE_SIZE),
      })
      const { list, last } = unwrapTransactionAllPayload(raw)
      records.value = refresh ? list : [...records.value, ...list]
      if (last || list.length < PAGE_SIZE) {
        hasMore.value = false
      } else {
        page.value++
      }
    } catch (e) {
      throw e
    } finally {
      recordLoading.value = false
    }
  }

  function reset() {
    filterCoin.value = ''
    filterType.value = ''
    filterStart.value = ''
    filterEnd.value = ''
  }

  return {
    coins, types, records, filterLoading, recordLoading, hasMore,
    filterCoin, filterType, filterStart, filterEnd,
    loadFilters, search, reset,
  }
})
