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

// ── 链上充值（新接口，见 docs/接口文档-2026-05-13.md）────────────────

export interface RechargeParentCoin {
  name: string
  nameCn: string
  unit: string
  status: number
  canRecharge: number
  sort: number
}

export interface RechargeChildGroup {
  coin: {
    name: string
    nameCn: string
    unit: string
    parentCoinName: string
    canRecharge: number
    sort: number
  }
  networkConfigs: {
    id: number
    coinName: string
    network: { id: number; name: string; protocol: string; status: number }
    contractAddress: string
    rechargeAddress: string
    sort: number
  }[]
}

/** 扁平化后的可选主网一行（选网 + 创建订单用） */
export interface RechargeFlatNetworkOption {
  coinName: string
  coinNameCn: string
  networkConfigId: number
  networkName: string
  protocol: string
  contractAddress: string
  rechargeAddress: string
}

export interface RechargeOrderDetail {
  id: number
  orderNo: string
  memberId?: number
  coinName: string
  networkConfigId?: number
  networkName: string
  rechargeAddress: string
  amount: string
  txHash: string | null
  status: number
  remark?: string | null
  createTime: string
  submitHashTime?: string | null
  updateTime?: string | null
}

/** 列表单项（与详情字段对齐） */
export interface RechargeOrderListItem {
  id: string
  orderNo: string
  coinName: string
  networkName: string
  rechargeAddress: string
  amount: string
  txHash: string | null
  status: number
  createTime: string
  submitHashTime: string | null
  updateTime: string
}

function flattenNetworkOptions(groups: RechargeChildGroup[]): RechargeFlatNetworkOption[] {
  const out: RechargeFlatNetworkOption[] = []
  for (const g of groups) {
    if (!g?.coin || !Array.isArray(g.networkConfigs)) {
      continue
    }
    const nets = [...g.networkConfigs].sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
    for (const n of nets) {
      out.push({
        coinName: String(g.coin.name ?? ''),
        coinNameCn: String(g.coin.nameCn ?? ''),
        networkConfigId: Number(n.id),
        networkName: String(n.network?.name ?? ''),
        protocol: String(n.network?.protocol ?? ''),
        contractAddress: String(n.contractAddress ?? ''),
        rechargeAddress: String(n.rechargeAddress ?? ''),
      })
    }
  }
  return out
}

function mapListItem(row: Record<string, unknown>): RechargeOrderListItem {
  return {
    id: String(row.id ?? row.orderNo ?? ''),
    orderNo: String(row.orderNo ?? ''),
    coinName: String(row.coinName ?? ''),
    networkName: String(row.networkName ?? ''),
    rechargeAddress: String(row.rechargeAddress ?? ''),
    amount: String(row.amount ?? '0'),
    txHash: row.txHash != null && String(row.txHash) !== '' ? String(row.txHash) : null,
    status: Number(row.status ?? 0),
    createTime: String(row.createTime ?? ''),
    submitHashTime: row.submitHashTime != null && String(row.submitHashTime) !== '' ? String(row.submitHashTime) : null,
    updateTime: String(row.updateTime ?? ''),
  }
}

