<template>
  <div v-loading="pageLoading" class="app-container" :element-loading-text="loadingText">
    <el-tabs v-model="activeTab" class="account-tabs" type="card">
      <el-tab-pane label="账户概览" name="overview">
        <AccountOverview ref="overviewRef" :enterprise-id="currentEnterpriseId" @refresh="handleOverviewRefresh"
          @goTab="handleGoTab" @withdraw="withdrawVisible = true"
          :transfer-enabled="hasTransferPermission" />
      </el-tab-pane>

      <!-- <el-tab-pane label="转账授权签约" name="authorize">
        <div class="tab-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>转账授权签约</span>
              </div>
            </template>
<el-form ref="authorizeFormRef" :model="authorizeForm" :rules="authorizeRules" label-width="120px">
  <el-form-item label="企业ID" prop="enterprise_id" v-show="!currentEnterpriseId">
    <el-input v-model="authorizeForm.enterprise_id" placeholder="请输入企业ID" :disabled="!!currentEnterpriseId" />
  </el-form-item>
  <el-form-item>
    <el-button v-hasPerm="['module_payment:account:authorize']" type="primary" :loading="authorizeLoading"
      @click="handleAuthorize">
      申请签约
    </el-button>
    <el-button @click="handleAuthorizeReset">重置</el-button>
  </el-form-item>
</el-form>
<div v-if="authorizeResult.sign_url" class="authorize-result">
  <el-alert title="签约链接已生成，请在支付宝中完成签约" type="success" :closable="false">
    <template #default>
                  <el-link :href="authorizeResult.sign_url" target="_blank" type="primary">
                    点击前往签约 →
                  </el-link>
                </template>
  </el-alert>
