<template>
  <ContentWrap>
    <!-- 顶部：提现中提示 -->

    <!-- 搜索（瘦身版） -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="提现单号" prop="withdrawNo">
        <el-input v-model="queryParams.withdrawNo" placeholder="请输入提现单号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" style="width: 130px;" placeholder="请选择状态" clearable>
          <el-option label="申请中" value="APPLIED" />
          <el-option label="已审核" value="APPROVED" />
          <el-option label="已拒绝" value="REJECTED" />
          <el-option label="提现中" value="PAYING" />
          <el-option label="已打款" value="PAID" />
          <el-option label="打款失败" value="FAILED" />
          <el-option label="已取消" value="CANCELED" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker v-model="queryParams.applyTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始" end-placeholder="结束" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>

        <!-- <el-button type="warning" plain @click="openWithdraw">
          <Icon icon="ep:money" class="mr-5px" /> 提现
        </el-button> -->

        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:tenant-withdraw-order:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>

        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:tenant-withdraw-order:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表（瘦身版） -->
  <ContentWrap>
    <el-table ref="tableRef" row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="租户" align="center" prop="tenantName" width="90" />
      <el-table-column label="提现单号" align="center" prop="withdrawNo" min-width="180" />
      <el-table-column label="钱包流水号" align="center" prop="bizNo" min-width="180" />
      <el-table-column label="申请金额(元)" align="center" prop="amount" width="120" />
      <el-table-column label="实际到账(元)" align="center" prop="actualAmount" width="120" />
      <el-table-column label="渠道" align="center" prop="payChannel" width="110" />
      <el-table-column label="收款人" align="center" prop="payeeName" min-width="140" />
      <el-table-column label="收款账号" align="center" prop="payeeAccount" min-width="180" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.status === 'APPLIED'" type="info">申请中</el-tag>
          <el-tag v-else-if="row.status === 'APPROVED'" type="primary">已审核</el-tag>
          <el-tag v-else-if="row.status === 'REJECTED'" type="danger">已拒绝</el-tag>
          <el-tag v-else-if="row.status === 'PAYING'" type="warning">提现中</el-tag>
          <el-tag v-else-if="row.status === 'PAID'" type="success">已打款</el-tag>
          <el-tag v-else-if="row.status === 'FAILED'" type="danger">打款失败</el-tag>
          <el-tag v-else-if="row.status === 'CANCELED'" type="info">已取消</el-tag>
          <el-tag v-else>{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" :formatter="dateFormatter" width="180" />

      <el-table-column label="操作" align="center" width="220">
        <template #default="{ row }">
          <el-button
            v-if="!(row.status === 'PAID' || row.status === 'REJECTED' || row.status === 'CANCELED' || row.status === 'FAILED')"
            link type="primary" @click="openForm('update', row.id)"
            v-hasPermi="['keyboard:tenant-withdraw-order:update']">
            去处理
          </el-button>

          <!-- <el-button link type="danger" @click="handleDelete(row.id)"
            v-hasPermi="['keyboard:tenant-withdraw-order:delete']">
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 你原来的：提现弹窗 & 表单组件（保留即可） -->
  <Dialog v-model="withdrawDialogVisible" title="提现" width="600px">
    <!-- ...你原本的提现表单不动... -->
  </Dialog>

  <TenantWithdrawOrderForm ref="formRef" @success="getList" />
</template>


<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TenantWithdrawOrderApi, TenantWithdrawOrder } from '@/api/keyboard/tenantwithdraworder'
import TenantWithdrawOrderForm from './TenantWithdrawOrderForm.vue'

defineOptions({ name: 'KeyboardTenantWithdrawOrder' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<TenantWithdrawOrder[]>([])
const total = ref(0)
const tableRef = ref()

// ✅ 搜索参数：瘦身 + 修复重复字段
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  withdrawNo: undefined as any,
  status: undefined as any,
  applyTime: [] as string[]
})

const queryFormRef = ref()
const exportLoading = ref(false)

/** 勾选 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: TenantWithdrawOrder[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

/** 拉列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TenantWithdrawOrderApi.getTenantWithdrawOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 表单（新增/编辑） */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await TenantWithdrawOrderApi.deleteTenantWithdrawOrder(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

/** 批量删除 */
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await TenantWithdrawOrderApi.deleteTenantWithdrawOrderList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

/** 导出 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await TenantWithdrawOrderApi.exportTenantWithdrawOrder(queryParams)
    download.excel(data, '租户提现订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** ✅ 提现中统计 + 去处理滚动 */
const withdrawDialogVisible = ref(false)
// const openWithdraw = () => {
//   withdrawDialogVisible.value = true
// }

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