<template>
  <ContentWrap>
    <!-- 工具栏 -->
    <div class="mb-12px flex items-center justify-between">
      <!-- <div class="flex items-center gap-8px">
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['keyboard:tenant-balance:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>

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

      <div class="flex items-center gap-8px">
        <el-switch v-model="showMoreColumns" inline-prompt active-text="更多列" inactive-text="精简" />
      </div>
    </div>

    <!-- 搜索栏（新增） -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="全部" clearable class="!w-180px">
          <el-option label="提现成功" value="WITHDRAW_SUCCESS" />
          <el-option label="发起提现" value="FREEZE" />
          <el-option label="退还佣金" value="WITHDRAW_REJECTED" />
          <el-option label="充值佣金" value="RECHARGE" />
          <el-option label="提现取消" value="WITHDRAW_CANCELED" />
          <el-option label="提现失败" value="WITHDRAW_FAILED" />
        </el-select>
      </el-form-item>


      <el-form-item label="订单号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="订单 Id/业务单号" clearable class="!w-220px" />
      </el-form-item>

      <el-form-item label="流水号" prop="bizNo">
        <el-input v-model="queryParams.bizNo" placeholder="业务流水号" clearable class="!w-220px" />
      </el-form-item>

      <el-form-item label="操作人" prop="operatorId">
        <el-input v-model="queryParams.operatorId" placeholder="操作人 Id" clearable class="!w-160px" />
      </el-form-item>

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

    <!-- 表格 -->
    <el-table 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="ID" align="center" prop="id" width="90" /> -->

      <!-- points：正负突出 -->
      <el-table-column label="变动点数" align="center" prop="points" width="120">
        <template #default="{ row }">
          <el-tag v-if="Number(row.points) > 0" type="success">+{{ row.points }}</el-tag>
          <el-tag v-else-if="Number(row.points) < 0" type="danger">{{ row.points }}</el-tag>
          <el-tag v-else type="info">0</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="不可提现余额" align="center" prop="balance" width="120" />
      <el-table-column label="冻结金额" align="center" prop="frozenAmt" width="120" />
      <el-table-column label="可提现金额" align="center" prop="withdrawableBalance" width="120" />

      <!-- type：tag -->
      <!-- <el-table-column label="类型" align="center" prop="type" width="150">
        <template #default="{ row }">
          <el-tag v-if="row.type === 'WITHDRAW_SUCCESS'" type="success">提现成功</el-tag>
          <el-tag v-else-if="row.type === 'FREEZE'" type="warning">发起提现</el-tag>
          <el-tag v-else-if="row.type === 'WITHDRAW_REJECTED'" type="info">退还佣金</el-tag>
          <el-tag v-else-if="row.type === 'RECHARGE'" type="primary">充值佣金</el-tag>
          <el-tag v-else-if="row.type === 'WITHDRAW_CANCELED'" type="primary">提现取消</el-tag>
          <el-tag v-else-if="row.type === 'WITHDRAW_FAILED'" type="error">提现失败</el-tag>
          <el-tag v-else>{{ row.type }}</el-tag>
        </template>
      </el-table-column> -->

      <!-- 合并：描述/备注 -->
      <el-table-column label="说明" align="left" min-width="260">
        <template #default="{ row }">
          <div class="leading-18px">
            <div class="font-500">{{ row.description || '-' }}</div>
            <div class="text-gray-500 text-12px mt-2px" v-if="row.remark">
              备注：{{ row.remark }}
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 订单号/流水号：默认展示 -->
      <el-table-column label="订单号" align="center" prop="orderId" min-width="160" />
      <el-table-column label="流水号" align="center" prop="bizNo" min-width="180" />

      <!-- 更多列（开关控制） -->
      <el-table-column v-if="showMoreColumns" label="操作人" align="center" prop="operatorId" width="120" />
      <el-table-column label="创建时间" align="center" prop="createdAt" :formatter="dateFormatter" width="180px" />

      <!-- <el-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['keyboard:tenant-balance:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:tenant-balance: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>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { isEmpty } from '@/utils/is'
import { TenantBalanceApi, TenantBalanceTransaction } from '@/api/keyboard/tenantbalance'

import TenantBalanceTransactionForm from './TenantBalanceTransactionForm.vue'

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

const props = defineProps<{ tenantId?: number }>()

const loading = ref(false)
const list = ref<any[]>([])
const total = ref(0)

const showMoreColumns = ref(false)

const queryFormRef = ref()

// ✅ 增加查询字段（不影响后端的话就直接透传；如果后端不支持，你就把不支持的删掉）
// 说明：createdAtRange 需要你后端支持数组区间；不支持的话，我可以按你后端参数名改成 start/end
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  tenantId: undefined as unknown,

  type: undefined as any,
  orderId: undefined as any,
  bizNo: undefined as any,
  operatorId: undefined as any,
  createdAtRange: [] as string[]
})

watch(
  () => props.tenantId,
  (val: number) => {
    if (!val) {
      list.value = []
      return
    }
    queryParams.tenantId = val
    handleQuery()
  },
  { immediate: true, deep: true }
)

const getList = async () => {
  loading.value = true
  try {
    const data = await TenantBalanceApi.getTenantBalanceTransactionPage(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) => {
  if (!props.tenantId) {
    message.error('请选择一个租户余额')
    return
  }
  formRef.value.open(type, id, props.tenantId)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await TenantBalanceApi.deleteTenantBalanceTransaction(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await TenantBalanceApi.deleteTenantBalanceTransactionList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: TenantBalanceTransaction[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

const refresh = () => {
  if (!props.tenantId) return
  handleQuery()
}
defineExpose({ refresh })
</script>