export const useDepositStore = defineStore('deposit', () => {
  const parentCoins = ref<RechargeParentCoin[]>([])
  const flatNetworks = ref<RechargeFlatNetworkOption[]>([])
  const selectedParentIndex = ref(0)
  const selectedFlatIndex = ref(0)

  const loadingParents = ref(false)
  const childrenLoading = ref(false)
  const error = ref<string | null>(null)

  const currentOrder = ref<RechargeOrderDetail | null>(null)
  const orderSubmitting = ref(false)
  const hashSubmitting = ref(false)

  const records = ref<RechargeOrderListItem[]>([])
  /** 最近一次已成功请求的页码（从 1 开始）；0 表示尚未加载 */
  const lastRecordPageFetched = ref(0)
  const recordPageSize = 15
  const recordTotalPages = ref(0)
  const recordTotalElements = ref(0)
  const recordLoading = ref(false)

  const recordHasMore = computed(() => {
    if (recordTotalPages.value <= 0) {
      return false
    }
    return lastRecordPageFetched.value < recordTotalPages.value
  })

  const selectedParent = computed(() => parentCoins.value[selectedParentIndex.value] ?? null)
  const selectedNetwork = computed(() => flatNetworks.value[selectedFlatIndex.value] ?? null)

  async function loadParentCoins() {
    loadingParents.value = true
    error.value = null
    try {
      const raw = await get<RechargeParentCoin[]>('/uc/coin-network/recharge-parents')
      const list = Array.isArray(raw) ? raw : []
      parentCoins.value = [...list].sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
      if (selectedParentIndex.value >= parentCoins.value.length) {
        selectedParentIndex.value = 0
      }
      if (parentCoins.value.length > 0) {
        await loadChildrenForParent(parentCoins.value[selectedParentIndex.value].name)
      } else {
        flatNetworks.value = []
      }
    } catch (e) {
      error.value = e instanceof Error ? e.message : '加载币种失败'
      parentCoins.value = []
      flatNetworks.value = []
      throw e
    } finally {
      loadingParents.value = false
    }
  }

  async function loadChildrenForParent(coinName: string) {
    childrenLoading.value = true
    error.value = null
    try {
      const raw = await get<RechargeChildGroup[]>('/uc/coin-network/children-with-network', {
        coinName,
      })
      const groups = Array.isArray(raw) ? raw : []
      flatNetworks.value = flattenNetworkOptions(groups)
      selectedFlatIndex.value = 0
    } catch (e) {
      error.value = e instanceof Error ? e.message : '加载主网失败'
      flatNetworks.value = []
      throw e
    } finally {
      childrenLoading.value = false
    }
  }

  async function selectParent(index: number) {
    if (index < 0 || index >= parentCoins.value.length) {
      return
    }
    selectedParentIndex.value = index
    const p = parentCoins.value[index]
    if (p) {
      await loadChildrenForParent(p.name)
    }
  }

  function selectFlatNetwork(index: number) {
    if (index >= 0 && index < flatNetworks.value.length) {
      selectedFlatIndex.value = index
    }
  }

  async function createRechargeOrder(amount: string) {
    const opt = selectedNetwork.value
    if (!opt) {
      throw new Error('请先选择充值网络')
    }
    orderSubmitting.value = true
    error.value = null
    try {
      const data = await postForm<RechargeOrderDetail>('/uc/recharge/create', {
        coinName: opt.coinName,
        networkConfigId: opt.networkConfigId,
        amount: amount.trim(),
      })
      currentOrder.value = data
      return data
    } catch (e) {
      error.value = e instanceof Error ? e.message : '创建订单失败'
      throw e
    } finally {
      orderSubmitting.value = false
    }
  }

  async function submitTxHash(orderNo: string, txHash: string) {
    hashSubmitting.value = true
    error.value = null
    try {
      const data = await postForm<RechargeOrderDetail>('/uc/recharge/submit-hash', {
        orderNo,
        txHash: txHash.trim(),
      })
      currentOrder.value = data
      return data
    } catch (e) {
      error.value = e instanceof Error ? e.message : '提交失败'
      throw e
    } finally {
      hashSubmitting.value = false
    }
  }

  function clearCurrentOrder() {
    currentOrder.value = null
  }

  async function loadRecords(refresh = false) {
    if (refresh) {
      lastRecordPageFetched.value = 0
      records.value = []
      recordTotalPages.value = 0
      recordTotalElements.value = 0
    }
    if (!refresh && !recordHasMore.value) {
      return
    }
    if (recordLoading.value) {
      return
    }
    const pageToFetch = refresh ? 1 : lastRecordPageFetched.value + 1
    recordLoading.value = true
    try {
      const data = await get<{
        content?: Record<string, unknown>[]
        totalElements?: number
        totalPages?: number
        number?: number
        size?: number
      }>('/uc/recharge/orders', {
        pageNo: pageToFetch,
        pageSize: recordPageSize,
      })
      const content = Array.isArray(data?.content) ? data.content : []
      const items = content.map(r => mapListItem(r as Record<string, unknown>))
      records.value = refresh ? items : [...records.value, ...items]
      recordTotalElements.value = Number(data?.totalElements ?? records.value.length)
      let totalPg = Number(data?.totalPages ?? 0)
      if (totalPg <= 0 && items.length > 0) {
        totalPg = 1
      }
      recordTotalPages.value = totalPg
      lastRecordPageFetched.value = pageToFetch
    } catch (e) {
      throw e instanceof Error ? e : new Error('加载记录失败')
    } finally {
      recordLoading.value = false
    }
  }

  async function fetchOrderDetail(orderNo: string) {
    return get<RechargeOrderDetail>('/uc/recharge/order', { orderNo })
  }

  return {
    parentCoins,
    flatNetworks,
    selectedParentIndex,
    selectedFlatIndex,
    loadingParents,
    childrenLoading,
    error,
    currentOrder,
    orderSubmitting,
    hashSubmitting,
    records,
    recordLoading,
    recordHasMore,
    recordTotalElements,
    lastRecordPageFetched,
    selectedParent,
    selectedNetwork,
    loadParentCoins,
    loadChildrenForParent,
    selectParent,
    selectFlatNetwork,
    createRechargeOrder,
    submitTxHash,
    clearCurrentOrder,
    loadRecords,
    fetchOrderDetail,
  }
})