</div>
</el-card>
</div>
</el-tab-pane> -->

      <!-- <el-tab-pane label="开通资金专户" name="create">
        <div class="tab-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>开通资金专户</span>
                <el-tag v-if="authorizeStatus !== 'AUTHORIZED'" type="danger">
                  请先完成转账授权签约
                </el-tag>
              </div>
            </template>
            <el-form
              ref="createFormRef"
              :model="createForm"
              :rules="createRules"
              label-width="140px"
            >
              <el-form-item label="企业ID" prop="enterprise_id">
                <el-input
                  v-model="createForm.enterprise_id"
                  placeholder="请输入企业ID"
                  :disabled="!!currentEnterpriseId"
                />
              </el-form-item>
              <el-form-item label="账户类型" prop="account_type">
                <el-select v-model="createForm.account_type" placeholder="请选择账户类型">
                  <el-option label="收支全能户" value="ALL" />
                  <el-option label="收入户" value="INCOME" />
                  <el-option label="支出户" value="DISBURSE" />
                </el-select>
              </el-form-item>
              <el-form-item label="场景类型" prop="scene">
                <el-select v-model="createForm.scene" placeholder="请选择场景类型">
                  <el-option label="ToB转账" value="B2B_TRANS" />
                  <el-option label="企业信用" value="ENT_CREDIT" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="createForm.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
              <el-form-item>
                <el-button
                  v-hasPerm="['module_payment:account:create']"
                  type="primary"
                  :loading="createLoading"
                  :disabled="authorizeStatus !== 'AUTHORIZED'"
                  @click="handleCreate"
                >
                  开通专户
                </el-button>
                <el-button @click="handleCreateReset">重置</el-button>
              </el-form-item>
            </el-form>
            <div v-if="createResult.account_book_id" class="create-result">
              <el-alert title="资金专户开通成功" type="success" :closable="false">
                <template #default>
                  <div>专户ID: {{ createResult.account_book_id }}</div>
                </template>
              </el-alert>
            </div>
          </el-card>
        </div>
      </el-tab-pane> -->

      <el-tab-pane v-if="hasTransferPermission" label="账户充值" name="deposit">
        <div class="tab-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>资金专户充值</span>
                <el-tag v-if="!accountInfo.account_book_id" type="danger">
                  请先开通资金专户
                </el-tag>
                <!-- <el-tag v-else-if="accountInfo.status !== 'AUTHORIZED'" type="warning">
                  资金专户状态异常
                </el-tag> -->
              </div>
            </template>
            <el-form ref="depositFormRef" :model="depositForm" :rules="depositRules" label-width="140px">
              <!-- <el-form-item label="企业ID" prop="enterprise_id">
                <el-input v-model="currentEnterpriseId" placeholder="请输入企业ID" :disabled="!!currentEnterpriseId" />
              </el-form-item> -->
              <!-- <el-form-item label="资金账户" prop="account_book_id">
                <el-input v-model="depositForm.account_book_id" :placeholder="accountInfo.account_book_id || '请先开通资金账户'"
                  :disabled="!!accountInfo.account_book_id" />
              </el-form-item> -->
              <el-form-item label="充值金额" prop="amount">
                <el-input-number v-model="depositForm.amount" :min="0.00" :precision="2" :controls="false"
                  placeholder="请输入充值金额" style="width: 300px" />
                <span class="ml-2">元</span>
              </el-form-item>
              <!-- <el-form-item label="备注" prop="remark">
                <el-input v-model="depositForm.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item> -->
              <el-form-item>
                <el-button v-hasPerm="['module_payment:account:deposit']" type="primary" :loading="depositLoading"
                  :disabled="!accountInfo.account_book_id || accountInfo.status === 'AUTHORIZED'" @click="handleDeposit">
                  发起充值
                </el-button>
                <el-button @click="handleDepositReset">重置</el-button>
              </el-form-item>
            </el-form>
            <div v-if="depositResult.url" class="deposit-result">
              <el-alert title="充值页面已生成，请在支付宝中完成支付" type="success" :closable="false">
                <template #default>
                  <el-link :href="depositResult.url" target="_blank" type="primary">
                    点击前往充值 →
                  </el-link>
                </template>
              </el-alert>
            </div>
          </el-card>

          <!-- <el-card class="mt-4">
            <template #header>
              <span>充值记录</span>
            </template>
            <el-table :data="depositList" border stripe>
              <el-table-column prop="out_biz_no" label="订单号" min-width="180" />
              <el-table-column prop="amount" label="充值金额" min-width="100">
                <template #default="{ row }">
                  ¥{{ row.amount }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100">
                <template #default="{ row }">
                  <el-tag :type="getDepositStatusType(row.status)">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_time" label="创建时间" min-width="160" />
            </el-table>
          </el-card> -->
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="hasTransferPermission" label="转账管理" name="transfer">
        <div class="tab-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>发起转账</span>
                <div>
                  <el-tag v-if="!accountInfo.account_book_id" type="danger" class="ml-2">
                    请先开通资金专户
                  </el-tag>
                  <el-tag v-else-if="accountInfo.balance <= 0" type="warning" class="ml-2">
                    账户余额不足，请先充值
                  </el-tag>
                </div>
              </div>
            </template>
            <el-form ref="transferFormRef" :model="transferForm" :rules="transferRules" label-width="140px">
              <!-- <el-form-item label="企业ID" prop="enterprise_id">
                <el-input v-model="currentEnterpriseId" placeholder="请输入企业ID"
                  :disabled="!!currentEnterpriseId" />
              </el-form-item>
              <el-form-item label="付款资金账户" prop="account_book_id">
                <el-input v-model="transferForm.account_book_id"
                  :placeholder="accountInfo.account_book_id || '请先开通资金账户'" :disabled="!!accountInfo.account_book_id" />
              </el-form-item> -->
              <el-form-item label="转账金额" prop="amount">
                <el-input-number v-model="transferForm.amount" :min="0.00" :precision="2" :controls="false"
                  placeholder="请输入转账金额" style="width: 300px" />
                <span class="ml-2">元</span>
              </el-form-item>
              <el-form-item label="转账标题" prop="order_title">
                <el-input v-model="transferForm.order_title" placeholder="请输入转账标题" />
              </el-form-item>
              <el-form-item label="转账场景" prop="transfer_scene_name">
                <el-select v-model="transferForm.transfer_scene_name" placeholder="请选择转账场景">
                  <el-option v-for="s in TRANSFER_SCENE_OPTIONS" :key="s.value" :label="s.label" :value="s.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="收款方类型" prop="payee_info.identity_type">
                <el-select v-model="transferForm.payee_info.identity_type" placeholder="请选择收款方类型">
                  <el-option label="支付宝账户(UID)" value="ALIPAY_USER_ID" />
                  <el-option label="支付宝账户(手机号/邮箱)" value="ALIPAY_LOGON_ID" />
                  <el-option label="银行卡" value="BANKCARD_ACCOUNT" />
                  <!-- <el-option label="资金专户" value="book" /> -->
                </el-select>
              </el-form-item>
              <el-form-item label="收款方真实姓名" prop="payee_info.name">
                <el-input v-model="transferForm.payee_info.name" placeholder="请输入收款方姓名" />
              </el-form-item>
              <el-form-item :label="isAlipayPayee ? '收款方支付宝账号' : '收款方银行卡号'" prop="payee_info.identity">
                <el-input v-model="transferForm.payee_info.identity" :placeholder="isAlipayPayee ? '请输入收款方支付宝账号' : '请输入收款方银行卡号'" />
              </el-form-item>
              <template v-if="transferForm.payee_info.identity_type === 'BANKCARD_ACCOUNT'">
                <el-form-item label="到账时效" prop="withdraw_timeliness">
                  <el-radio-group v-model="transferForm.withdraw_timeliness">
                    <el-radio label="T1">次日到账（默认）</el-radio>
                    <el-radio label="T0">当天到账</el-radio>
                  </el-radio-group>
                  <div class="form-item-tip">当天到账受银行处理时效影响，不保证100%实时到账</div>
                </el-form-item>
                <el-form-item label="账户类型" prop="payee_info.bankcard_ext_info.account_type">
                  <el-select v-model="transferForm.payee_info.bankcard_ext_info!.account_type" placeholder="请选择账户类型">
                    <el-option label="公司账户" value="1" />
                    <el-option label="个人账户" value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="银行名称" prop="payee_info.bankcard_ext_info.inst_name" :required="isCorporate">
                  <el-input v-model="transferForm.payee_info.bankcard_ext_info!.inst_name" placeholder="请输入银行名称" />
                </el-form-item>
                <template v-if="isCorporate">
                  <el-alert type="warning" :closable="false" show-icon style="margin-bottom:12px">
                    对公账户必须填写省市支行信息 或 联行号
                  </el-alert>
                </template>
                <el-form-item label="开户省份" prop="payee_info.bankcard_ext_info.inst_province" :required="isCorporate">
                  <el-input v-model="transferForm.payee_info.bankcard_ext_info!.inst_province" placeholder="请输入开户省份" />
                </el-form-item>
                <el-form-item label="开户城市" prop="payee_info.bankcard_ext_info.inst_city" :required="isCorporate">
                  <el-input v-model="transferForm.payee_info.bankcard_ext_info!.inst_city" placeholder="请输入开户城市" />
                </el-form-item>
                <el-form-item label="支行名称" prop="payee_info.bankcard_ext_info.inst_branch_name" :required="isCorporate">
                  <el-input v-model="transferForm.payee_info.bankcard_ext_info!.inst_branch_name"
                    placeholder="请输入支行名称" />
                </el-form-item>
                <el-form-item label="联行号" prop="payee_info.bankcard_ext_info.bank_code" :required="isCorporate">
                  <el-input v-model="transferForm.payee_info.bankcard_ext_info!.bank_code" placeholder="请输入联行号" />
                </el-form-item>
              </template>
              <el-form-item label="备注" prop="remark" required>
                <el-input v-model="transferForm.remark" type="textarea" :placeholder="remarkPlaceholder" />
              </el-form-item>
              <el-form-item>
                <el-button v-hasPerm="['module_payment:account:transfer']" type="primary" :loading="transferLoading"
                  :disabled="!accountInfo.account_book_id || accountInfo.balance <= 0" @click="handleTransfer">
                  发起转账
                </el-button>
                <el-button @click="handleTransferReset">重置</el-button>
                <el-button v-hasPerm="['module_payment:account:transfer']" type="primary" @click="openBatchTransferDialog">
                    批量转账
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card class="mt-4">
            <template #header>
              <div class="card-header">
                <span>转账记录</span>
                <!-- <el-button
                  type="primary"
                  icon="Download"
                  class="ml-auto"
                  @click="showDownloadMenu = true"
                >
                  下载报表
                </el-button> -->
              </div>
            </template>
            <div class="mb-4">
              <el-form :inline="true" :model="transferSearchForm">
                <el-form-item label="订单号">
                  <el-input v-model="transferSearchForm.out_biz_no" placeholder="请输入订单号" clearable />
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="transferSearchForm.status" placeholder="请选择状态" clearable>
                    <el-option label="处理中" value="DEALING" />
                    <el-option label="成功" value="SUCCESS" />
                    <el-option label="失败" value="FAIL" />
                    <el-option label="退票" value="REFUND" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="is_platform_user" label="租户">
                  <el-select v-model="transferSearchForm.tenant_id" placeholder="选择租户" clearable filterable>
                    <el-option v-for="t in allTenantData" :key="t.id" :label="t.name" :value="t.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="企业">
                  <el-select v-model="transferSearchForm.enterprise_id" placeholder="选择企业" clearable filterable>
                    <el-option v-for="e in enterpriseStore.getEnterpriseList" :key="e.enterprise_id" :label="e.name" :value="e.enterprise_id" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleTransferSearch">查询</el-button>
                  <el-button @click="handleTransferSearchReset">重置</el-button>
                  <el-button icon="Refresh" @click="handleTransferSearchReset">刷新</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="transferList" border stripe v-loading="transferListLoading">
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column prop="out_biz_no" label="订单号" min-width="180" />
              <el-table-column prop="amount" label="转账金额" min-width="100">
                <template #default="{ row }">
                  ¥{{ row.amount }}
                </template>
              </el-table-column>
              <el-table-column prop="payee_info.name" label="收款方姓名" min-width="120" />
              <el-table-column prop="payee_info.identity_type" label="收款方类型" min-width="100">
                <template #default="{ row }">
                  {{ getPayeeTypeLabel(row.payee_info?.identity_type) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100">
                <template #default="{ row }">
                  <el-tag :type="getTransferStatusType(row.status)">
                    {{ getStatusLabel(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="order_title" label="转账标题" min-width="150" />
              <el-table-column prop="created_time" label="创建时间" min-width="160" />
              <el-table-column label="操作" width="160" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleViewTransferDetail(row.out_biz_no)">
                    详情
                  </el-button>
                  <el-button
                    type="primary"
                    link
                    icon="Download"
                    @click="handleDownloadReceipt(row)"
                    :disabled="row.status !== 'SUCCESS'"
                    :title="row.status !== 'SUCCESS' ? '仅成功的转账可下载回单' : '下载回单'"
                  >
                    下载回单
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-4 flex justify-end">
              <el-pagination v-model:current-page="transferPage.page_no" v-model:page-size="transferPage.page_size"
                :total="transferPage.total" :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleTransferListChange"
                @current-change="handleTransferListChange" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="消费记录" name="consume-record">
        <div class="tab-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>消费记录列表</span>
              </div>
            </template>
            <div class="mb-4">
              <el-form :inline="true" :model="consumeSearchForm">
                <el-form-item v-if="is_platform_user" label="租户">
                  <el-select v-model="consumeSearchForm.tenant_id" placeholder="选择租户" clearable filterable>
                    <el-option v-for="t in allTenantData" :key="t.id" :label="t.name" :value="t.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="企业">
                  <el-select v-model="consumeSearchForm.enterprise_id" placeholder="选择企业" clearable filterable>
                    <el-option v-for="e in enterpriseStore.getEnterpriseList" :key="e.enterprise_id" :label="e.name" :value="e.enterprise_id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="消费类型">
                  <el-select v-model="consumeSearchForm.consume_type" placeholder="全部" clearable>
                    <el-option label="消费" value="CONSUME" />
                    <el-option label="退款" value="REFUND" />
                    <el-option label="转账" value="TRANSFER" />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select v-model="consumeSearchForm.status" placeholder="全部" clearable>
                    <el-option label="未处理" value="NEW" />
                    <el-option label="已处理" value="PROCESSED" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="consumeSearchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    @change="handleConsumeDateChange"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleConsumeSearch">查询</el-button>
                  <el-button @click="handleConsumeSearchReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table :data="consumeRecordList" border stripe v-loading="consumeListLoading">
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column prop="pay_no" label="账单号" min-width="180" />
              <el-table-column prop="enterprise_id" label="企业ID" min-width="120" />
              <el-table-column prop="employee_id" label="员工ID" min-width="120" />
              <el-table-column prop="consume_amount" label="消费金额" min-width="120">
                <template #default="{ row }">
                  ¥{{ Number(row.consume_amount).toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="consume_type" label="消费类型" min-width="100">
                <template #default="{ row }">
                  <el-tag :type="getConsumeTypeTag(row.consume_type)">
                    {{ getConsumeTypeLabel(row.consume_type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100">
                <template #default="{ row }">
                  <el-tag :type="getConsumeStatusType(row.status)">
                    {{ getConsumeStatusLabel(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="gmt_biz_create" label="业务时间" min-width="160" />
            </el-table>
            <div class="mt-4 flex justify-end">
              <el-pagination v-model:current-page="consumePage.page_no" v-model:page-size="consumePage.page_size"
                :total="consumePage.total" :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper" @size-change="handleConsumeListChange"
                @current-change="handleConsumeListChange" />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="收款记录" name="f2f-trade">
        <F2fTradeRecord v-if="activeTab === 'f2f-trade'" />
      </el-tab-pane>

      <!-- <el-tab-pane label="账单查询" name="consume">
        <div class="tab-content">
          <el-card>
            <template #header>
              <span>账单详情查询</span>
            </template>
            <el-form ref="consumeFormRef" :model="consumeForm" :rules="consumeRules" label-width="140px">
              <el-form-item label="支付宝账单号" prop="pay_no">
                <el-input v-model="consumeForm.pay_no" placeholder="请输入支付宝账单号" />
              </el-form-item>
              <el-form-item label="企业ID" prop="enterprise_id">
                <el-input
                  v-model="consumeForm.enterprise_id"
                  placeholder="请输入企业ID（2.0接口签约企业必填）"
                  :disabled="!!currentEnterpriseId"
                />
              </el-form-item>
              <el-form-item label="蚂蚁门店ID" prop="ant_shop_id">
                <el-input v-model="consumeForm.ant_shop_id" placeholder="请输入蚂蚁门店ID（商户服务商必填）" />
              </el-form-item>
              <el-form-item label="查询选项">
                <el-checkbox-group v-model="consumeForm.query_options">
                  <el-checkbox label="Refund">退款信息</el-checkbox>
                  <el-checkbox label="Order">订单信息</el-checkbox>
                  <el-checkbox label="Ticket">票据信息</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item>
                <el-button
                  v-hasPerm="['module_payment:account:consume:detail']"
                  type="primary"
                  :loading="consumeLoading"
                  @click="handleConsumeQuery"
                >
                  查询
                </el-button>
                <el-button @click="handleConsumeReset">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card v-if="consumeDetail" class="mt-4">
            <template #header>
              <span>账单详情</span>
            </template>
            <ConsumeDetail :data="consumeDetail" />
          </el-card>
        </div>
      </el-tab-pane> -->
    </el-tabs>

    <TransferDetail v-model="transferDetailVisible" :out-biz-no="currentTransferOutBizNo"
      @refresh="handleTransferDetailRefresh" />

    <!-- 进件弹窗 -->
    <el-dialog v-model="onboardDialogVisible" title="提交进件资料" width="650px" destroy-on-close
      :close-on-click-modal="false">
      <el-form ref="onboardFormRef" :model="onboardForm" :rules="onboardRules" label-width="120px">
        <el-form-item label="场景码" prop="scene_code" required>
          <el-select v-model="onboardForm.scene_code" placeholder="请选择转账场景">
            <el-option v-for="s in ONBOARD_SCENE_OPTIONS" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="场景说明" prop="scene_directions" required>
          <el-input v-model="onboardForm.scene_directions" type="textarea" :rows="3"
            placeholder="谁/通过什么媒介/主要为谁提供什么服务/用于在什么场景给什么人群转账" maxlength="1024" show-word-limit />
        </el-form-item>
        <el-form-item label="场景截图" prop="scene_image" required>
          <el-upload ref="uploadRef" :http-request="handleOnboardUpload" :file-list="onboardFiles"
            :limit="5" list-type="picture-card" accept=".jpg,.jpeg,.png,.pdf"
            :before-upload="handleSceneBeforeUpload" :on-remove="handleOnboardFileRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 jpg / png / pdf，最多 5 个文件</div>
        </el-form-item>
        <el-form-item>
          <template #label>
            资质文件
            <el-tooltip placement="top" :content="qualificationTip" raw-content>
              <el-icon style="margin-left:4px;cursor:help"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-upload ref="qualUploadRef" :http-request="handleQualUpload" :file-list="onboardQualFiles"
            :limit="5" list-type="picture-card" accept=".jpg,.jpeg,.png,.pdf"
            :before-upload="handleQualBeforeUpload" :on-remove="handleQualFileRemove">
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">按场景要求上传行业资质，最多 5 个文件<br>受其他公司委托为他人代发时，无论属于什么场景，请上传合作协议（含甲方行业、委托代发原因、代发对象身份等）</div>
        </el-form-item>
        <el-form-item label="站点信息">
          <el-checkbox-group v-model="onboardSiteTypes">
            <el-checkbox v-for="s in SITE_TYPE_OPTIONS" :key="s.value" :label="s.value">{{ s.label }}</el-checkbox>
          </el-checkbox-group>
          <div v-for="st in onboardSiteTypes" :key="st" style="margin-top: 8px">
            <el-input v-model="onboardSites[st]" :placeholder="'请输入' + (SITE_TYPE_OPTIONS.find(s => s.value === st)?.label || st) + '地址'" style="width: 300px" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onboardDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="onboardLoading" @click="handleOnboardSubmit">提交进件</el-button>
      </template>
    </el-dialog>

    <!-- 批量转账对话框 -->
    <el-dialog v-model="batchTransferVisible" title="批量转账" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="batch-transfer-container" :class="{ 'has-overlay': showBatchTransferOverlay }">
        <el-card class="mb-4">
          <template #header>
            <span>Excel模板下载</span>
          </template>
          <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
          <el-alert
            title="模板说明"
            type="info"
            :closable="false"
            class="mt-4"
          >
            <ul>
              <li>请按照模板格式填写转账数据</li>
              <li>支持支付宝账户和银行卡转账</li>
              <li>银行卡转账需要填写完整的银行信息</li>
            </ul>
          </el-alert>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <span>上传Excel文件</span>
          </template>
          <el-upload
            class="upload-demo"
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx, .xls"
            :file-list="fileList"
            :limit="1"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传Excel文件，支持.xlsx和.xls格式
              </div>
            </template>
          </el-upload>
        </el-card>

        <el-card v-if="batchTransferData.length > 0">
          <template #header>
            <span>数据预览</span>
          </template>
          <el-table :data="batchTransferData" border stripe>
            <el-table-column prop="amount" label="转账金额(元)" min-width="100" />
            <el-table-column prop="order_title" label="转账标题" min-width="150" />
            <el-table-column prop="payee_name" label="收款方姓名" min-width="120" />
            <el-table-column prop="payee_type" label="收款方类型" min-width="100" />
            <el-table-column prop="payee_account" label="收款方账号" min-width="180" />
            <el-table-column prop="bank_name" label="银行名称" min-width="120" v-if="hasBankTransfer" />
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'valid' ? 'success' : 'danger'">
                  {{ row.status === 'valid' ? '有效' : '无效' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="error_msg" label="错误信息" min-width="150" v-if="hasInvalidData" />
          </el-table>
        </el-card>

        <!-- 遮罩层 -->
        <div v-if="showBatchTransferOverlay" class="batch-transfer-overlay">
          <div class="overlay-content">
            <el-icon class="is-loading" size="40"><Loading /></el-icon>
            <h3>正在处理批量转账，请勿关闭对话框</h3>
            <el-progress :percentage="Math.round((batchCurrentIndex / batchTotalCount) * 100)" :stroke-width="20" />
            <p>正在向 {{ batchCurrentPayee }} 转账 ¥{{ batchCurrentAmount }}</p>
            <div class="result-summary">
              <el-tag type="success">成功: {{ batchTransferSuccessCount }}</el-tag>
              <el-tag type="danger">失败: {{ batchTransferFailCount }}</el-tag>
              <el-tag type="warning">进行中: {{ batchCurrentIndex }}/{{ batchTotalCount }}</el-tag>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchTransferVisible = false" :disabled="batchTransferLoading">取消</el-button>
          <el-button type="primary" :loading="batchTransferLoading" @click="handleBatchTransfer" :disabled="batchTransferData.length === 0 || hasInvalidData || showBatchTransferOverlay">
            开始批量转账
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量转账结果对话框 -->
    <el-dialog v-model="batchTransferResultVisible" title="批量转账结果" width="800px">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>处理结果</span>
            <div>
              <el-tag type="success" class="ml-2">{{ batchTransferSuccessCount }} 成功</el-tag>
              <el-tag type="danger" class="ml-2">{{ batchTransferFailCount }} 失败</el-tag>
            </div>
          </div>
        </template>
        <el-table :data="batchTransferResults" border stripe>
          <el-table-column prop="amount" label="转账金额(元)" min-width="100" />
          <el-table-column prop="payee_name" label="收款方姓名" min-width="120" />
          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息" min-width="200" />
        </el-table>
      </el-card>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchTransferResultVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现弹窗 -->
    <el-dialog v-model="withdrawVisible" title="发起提现" width="500px" destroy-on-close>
      <el-form ref="withdrawFormRef" :model="withdrawForm" :rules="withdrawRules" label-width="100px">
        <el-form-item label="当前余额">
          <span style="font-weight: bold; color: #67c23a">¥{{ accountInfo.balance?.toFixed(2) ?? "0.00" }}</span>
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="0.01"
            :max="accountInfo.balance"
            :precision="2"
            :controls="false"
            placeholder="请输入提现金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="提现原因" prop="remark">
          <el-input v-model="withdrawForm.remark" placeholder="选填，默认'提现'" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="withdrawVisible = false">取消</el-button>
        <el-button type="primary" :loading="withdrawLoading" @click="handleWithdraw">确认提现</el-button>
      </template>
    </el-dialog>

    <!-- 下载报表弹窗 -->
    <el-dialog title="下载转账报表" v-model="showDownloadMenu" width="500px" :close-on-click-modal="false">
      <div class="download-options">
        <div class="option-group">
          <p class="option-title">快捷时间范围</p>
          <div class="option-buttons">
            <el-button
              v-for="option in quickOptions"
              :key="option.value"
              :type="selectedQuickOption === option.value ? 'primary' : ''"
              @click="selectedQuickOption = option.value"
            >
              {{ option.label }}
            </el-button>
          </div>
        </div>
        <div class="option-group mt-4">
          <p class="option-title">自定义时间范围</p>
          <el-date-picker
            v-model="customDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            class="w-full"
            @change="handleCustomDateChange"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="showDownloadMenu = false">取消</el-button>
        <el-button type="primary" @click="handleDownload" :loading="downloadLoading">
          下载报表
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Account",
  inheritAttrs: false,
});

import { useEnterpriseStore, useUserStore } from "@/store";
import AccountAPI from "@/api/module_payment/account";
import AccountOverview from "./components/AccountOverview.vue";
import TransferDetail from "./components/TransferDetail.vue";
import ConsumeDetail from "./components/ConsumeDetail.vue";
import F2fTradeRecord from "./components/F2fTradeRecord.vue";
import TenantAPI, { TenantTable } from "@/api/module_system/tenant";
import { ref, reactive, computed, onMounted, watch } from "vue";
import { Refresh, Loading, Plus, QuestionFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import * as ExcelJS from "exceljs";

const enterpriseStore = useEnterpriseStore();
const userStore = useUserStore();

const is_platform_user = computed(() => userStore.is_platform_user);

const activeTab = ref("overview");
const pageLoading = ref(false);
const loadingText = ref("加载中...");

const authorizeLoading = ref(false);
const createLoading = ref(false);
const depositLoading = ref(false);
const transferLoading = ref(false);
const consumeLoading = ref(false);
const transferListLoading = ref(false);
const downloadLoading = ref(false);

const showDownloadMenu = ref(false);
const selectedQuickOption = ref("today");
const customDateRange = ref<Date[] | null>(null);

const quickOptions = [
  { label: "当天", value: "today" },
  { label: "近3天", value: "3days" },
  { label: "近15天", value: "15days" },
  { label: "近30天", value: "30days" },
];

const authorizeFormRef = ref<FormInstance>();
const createFormRef = ref<FormInstance>();
const depositFormRef = ref<FormInstance>();
const transferFormRef = ref<FormInstance>();
const consumeFormRef = ref<FormInstance>();
const overviewRef = ref<InstanceType<typeof AccountOverview>>();

const currentEnterpriseId = computed(() => enterpriseStore.getCurrentEnterprise?.enterprise_id);
const hasTransferPermission = computed(() =>
  userStore.is_platform_user || enterpriseStore.getCurrentEnterprise?.transfer_enabled === true
);
const cureentEnterprise = computed(() => enterpriseStore.getCurrentEnterprise);

const accountInfo = ref<{
  account_book_id: string;
  status: string;
  balance: number;
}>({
  account_book_id: "",
  status: "",
  balance: 0,
});

const authorizeStatus = ref("PENDING");

const authorizeForm = reactive({
  enterprise_id: "",
});

const authorizeRules: FormRules = {
  enterprise_id: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
};

const authorizeResult = reactive({
  sign_url: "",
  external_agreement_no: "",
  agreement_no: "",
  queryLoading: false,
});

const createForm = reactive({
  enterprise_id: "",
  agreement_no: "",
  account_type: "ALL",
  scene: "B2B_TRANS",
  remark: "",
});

const ONBOARD_QUALIFICATION_TIPS: Record<string, string> = {
  YONGJIN_BAOCHOU: `需提供以下任一：<br>① 发薪资质（人力资源经营许可证/劳务派遣经营许可证/委托代征协议）+ 至少1份已签署的上游委托发薪合作合同<br>② 付款员工清单(盖章)+至少3份已签署的劳动(务)合同<br>③ 付款员工清单(盖章)+最近1个月代缴个税或社保缴纳证明`,
  XIANJIN_YINGXIAO: "需提供用户参与营销活动细则",
  XINGZHENG_BUTIE: "需提供行政补贴/奖励官方文件或政府官网全文截图；若委托其他主体代发且无官方文件，需行政机关出具证明函说明委托关系",
  BAOXIAN_LIPEI: "需提供保险资质证明（如《保险许可证》《保险业务法人登记证书》等）或保司合作证明",
  CAIGOU_HUOKUAN: "需提供至少1份上下游合作伙伴合作协议",
};
const qualificationTip = computed(() =>
  ONBOARD_QUALIFICATION_TIPS[onboardForm.scene_code] || "选填，按需上传行业资质文件"
);
const onboardQualFiles = ref<any[]>([]);
const onboardQualImageIds = ref<string[]>([]);

async function handleQualUpload(option: any) {
  try {
    const res = await AccountAPI.uploadImage(option.file, currentEnterpriseId.value!);
    const imageId = res.data.data?.image_id;
    if (imageId) {
      onboardQualImageIds.value.push(imageId);
      option.onSuccess();
    } else {
      option.onError(new Error("上传失败"));
    }
  } catch (e) {
    option.onError(e);
  }
}

function handleQualFileRemove(_file: any, fileList: any) {
  const idx = fileList.findIndex((f: any) => f.uid === _file.uid);
  if (idx >= 0) onboardQualImageIds.value.splice(idx, 1);
}

const SITE_TYPE_OPTIONS = [
  { value: "WEBSITE", label: "网站" },
  { value: "APP", label: "APP" },
  { value: "GONGZH", label: "公众号" },
  { value: "XCHENGXU_ZHI", label: "支付宝小程序" },
  { value: "WEB", label: "手机网站/H5" },
  { value: "QITA", label: "其它" },
];

const onboardDialogVisible = ref(false);
const onboardFormRef = ref<FormInstance>();
const onboardLoading = ref(false);
const onboardFiles = ref<any[]>([]);
const onboardImageIds = ref<string[]>([]);
const uploadRef = ref();
const onboardSiteTypes = ref<string[]>([]);
const onboardSites = reactive<Record<string, string>>({});

const ONBOARD_SCENE_OPTIONS = [
  { value: "XIANJIN_YINGXIAO", label: "现金营销" },
  { value: "XINGZHENG_BUTIE", label: "行政补贴" },
  { value: "BAOXIAN_LIPEI", label: "保险理赔" },
  { value: "YONGJIN_BAOCHOU", label: "佣金报酬" },
  { value: "QIYE_PEIFU", label: "企业赔付" },
  { value: "CAIGOU_HUOKUAN", label: "采购货款" },
  { value: "ERSHOU_HUISHOU", label: "二手回收" },
  { value: "GONGYI_BUZHU", label: "公益补助" },
  { value: "ZHUANZHANG_QITA", label: "其他场景" },
];

const onboardForm = reactive({
  scene_code: "ZHUANZHANG_QITA",
  scene_directions: "",
  scene_image: "",
});

const validateSceneImage = (_rule: any, _value: any, callback: any) => {
  if (onboardImageIds.value.length === 0) callback(new Error("请上传场景截图"));
  else callback();
};

const onboardRules: FormRules = {
  scene_code: [{ required: true, message: "请选择场景码", trigger: "change" }],
  scene_directions: [{ required: true, message: "请填写场景说明", trigger: "blur" }],
  scene_image: [{ validator: validateSceneImage, trigger: "change" }],
};

const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];

function validateFileFormat(file: File) {
  const ext = "." + file.name.split(".").pop()?.toLowerCase();
  if (!ALLOWED_EXTENSIONS.includes(ext)) {
    ElMessage.error("仅支持 jpg / png / pdf 格式");
    return false;
  }
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("文件大小不能超过 5MB");
    return false;
  }
  return true;
}

function handleSceneBeforeUpload(file: File) {
  if (!validateFileFormat(file)) return false;
  if (onboardImageIds.value.length >= 5) {
    ElMessage.error("场景截图最多 5 个文件");
    return false;
  }
  return true;
}

function handleQualBeforeUpload(file: File) {
  if (!validateFileFormat(file)) return false;
  if (onboardQualImageIds.value.length >= 5) {
    ElMessage.error("资质文件最多 5 个文件");
    return false;
  }
  return true;
}

/** 自定义上传 — 选图即调用 image.upload */
async function handleOnboardUpload(option: any) {
  try {
    const res = await AccountAPI.uploadImage(option.file, currentEnterpriseId.value!);
    const imageId = res.data.data?.image_id;
    if (imageId) {
      onboardImageIds.value.push(imageId);
      onboardForm.scene_image = onboardImageIds.value.join(",");
      onboardFormRef.value?.validateField("scene_image");
      option.onSuccess();
    } else {
      option.onError(new Error("上传失败"));
    }
  } catch (e) {
    option.onError(e);
  }
}

function handleOnboardFileRemove(_file: any, fileList: any) {
  // 移除对应位置的 image_id
  const idx = fileList.findIndex((f: any) => f.uid === _file.uid);
  if (idx >= 0) {
    onboardImageIds.value.splice(idx, 1);
    onboardForm.scene_image = onboardImageIds.value.join(",");
    onboardFormRef.value?.validateField("scene_image");
  }
}

async function handleOnboardSubmit() {
  if (!onboardFormRef.value) return;
  await onboardFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (onboardImageIds.value.length === 0) {
      ElMessage.warning("请上传转账场景截图");
      return;
    }
    onboardLoading.value = true;
    try {
      // 构建 sites JSON
      let sites: string | undefined;
      if (onboardSiteTypes.value.length > 0) {
        const obj: Record<string, string> = {};
        for (const st of onboardSiteTypes.value) {
          if (onboardSites[st]) obj[st] = onboardSites[st];
        }
        if (Object.keys(obj).length > 0) sites = JSON.stringify(obj);
      }
      const res = await AccountAPI.createOnboard({
        enterprise_id: currentEnterpriseId.value!,
        scene_code: onboardForm.scene_code,
        scene_directions: onboardForm.scene_directions,
        scene_image: onboardImageIds.value.join(","),
        scene_qualification_image: onboardQualImageIds.value.join(",") || undefined,
        sites,
      });
      const data = res.data.data;
      if (data?.order_id) {
        ElMessage.success("进件单已提交，支付宝审核中");
        accountInfo.value.onboard_status = "PENDING";
        onboardDialogVisible.value = false;
        overviewRef.value?.refresh();
      }
    } catch (e: any) {
      ElMessage.error(e?.message || "提交进件失败");
    } finally {
      onboardLoading.value = false;
    }
  });
}

function handleOnboardReset() {
  onboardFormRef.value?.resetFields();
  onboardFiles.value = [];
  onboardImageIds.value = [];
  onboardQualFiles.value = [];
  onboardQualImageIds.value = [];
  onboardSiteTypes.value = [];
  Object.keys(onboardSites).forEach(k => delete onboardSites[k]);
}

const createRules: FormRules = {
  enterprise_id: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
  account_type: [{ required: true, message: "请选择账户类型", trigger: "change" }],
  scene: [{ required: true, message: "请选择场景类型", trigger: "change" }],
};

const createResult = reactive({
  enterprise_id: "",
  account_book_id: "",
});

const depositForm = reactive({
  enterprise_id: "",
  account_book_id: "",
  amount: 0,
  remark: "",
});

const depositRules: FormRules = {
  enterprise_id: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
  account_book_id: [{ required: true, message: "请输入资金专户号", trigger: "blur" }],
  amount: [{ required: true, message: "请输入充值金额", trigger: "blur" }],
};

const depositResult = reactive({
  url: "",
});

const depositList = ref<any[]>([]);

const transferForm = reactive({
  enterprise_id: "",
  account_book_id: "",
  amount: 0,
  order_title: "",
  remark: "",
  transfer_scene_name: "佣金报酬",
  withdraw_timeliness: "T1",
  payee_info: {
    identity_type: "ALIPAY_USER_ID",
    name: "",
    identity: "",
    bankcard_ext_info: {
      account_type: "2",
      inst_name: "",
      inst_province: "",
      inst_city: "",
      inst_branch_name: "",
      bank_code: "",
    },
  },
});

const transferRules: FormRules = {
  enterprise_id: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
  account_book_id: [{ required: true, message: "请输入付款资金账户", trigger: "blur" }],
  amount: [{ required: true, message: "请输入转账金额", trigger: "blur" }],
  "payee_info.identity_type": [{ required: true, message: "请选择收款方类型", trigger: "change" }],
  "payee_info.name": [{ required: true, message: "请输入收款方姓名", trigger: "blur" }],
  "payee_info.identity": [{ required: true, message: "请输入收款方账号", trigger: "blur" }],
  remark: [{ required: true, message: "请填写备注，说明转账事由", trigger: "blur" }],
  "payee_info.bankcard_ext_info.inst_name": [{
    validator: (_r: any, _v: any, cb: any) => {
      if (isCorporate.value && !transferForm.payee_info.bankcard_ext_info?.inst_name)
        cb(new Error("对公账户银行名称不能为空"));
      else cb();
    }, trigger: "blur"
  }],
};

const isCorporate = computed(() =>
  transferForm.payee_info.identity_type === "BANKCARD_ACCOUNT"
  && transferForm.payee_info.bankcard_ext_info?.account_type === "1"
);

const TRANSFER_SCENE_OPTIONS = [
  { value: "佣金报酬", label: "佣金报酬" },
  { value: "业务结算", label: "业务结算" },
  { value: "二手回收", label: "二手回收" },
];

const remarkPlaceholder = computed(() => {
  const map: Record<string, string> = {
    "佣金报酬": "请填写佣金报酬说明，如：8月家政服务报酬",
    "业务结算": "请填写结算款项名称，如：材料货款",
    "二手回收": "请填写回收商品名称，如：旧衣服",
  };
  return map[transferForm.transfer_scene_name] || "请填写转账事由";
});

const isAlipayPayee = computed(() =>
  transferForm.payee_info.identity_type === "ALIPAY_USER_ID"
  || transferForm.payee_info.identity_type === "ALIPAY_LOGON_ID"
);

const transferList = ref<any[]>([]);
const transferPage = reactive({
  page_no: 1,
  page_size: 10,
  total: 0,
});

const transferSearchForm = reactive({
  out_biz_no: "",
  status: "",
  tenant_id: undefined as number | undefined,
  enterprise_id: undefined as string | undefined,
});

const allTenantData = ref<TenantTable[]>([]);

const transferDetailVisible = ref(false);
const currentTransferOutBizNo = ref("");

// 批量转账相关
const batchTransferVisible = ref(false);
const batchTransferResultVisible = ref(false);
const batchTransferLoading = ref(false);
const showBatchTransferOverlay = ref(false);
const batchCurrentIndex = ref(0);
const batchTotalCount = ref(0);
const batchCurrentPayee = ref("");
const batchCurrentAmount = ref(0);
const fileList = ref<any[]>([]);
const batchTransferData = ref<any[]>([]);
const batchTransferResults = ref<any[]>([]);
const batchTransferSuccessCount = ref(0);
const batchTransferFailCount = ref(0);

const consumeForm = reactive({
  pay_no: "",
  enterprise_id: "",
  ant_shop_id: "",
  query_options: [] as string[],
});

const consumeRules: FormRules = {
  pay_no: [{ required: true, message: "请输入支付宝账单号", trigger: "blur" }],
};

const consumeDetail = ref<any>(null);

function getDepositStatusType(status: string) {
  const map: Record<string, any> = {
    DEALING: "warning",
    SUCCESS: "success",
    FAIL: "danger",
  };
  return map[status] || "info";
}

function getTransferStatusType(status: string) {
  const map: Record<string, any> = {
    DEALING: "warning",
    SUCCESS: "success",
    FAIL: "danger",
    REFUND: "warning",
  };
  return map[status] || "info";
}

function getPayeeTypeLabel(type: string) {
  const map: Record<string, string> = {
    ALIPAY_ACCOUNT: "支付宝",
    BANK_CARD: "银行卡",
    BOOK: "资金专户",
  };
  return map[type] || type;
}

function getStatusLabel(status: string) {
  const map: Record<string, string> = {
    DEALING: "处理中",
    SUCCESS: "成功",
    FAIL: "失败",
    REFUND: "退票",
  };
  return map[status] || status;
}

// 批量转账相关计算属性
const hasBankTransfer = computed(() => {
  return batchTransferData.value.some(item => item.payee_type === "bank");
});

const hasInvalidData = computed(() => {
  return batchTransferData.value.some(item => item.status === "invalid");
});

// 下载模板
function downloadTemplate() {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("批量转账模板");

  // 设置表头
  worksheet.columns = [
    { header: "转账金额", key: "amount", width: 15 },
    { header: "转账标题", key: "order_title", width: 20 },
    { header: "收款方姓名", key: "payee_name", width: 15 },
    { header: "收款方账号类型", key: "payee_type", width: 15 },
    { header: "收款方账号", key: "payee_account", width: 30 },
    { header: "银行账户类型（1：公司账户，2：个人账户）", key: "bank_type", width: 30 },
    { header: "银行名称（公司账户必填）", key: "bank_name", width: 20 },
    { header: "开户省份（非必填）", key: "bank_province", width: 15 },
    { header: "开户城市（非必填）", key: "bank_city", width: 15 },
    { header: "支行名称（非必填）", key: "bank_branch", width: 20 },
    { header: "联行号（非必填）", key: "bank_code", width: 15 },
    { header: "备注（非必填）", key: "remark", width: 20 },
  ];

  // 添加示例数据
  worksheet.addRow({ 
    amount: 100.00, 
    order_title: "测试转账", 
    payee_name: "张三", 
    payee_type: "支付宝", 
    payee_account: "zhangsan@example.com",
    remark: "测试" 
  });
  worksheet.addRow({ 
    amount: 200.00, 
    order_title: "测试转账", 
    payee_name: "李四", 
    payee_type: "银行卡", 
    payee_account: "6222021234567890123",
    bank_type: "1",
    bank_name: "中国工商银行",
    bank_province: "北京市",
    bank_city: "北京市",
    bank_branch: "中关村支行",
    bank_code: "102100004534",
    remark: "测试" 
  });

  // 生成并下载文件
  workbook.xlsx.writeBuffer().then(buffer => {
    const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "批量转账模板.xlsx";
    a.click();
    URL.revokeObjectURL(url);
  });
}

// 处理文件上传
async function handleFileChange(file: any) {
  fileList.value = [file.raw];
  await parseExcelFile(file.raw);
}

// 解析Excel文件
async function parseExcelFile(file: File) {
  try {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(await file.arrayBuffer());
    const worksheet = workbook.worksheets[0];
    
    const data: any[] = [];
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 1) { // 跳过表头
        const rowData = {
          amount: row.getCell(1).value,
          order_title: row.getCell(2).value,
          payee_name: row.getCell(3).value,
          payee_type: row.getCell(4).value,
          payee_account: (row.getCell(5).value || {}).text || row.getCell(5).value,
          bank_type: row.getCell(6).value,
          bank_name: row.getCell(7).value,
          bank_province: row.getCell(8).value,
          bank_city: row.getCell(9).value,
          bank_branch: row.getCell(10).value,
          bank_code: row.getCell(11).value,
          remark: row.getCell(12).value,
        };
        data.push(rowData);
      }
    });
    
    // 验证数据
    batchTransferData.value = data.map(item => validateTransferData(item));
  } catch (error) {
    ElMessage.error("文件解析失败，请检查文件格式");
    console.error(error);
  }
}

// 验证转账数据
function validateTransferData(data: any) {
  const result = {
    ...data,
    status: "valid",
    error_msg: "",
  };

  // 验证金额
  if (!data.amount || typeof data.amount !== "number" || data.amount < 0.02) {
    result.status = "invalid";
    result.error_msg = "转账金额必须大于等于0.02元";
    return result;
  }

  // 验证转账标题
  if (!data.order_title || data.order_title.toString().trim() === "") {
    result.status = "invalid";
    result.error_msg = "转账标题不能为空";
    return result;
  }

  // 验证收款方姓名
  if (!data.payee_name || data.payee_name.toString().trim() === "") {
    result.status = "invalid";
    result.error_msg = "收款方姓名不能为空";
    return result;
  }

  // 验证收款方类型
  if (!data.payee_type || !["支付宝", "银行卡"].includes(data.payee_type)) {
    result.status = "invalid";
    result.error_msg = "收款方类型必须是支付宝或银行卡";
    return result;
  }

  console.log(data.payee_account);
  // 验证收款方账号
  if (!data.payee_account || data.payee_account.toString().trim() === "") {
    result.status = "invalid";
    result.error_msg = "收款方账号不能为空";
    return result;
  }

  // 验证银行卡信息
  if (data.payee_type === "银行卡") {
    if (!data.bank_type || !["1", "2"].includes(data.bank_type.toString())) {
      console.log(typeof data.bank_type);
      result.status = "invalid";
      result.error_msg = "银行账户类型必须是1或2";
      return result;
    }
    if (data.bank_type === "1" && (!data.bank_name || data.bank_name.toString().trim() === "")) {
      result.status = "invalid";
      result.error_msg = "银行名称不能为空";
      return result;
    }
  }
  return result;
}

// 处理批量转账
async function handleBatchTransfer() {
  const validData = batchTransferData.value.filter(item => item.status === "valid");
  if (validData.length === 0) {
    ElMessage.warning("没有有效的转账数据");
    return;
  }

  ElMessageBox.confirm(
    `确定要批量转账 ${validData.length} 笔交易吗？`,
    "确认操作",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    // 开启遮罩
    showBatchTransferOverlay.value = true;
    batchTransferLoading.value = true;
    batchTotalCount.value = validData.length;
    batchCurrentIndex.value = 0;
    batchTransferResults.value = [];
    batchTransferSuccessCount.value = 0;
    batchTransferFailCount.value = 0;

    try {
      for (let i = 0; i < validData.length; i++) {
        const item = validData[i];
        batchCurrentIndex.value = i + 1;
        batchCurrentPayee.value = item.payee_name;
        batchCurrentAmount.value = item.amount;

        try {
          await AccountAPI.transfer({
            enterprise_id: currentEnterpriseId.value!,
            account_book_id: accountInfo.value.account_book_id,
            amount: item.amount,
            order_title: item.order_title.toString(),
            remark: item.remark?.toString() || "",
            payee_info: {
              identity_type: item.payee_type === "支付宝" ? "ALIPAY_USER_ID" : "BANKCARD_ACCOUNT",
              name: item.payee_name.toString(),
              identity: item.payee_account.toString(),
              bankcard_ext_info:
                item.payee_type === "银行卡"
                  ? {
                      account_type: item.bank_type?.toString(),
                      inst_name: item.bank_name?.toString(),
                      inst_province: item.bank_province?.toString(),
                      inst_city: item.bank_city?.toString(),
                      inst_branch_name: item.bank_branch?.toString(),
                      bank_code: item.bank_code?.toString(),
                    }
                  : undefined,
            },
          });
          batchTransferResults.value.push({
            amount: item.amount,
            payee_name: item.payee_name,
            status: "success",
            message: "转账成功",
          });
          batchTransferSuccessCount.value++;
        } catch (error: any) {
          batchTransferResults.value.push({
            amount: item.amount,
            payee_name: item.payee_name,
            status: "fail",
            message: error.message || "转账失败",
          });
          batchTransferFailCount.value++;
        }
      }

      // 完成后隐藏遮罩
      showBatchTransferOverlay.value = false;

      // 刷新转账记录
      await handleTransferSearch();

      // 关闭批量转账对话框，显示结果
      batchTransferResultVisible.value = true;
      batchTransferVisible.value = false;
    } catch (error) {
      showBatchTransferOverlay.value = false;
      ElMessage.error("批量转账过程出错");
    } finally {
      batchTransferLoading.value = false;
    }
  });
}

// 打开批量转账对话框
function openBatchTransferDialog() {
  // 重置数据
  resetBatchTransfer();
  // 打开对话框
  batchTransferVisible.value = true;
}

// 重置批量转账
function resetBatchTransfer() {
  batchTransferVisible.value = false;
  batchTransferResultVisible.value = false;
  showBatchTransferOverlay.value = false;
  batchCurrentIndex.value = 0;
  batchTotalCount.value = 0;
  batchCurrentPayee.value = "";
  batchCurrentAmount.value = 0;
  fileList.value = [];
  batchTransferData.value = [];
  batchTransferResults.value = [];
  batchTransferSuccessCount.value = 0;
  batchTransferFailCount.value = 0;
}

async function handleAuthorize() {
  try {
    const res = await AccountAPI.authorizeApply({
      enterprise_id: currentEnterpriseId.value!,
    });
    const signHtml = res.data.data?.sign_url || "";
    const externalAgreementNo = res.data.data?.external_agreement_no || "";
    authorizeResult.sign_url = signHtml;
    authorizeResult.external_agreement_no = externalAgreementNo;
    // pageExecute 返回 HTML 表单，自带自动提交，直接渲染到当前页自动重定向到支付宝
    document.open();
    document.write(signHtml);
    document.close();
  } finally {
    authorizeLoading.value = false;
  }
}

async function handleQueryAgreement() {
  if (!authorizeResult.external_agreement_no) {
    ElMessage.warning("请先申请签约");
    return;
  }
  authorizeResult.queryLoading = true;
  try {
    const res = await AccountAPI.queryAgreement(
      currentEnterpriseId.value!,
      authorizeResult.external_agreement_no,
    );
    const agreementNo = res.data.data?.agreement_no || "";
    if (agreementNo) {
      authorizeResult.agreement_no = agreementNo;
      createForm.agreement_no = agreementNo;
      ElMessage.success("签约协议号已获取: " + agreementNo);
    } else {
      ElMessage.warning("尚未完成签约，请在支付宝中完成签约后再查询");
    }
  } finally {
    authorizeResult.queryLoading = false;
  }
}

function handleAuthorizeReset() {
  authorizeFormRef.value?.resetFields();
  authorizeResult.sign_url = "";
  authorizeResult.external_agreement_no = "";
  authorizeResult.agreement_no = "";
}

async function handleCreate() {
  // if (!createFormRef.value) return;
  // await createFormRef.value.validate(async (valid) => {
  //   if (valid) {
  //     if (authorizeStatus.value !== "AUTHORIZED") {
  //       ElMessage.warning("请先完成转账授权签约");
  //       return;
  //     }
  //     createLoading.value = true;
  //     try {
  //       const res = await AccountAPI.create({
  //         enterprise_id: createForm.enterprise_id || currentEnterpriseId.value!,
  //         account_type: createForm.account_type,
  //         scene: createForm.scene,
  //         remark: createForm.remark,
  //       });
  //       createResult.enterprise_id = res.data.enterprise_id || "";
  //       createResult.account_book_id = res.data.account_book_id || "";
  //       accountInfo.value.account_book_id = createResult.account_book_id;
  //       accountInfo.value.status = "ACTIVE";
  //       overviewRef.value?.refresh();
  //     } finally {
  //       createLoading.value = false;
  //     }
  //   }
  // });

  try {
    const res = await AccountAPI.create({
      enterprise_id: currentEnterpriseId.value!,
      agreement_no: createForm.agreement_no || undefined,
      account_type: "ALL",
      scene: "B2B_TRANS",
      remark: "",
    });
    createResult.enterprise_id = res.data.data.enterprise_id || "";
    createResult.account_book_id = res.data.data.account_book_id || "";
    accountInfo.value.account_book_id = createResult.account_book_id;
    accountInfo.value.status = "AUTHORIZED";
    overviewRef.value?.refresh();
  } finally {
    createLoading.value = false;
  }
}

function handleCreateReset() {
  createFormRef.value?.resetFields();
  createResult.enterprise_id = "";
  createResult.account_book_id = "";
}

async function handleDeposit() {
  if (!depositFormRef.value) return;
  await depositFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!accountInfo.value.account_book_id) {
        ElMessage.warning("请先开通资金专户");
        return;
      }
      depositLoading.value = true;
      try {
        const res = await AccountAPI.deposit({
          enterprise_id: currentEnterpriseId.value!,
          account_book_id: accountInfo.value.account_book_id,
          amount: depositForm.amount,
          remark: depositForm.remark,
        });
        const depositHtml = res.data.data?.url || "";
        depositResult.url = depositHtml;
        // pageExecute 返回 HTML 表单，自带自动提交，直接渲染到当前页自动重定向到支付宝
        document.open();
        document.write(depositHtml);
        document.close();
      } finally {
        depositLoading.value = false;
      }
    }
  });
}

function handleDepositReset() {
  depositFormRef.value?.resetFields();
  depositResult.url = "";
}

async function handleTransfer() {
  if (!transferFormRef.value) return;
  await transferFormRef.value.validate(async (valid) => {
    if (valid) {
      if (accountInfo.value.balance <= 0) {
        ElMessage.warning("账户余额不足，请先充值");
        return;
      }
      transferLoading.value = true;
      try {
        await AccountAPI.transfer({
          enterprise_id: currentEnterpriseId.value!,
          account_book_id: accountInfo.value.account_book_id,
          amount: transferForm.amount,
          order_title: transferForm.order_title,
          remark: transferForm.remark,
          transfer_scene_name: transferForm.transfer_scene_name,
          payee_info: {
            identity_type: transferForm.payee_info.identity_type,
            name: transferForm.payee_info.name,
            identity: transferForm.payee_info.identity,
            bankcard_ext_info:
              transferForm.payee_info.identity_type === "BANKCARD_ACCOUNT"
                ? transferForm.payee_info.bankcard_ext_info
                : undefined,
          },
          ext_info:
            transferForm.payee_info.identity_type === "BANKCARD_ACCOUNT"
              ? { withdraw_timeliness: transferForm.withdraw_timeliness }
              : undefined,
        });
        // ElMessage.success("转账申请已提交");
        handleTransferListChange();
        handleTransferReset();
      } finally {
        transferLoading.value = false;
      }
    }
  });
}

function handleTransferReset() {
  transferFormRef.value?.resetFields();
  transferForm.withdraw_timeliness = "T1";
  transferForm.payee_info = {
    identity_type: "ALIPAY_USER_ID",
    name: "",
    identity: "",
    bankcard_ext_info: {
      account_type: "2",
      inst_name: "",
      inst_province: "",
      inst_city: "",
      inst_branch_name: "",
      bank_code: "",
    },
  };
}

// ===== 提现 =====
const withdrawVisible = ref(false);
const withdrawLoading = ref(false);
const withdrawFormRef = ref<FormInstance>();
const withdrawForm = reactive({ amount: 0, remark: "" });

const withdrawRules: FormRules = {
  amount: [
    { required: true, message: "请输入提现金额", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (value <= 0) callback(new Error("提现金额必须大于0"));
        else if (value > accountInfo.value.balance) callback(new Error("提现金额不能超过账户余额"));
        else callback();
      },
      trigger: "blur",
    },
  ],
};

async function handleWithdraw() {
  const valid = await withdrawFormRef.value?.validate().catch(() => false);
  if (!valid) return;
  withdrawLoading.value = true;
  try {
    await AccountAPI.withdraw({
      enterprise_id: enterpriseStore.getCurrentEnterprise?.enterprise_id || "",
      account_book_id: accountInfo.value.account_book_id,
      amount: withdrawForm.amount,
      remark: withdrawForm.remark || "提现",
    });
    ElMessage.success("提现成功");
    withdrawVisible.value = false;
    withdrawForm.amount = 0;
    withdrawForm.remark = "";
    overviewRef.value?.refresh();
    handleTransferSearch();
  } finally {
    withdrawLoading.value = false;
  }
}

async function handleTransferSearch() {
  transferPage.page_no = 1;
  await fetchTransferList();
}

function handleTransferSearchReset() {
  transferSearchForm.out_biz_no = "";
  transferSearchForm.status = "";
  transferSearchForm.tenant_id = undefined;
  transferSearchForm.enterprise_id = undefined;
  handleTransferSearch();
}

async function fetchTransferList() {
  transferListLoading.value = true;
  try {
    const res = await AccountAPI.transferList({
      page_no: transferPage.page_no,
      page_size: transferPage.page_size,
      out_biz_no: transferSearchForm.out_biz_no || undefined,
      status: transferSearchForm.status || undefined,
      tenant_id: transferSearchForm.tenant_id || undefined,
      enterprise_id: transferSearchForm.enterprise_id || undefined,
    });
    transferList.value = res.data.data?.items || res.data.data?.list || [];
    transferPage.total = res.data.data.total || 0;
  } finally {
    transferListLoading.value = false;
  }
}

function handleTransferListChange() {
  fetchTransferList();
}

async function fetchAllTenantData() {
  try {
    const res = await TenantAPI.listTenant({ page_no: 1, page_size: 100 });
    allTenantData.value = [{ id: undefined as any, name: "全部" }, ...(res.data.data?.items || [])];
  } catch (error) {
    console.error("获取所有租户数据失败:", error);
  }
}

// ========== 消费记录 ==========

const consumeRecordList = ref<any[]>([]);
const consumeListLoading = ref(false);
const consumePage = reactive({ page_no: 1, page_size: 10, total: 0 });
const consumeSearchForm = reactive({
  tenant_id: undefined as number | undefined,
  enterprise_id: undefined as string | undefined,
  consume_type: undefined as string | undefined,
  status: undefined as string | undefined,
  start_time: undefined as string | undefined,
  end_time: undefined as string | undefined,
  dateRange: null as Date[] | null,
});

function handleConsumeDateChange() {
  if (consumeSearchForm.dateRange && consumeSearchForm.dateRange.length === 2) {
    consumeSearchForm.start_time = (consumeSearchForm.dateRange as any)[0];
    consumeSearchForm.end_time = (consumeSearchForm.dateRange as any)[1];
  } else {
    consumeSearchForm.start_time = undefined;
    consumeSearchForm.end_time = undefined;
  }
}

async function fetchConsumeList() {
  consumeListLoading.value = true;
  try {
    const res = await AccountAPI.consumeList({
      page_no: consumePage.page_no,
      page_size: consumePage.page_size,
      tenant_id: consumeSearchForm.tenant_id || undefined,
      enterprise_id: consumeSearchForm.enterprise_id || undefined,
      consume_type: consumeSearchForm.consume_type || undefined,
      status: consumeSearchForm.status || undefined,
      start_time: consumeSearchForm.start_time || undefined,
      end_time: consumeSearchForm.end_time || undefined,
    });
    consumeRecordList.value = res.data.data?.items || res.data.data?.list || [];
    consumePage.total = res.data.data.total || 0;
  } finally {
    consumeListLoading.value = false;
  }
}

function handleConsumeSearch() { consumePage.page_no = 1; fetchConsumeList(); }
function handleConsumeSearchReset() {
  consumeSearchForm.tenant_id = undefined;
  consumeSearchForm.enterprise_id = undefined;
  consumeSearchForm.consume_type = undefined;
  consumeSearchForm.status = undefined;
  consumeSearchForm.start_time = undefined;
  consumeSearchForm.end_time = undefined;
  consumeSearchForm.dateRange = null;
  handleConsumeSearch();
}
function handleConsumeListChange() { fetchConsumeList(); }

function getConsumeTypeTag(type: string) {
  const map: Record<string, any> = { CONSUME: '', REFUND: 'warning', TRANSFER: 'info' };
  return map[type] || 'info';
}
function getConsumeTypeLabel(type: string) {
  const map: Record<string, string> = { CONSUME: '消费', REFUND: '退款', TRANSFER: '转账' };
  return map[type] || type;
}
function getConsumeStatusType(status: string) {
  const map: Record<string, any> = { NEW: 'info', PROCESSED: 'success' };
  return map[status] || 'info';
}
function getConsumeStatusLabel(status: string) {
  const map: Record<string, string> = { NEW: '未处理', PROCESSED: '已处理' };
  return map[status] || status;
}

function handleViewTransferDetail(outBizNo: string) {
  currentTransferOutBizNo.value = outBizNo;
  transferDetailVisible.value = true;
}

function downloadFile(url: string) {
  window.open(url, "_blank");
}

async function handleDownloadReceipt(row: any) {
  const loadingText = ref("获取回单中...");
  const loadingInstance = ElMessage({
    message: loadingText.value,
    type: "loading",
    duration: 0,
  });

  try {
    const res = await AccountAPI.downloadReceipt({
      enterprise_id: currentEnterpriseId.value!,
      order_no: row.order_no,
    });

    const { file_id, status, download_url, error_message } = res.data.data;

    if (status === "SUCCESS" && download_url) {
      downloadFile(download_url);
      ElMessage.success("回单下载成功");
    } else if (status === "FAIL") {
      ElMessage.error(`回单生成失败: ${error_message || "未知错误"}`);
    } else if (status === "PROCESS" || status === "INIT") {
      await pollForReceipt(file_id);
    } else {
      ElMessage.info("回单状态未知，请稍后尝试");
    }
  } catch (error: any) {
    ElMessage.error(error.message || "获取回单失败");
  } finally {
    loadingInstance.close();
  }
}

async function pollForReceipt(file_id: string) {
  const maxRetries = 3;
  const retryInterval = 3000;
  let retryCount = 0;

  while (retryCount < maxRetries) {
    await new Promise(resolve => setTimeout(resolve, retryInterval));
    retryCount++;

    try {
      const res = await AccountAPI.queryReceipt({
        enterprise_id: currentEnterpriseId.value!,
        file_id,
      });

      const { status, download_url, error_message } = res.data.data;

      if (status === "SUCCESS" && download_url) {
        downloadFile(download_url);
        ElMessage.success("回单下载成功");
        return;
      } else if (status === "FAIL") {
        ElMessage.error(`回单生成失败: ${error_message || "未知错误"}`);
        return;
      }
    } catch (error: any) {
      ElMessage.error(`轮询失败: ${error.message}`);
      return;
    }
  }

  ElMessage.info("回单正在生成中，请稍后手动刷新页面重试");
}

function handleTransferDetailRefresh() {
  fetchTransferList();
}

async function handleConsumeQuery() {
  if (!consumeFormRef.value) return;
  await consumeFormRef.value.validate(async (valid) => {
    if (valid) {
      consumeLoading.value = true;
      try {
        const res = await AccountAPI.consumeDetail({
          pay_no: consumeForm.pay_no,
          enterprise_id: consumeForm.enterprise_id || currentEnterpriseId.value || undefined,
          ant_shop_id: consumeForm.ant_shop_id || undefined,
          query_options: consumeForm.query_options.length > 0 ? consumeForm.query_options : undefined,
        });
        consumeDetail.value = res.data;
      } finally {
        consumeLoading.value = false;
      }
    }
  });
}

function handleConsumeReset() {
  consumeFormRef.value?.resetFields();
  consumeDetail.value = null;
}

function handleOverviewRefresh(data: any) {
  if (data) {
    accountInfo.value = {
      account_book_id: data.account_book_id || "",
      status: data.status || "",
      balance: data.balance || 0,
      onboard_status: data.onboard_status || "PENDING",
    };
    authorizeStatus.value = data.authorize_status || "PENDING";
  }
}

async function handleGoTab(tab: string) {
  console.log("goTab => ", tab);
  if (tab === "authorize") {
    await handleAuthorize();
  } else if (tab === "onboard") {
    onboardDialogVisible.value = true;
  } else if (tab === "create") {
    await handleCreate();
  } else if (tab === "deposit") {
    activeTab.value = tab;
  } else if (tab === "transfer") {
    activeTab.value = tab;
  }
}

onMounted(async () => {
  if (is_platform_user.value) {
    await fetchAllTenantData();
  }
  await enterpriseStore.loadEnterpriseList();
  if (!is_platform_user.value) {
    transferSearchForm.enterprise_id = currentEnterpriseId.value;
    consumeSearchForm.enterprise_id = currentEnterpriseId.value;
  }
  if (currentEnterpriseId.value) {
    authorizeForm.enterprise_id = currentEnterpriseId.value;
    createForm.enterprise_id = currentEnterpriseId.value;
    depositForm.enterprise_id = currentEnterpriseId.value;
    transferForm.enterprise_id = currentEnterpriseId.value;
    consumeForm.enterprise_id = currentEnterpriseId.value;
  }
});

watch(activeTab, async (newValue) => {
  if (newValue === "transfer") {
    await handleTransferSearch();
  }
  if (newValue === "consume-record") {
    await handleConsumeSearch();
  }
})

// watch(batchTransferVisible, (newValue) => {
//   if (!newValue) {
//     resetBatchTransfer();
//   }
// })

onMounted(async() => {
  pageLoading.value = true;
  try {
    await overviewRef.value?.refresh();
  } finally {
    pageLoading.value = false;
  }
});

async function handleDownload() {
  downloadLoading.value = true;
  try {
    let start_time: string;
    let end_time: string;

    if (selectedQuickOption.value !== "custom") {
      const range = calculateTimeRange(selectedQuickOption.value);
      start_time = range.start_time;
      end_time = range.end_time;
    } else {
      if (!customDateRange.value || customDateRange.value.length !== 2) {
        ElMessage.warning("请选择时间范围");
        return;
      }
      const [start, end] = customDateRange.value;
      start_time = formatDateTime(start, "start");
      end_time = formatDateTime(end, "end");
    }

    const res = await AccountAPI.exportTransferReport({
      start_time,
      end_time,
      enterprise_id: currentEnterpriseId.value || undefined,
    });

    const blob = new Blob([res.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `转账报表_${start_time}_${end_time}.xlsx`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);

    ElMessage.success("报表下载成功");
    showDownloadMenu.value = false;
    selectedQuickOption.value = "today";
    customDateRange.value = null;
  } catch (error) {
    ElMessage.error("下载失败，请稍后重试");
  } finally {
    downloadLoading.value = false;
  }
}

function calculateTimeRange(type: string): { start_time: string; end_time: string } {
  const now = new Date();
  const start = new Date();

  switch (type) {
    case "today":
      start.setHours(0, 0, 0, 0);
      break;
    case "3days":
      start.setDate(now.getDate() - 3);
      start.setHours(0, 0, 0, 0);
      break;
    case "15days":
      start.setDate(now.getDate() - 15);
      start.setHours(0, 0, 0, 0);
      break;
    case "30days":
      start.setDate(now.getDate() - 30);
      start.setHours(0, 0, 0, 0);
      break;
  }

  const end = new Date(now);
  end.setHours(23, 59, 59, 999);

  return {
    start_time: formatDateTime(start),
    end_time: formatDateTime(end),
  };
}

function formatDateTime(date: Date, type: string = "start"): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  
  if (type === "start") {
    return `${year}-${month}-${day} 00:00:00`;
  } else {
    return `${year}-${month}-${day} 23:59:59`;
  }
}

function handleCustomDateChange() {
  if (customDateRange.value && customDateRange.value.length === 2) {
    selectedQuickOption.value = "custom";
  }
}

</script>

<style lang="scss" scoped>
.account-tabs {
  height: 100%;

  :deep(.el-tabs__content) {
    height: calc(100% - 40px);
    overflow-y: auto;
  }
}

.tab-content {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-4 {
  margin-top: 16px;
}

.ml-2 {
  margin-left: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.flex {
  display: flex;
}

.justify-end {
  justify-content: flex-end;
}

.authorize-result,
.create-result,
.deposit-result {
  margin-top: 20px;
}

.batch-transfer-container {
  position: relative;

  &.has-overlay {
    pointer-events: none;
  }
}

.batch-transfer-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border-radius: 8px;

  .overlay-content {
    text-align: center;
    padding: 40px;

    h3 {
      margin: 20px 0;
      color: #303133;
    }

    p {
      margin: 15px 0;
      color: #606266;
    }

    .result-summary {
      display: flex;
      gap: 15px;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

.download-options {
  .option-group {
    .option-title {
      font-size: 14px;
      font-weight: 500;
      color: #606266;
      margin-bottom: 12px;
    }

    .option-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
}
</style>
