<template>
  <div class="address-list-page table_form-container">
    <!-- 搜索 -->
    <Search
      :search-form="searchForm"
      :search-options="searchOptions"
      :button-loading="loading"
      @search="handleSearch"
      @reset="handleReset"
    >
    </Search>

    <!-- 表格 -->
    <Table
      ref="tableRef"
      :table-data="tableData"
      :columns="tableColumnsOptions"
      row-key="address"
      :loading="loading"
      @rowClick="handleRowClick"
    >
      <template #action="{ row }">
        <el-button type="primary" size="small" @click.stop="openWithdrawDialog(row)">提现</el-button>
        <el-button size="small" @click.stop="handleRefresh(row)">刷新</el-button>
      </template>
    </Table>

    <!-- 分页 -->
    <Pagination
      v-model="queryParams.page"
      v-model:pageSizeValue="queryParams.page_size"
      :total="total"
      :layout="'prev, pager, next'"
      @pagination-change="getList"
    />

    <!-- 提现弹窗 -->
    <el-dialog v-model="withdrawDialogVisible" title="提现" width="600px">
      <el-form :model="withdrawForm" label-width="80px">
        <el-form-item label="来源地址">
          <el-input v-model="withdrawForm.from" disabled />
        </el-form-item>
        <el-form-item label="目标地址" required>
          <el-input v-model="withdrawForm.to" placeholder="请输入目标地址" />
        </el-form-item>
        <el-form-item label="金额" required>
          <el-input v-model="withdrawForm.amount" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="withdrawDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="withdrawLoading" @click="handleWithdraw">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Search from '@/components/common/Search.vue'
import Table from '@/components/common/Table.vue'
import Pagination from '@/components/common/Pagination.vue'
import { usePageLoading } from '@/composables/useLoading'
import { tableColumns, searchOptions } from './options'
import { getAddressList, balanceRefresh, withdrawAction } from '@/api/modules/wallet/wallet'

defineOptions({
  name: 'AddressList'
})

interface AddressRow {
  address: string
  trxBalance: string
  usdtBalance: string
  addressType: string
  createdAt: string
}

const tableRef = ref()
const tableData = ref<AddressRow[]>([])
const selectedRow = ref<AddressRow | null>(null)
const { loading, startLoading, stopLoading } = usePageLoading()

// 提现弹窗
const withdrawDialogVisible = ref(false)
const withdrawLoading = ref(false)
const withdrawForm = reactive({
  from: '',
  to: '',
  amount: '',
})

// 分页参数
const queryParams = reactive({
  page: 1,
  page_size: 20,
})
const total = ref(0)

// 搜索表单
const searchForm = ref({
  addressType: '',
  address: '',
})

// 表格列配置
const tableColumnsOptions = tableColumns

// 获取列表数据
const getList = async () => {
  startLoading()
  try {
    const res = await getAddressList({
      address: searchForm.value.address || '',
      addressType: searchForm.value.addressType || '',
      page: queryParams.page,
      page_size: queryParams.page_size,
    })
    
    if (res) {
      tableData.value = res?.address_list?.data?.list || []
      if (res?.address_list?.data?.list?.length === 20) {
        total.value = queryParams.page * queryParams.page_size
      }else{
        total.value = queryParams.page * queryParams.page_size - 1
      }
      console.log("total.value", total.value)
    }
  } catch (error) {
    console.error('获取列表失败', error)
  } finally {
    stopLoading()
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    addressType: '',
    address: '',
  }
  queryParams.page = 1
  getList()
}

// 行点击
const handleRowClick = (row: AddressRow) => {
  selectedRow.value = row
}

// 打开提现弹窗
const openWithdrawDialog = (row?: AddressRow) => {
  const targetRow = row || selectedRow.value
  if (!targetRow) {
    ElMessage.warning('请选择一条记录')
    return
  }
  withdrawForm.from = targetRow.address
  withdrawForm.to = ''
  withdrawForm.amount = ''
  withdrawDialogVisible.value = true
}

// 提现
const handleWithdraw = async () => {
  if (!withdrawForm.to) {
    ElMessage.warning('请输入目标地址')
    return
  }
  if (!withdrawForm.amount) {
    ElMessage.warning('请输入金额')
    return
  }
  withdrawLoading.value = true
  try {
    await withdrawAction({
      from: withdrawForm.from,
      to: withdrawForm.to,
      amount: withdrawForm.amount,
    })
    ElMessage.success('提现成功')
    withdrawDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提现失败', error)
  } finally {
    withdrawLoading.value = false
  }
}

// 刷新
const handleRefresh = async (row?: AddressRow) => {
  const targetRow = row || selectedRow.value
  if (!targetRow) {
    ElMessage.warning('请选择一条记录')
    return
  }
  try {
    const res = await balanceRefresh({ address: targetRow.address, addressType: targetRow.addressType })
    console.log(res)
    if (res) {
      ElMessage.success('刷新成功')
      const index = tableData.value.findIndex(item => item.address === targetRow.address)
      if (index !== -1) {
        tableData.value[index]!.usdtBalance = res.data;
      }
    }
  } catch (error) {
    console.error('刷新失败', error)
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.address-list-page {
}
</style>
