<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="内购记录ID" prop="purchaseRecordId">
        <el-input v-model="queryParams.purchaseRecordId" placeholder="请输入内购记录ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="内购交易ID" prop="transactionId">
        <el-input v-model="queryParams.transactionId" placeholder="请输入内购交易ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="购买用户ID" prop="inviteeUserId">
        <el-input v-model="queryParams.inviteeUserId" placeholder="请输入购买用户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="邀请人用户ID" prop="inviterUserId">
        <el-input v-model="queryParams.inviterUserId" placeholder="请输入邀请人用户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="内购时间" prop="purchaseTime">
        <el-date-picker v-model="queryParams.purchaseTime" 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-220px" />
      </el-form-item>
      <el-form-item label="内购金额" prop="purchaseAmount">
        <el-input v-model="queryParams.purchaseAmount" placeholder="请输入内购金额" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="分成比例" prop="commissionRate">
        <el-input v-model="queryParams.commissionRate" placeholder="请输入分成比例" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="分成金额" prop="commissionAmount">
        <el-input v-model="queryParams.commissionAmount" placeholder="请输入分成金额" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="结算时间" prop="settledAt">
        <el-date-picker v-model="queryParams.settledAt" value-format="YYYY-MM-DD" type="date" placeholder="选择结算时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="余额交易ID" prop="balanceTransactionId">
        <el-input v-model="queryParams.balanceTransactionId" placeholder="请输入余额交易ID" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="创建时间" prop="createdAt">
        <el-date-picker v-model="queryParams.createdAt" value-format="YYYY-MM-DD" type="date" placeholder="选择创建时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="更新时间" prop="updatedAt">
        <el-date-picker v-model="queryParams.updatedAt" value-format="YYYY-MM-DD" type="date" placeholder="选择更新时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable @keyup.enter="handleQuery"
          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="primary" plain @click="openForm('create')" v-hasPermi="['keyboard:tenant-commission:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:tenant-commission:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:tenant-commission:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button link type="primary" @click="toggleMore">
          <Icon :icon="showMore ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showMore ? '收起' : '更多条件' }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <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="90px" />
      <el-table-column label="内购记录ID" align="center" prop="purchaseRecordId" width="110px" />
      <el-table-column label="内购交易ID" align="center" prop="transactionId" min-width="160px" />
      <el-table-column label="购买用户ID" align="center" prop="inviteeUserId" width="110px" />
      <el-table-column label="邀请人用户ID" align="center" prop="inviterUserId" width="110px" />
      <el-table-column label="内购金额" align="center" prop="purchaseAmount" width="110px" />
      <el-table-column label="分成比例" align="center" prop="commissionRate" width="100px" />
      <el-table-column label="分成金额" align="center" prop="commissionAmount" width="110px" />
      <el-table-column label="状态" align="center" prop="status" width="120px">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="内购时间" align="center" prop="purchaseTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="结算时间" align="center" prop="settledAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="余额交易ID" align="center" prop="balanceTransactionId" width="110px" />
      <el-table-column label="创建时间" align="center" prop="createdAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="更新时间" align="center" prop="updatedAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="备注" align="center" prop="remark" min-width="140px" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-hasPermi="['keyboard:tenant-commission:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:tenant-commission: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>

  <!-- 表单弹窗：添加/修改 -->
  <TenantCommissionForm 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 { TenantCommissionApi, TenantCommission } from '@/api/keyboard/tenantcommission'
import TenantCommissionForm from './TenantCommissionForm.vue'
// import * as TenantApi from '@/api/system/tenant'
/** 租户内购分成记录 列表 */
defineOptions({ name: 'KeyboardTenantCommission' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
// const userData = ref()
const loading = ref(true) // 列表的加载中
const list = ref<TenantCommission[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const showMore = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  purchaseRecordId: undefined,
  transactionId: undefined,
  inviteeUserId: undefined,
  inviterUserId: undefined,
  purchaseAmount: undefined,
  commissionRate: undefined,
  commissionAmount: undefined,
  status: undefined,
  purchaseTime: [],
  settledAt: undefined,
  balanceTransactionId: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  remark: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const statusOptions = [
  { label: '待结算', value: 'PENDING', tagType: 'info' },
  { label: '已结算', value: 'SETTLED', tagType: 'success' },
  { label: '已退款', value: 'REFUNDED', tagType: 'warning' }
]


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TenantCommissionApi.getTenantCommissionPage(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 toggleMore = () => {
  showMore.value = !showMore.value
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TenantCommissionApi.deleteTenantCommission(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除租户内购分成记录 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await TenantCommissionApi.deleteTenantCommissionList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

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

const getStatusOption = (status: unknown) => {
  return statusOptions.find((item) => String(item.value) === String(status))
}

const getStatusLabel = (status: unknown) => {
  return getStatusOption(status)?.label ?? '-'
}

const getStatusTagType = (status: unknown) => {
  return getStatusOption(status)?.tagType ?? 'info'
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TenantCommissionApi.exportTenantCommission(queryParams)
    download.excel(data, '租户内购分成记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()
  // userData.value = await TenantApi.getcurrent()
})
</script>
