<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="产品ID" prop="productId">
        <el-input v-model="queryParams.productId" placeholder="请输入产品ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="购买类型" prop="purchaseType">
        <el-select v-model="queryParams.purchaseType" placeholder="请选择购买类型" clearable class="!w-240px">
          <el-option v-for="item in purchaseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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="price">
        <el-input v-model="queryParams.price" placeholder="请输入实际价格" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="购买数量" prop="purchaseQuantity">
        <el-input v-model="queryParams.purchaseQuantity" placeholder="请输入购买数量" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="货币" prop="currency">
        <el-input v-model="queryParams.currency" placeholder="请输入货币类型" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="支付方式" prop="paymentMethod">
        <el-input v-model="queryParams.paymentMethod" placeholder="请输入支付方式" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" 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 v-show="showMore" label="原始交易ID" prop="originalTransactionId">
        <el-input v-model="queryParams.originalTransactionId" placeholder="请输入原始交易ID" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="产品ID列表" prop="productIds">
        <el-input v-model="queryParams.productIds" placeholder="请输入产品ID列表" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="苹果购买时间" prop="purchaseDate">
        <el-date-picker v-model="queryParams.purchaseDate" 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 v-show="showMore" label="苹果过期时间" prop="expiresDate">
        <el-date-picker v-model="queryParams.expiresDate" 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 v-show="showMore" label="苹果环境" prop="environment">
        <el-input v-model="queryParams.environment" 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:user-purchase-records:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:user-purchase-records:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:user-purchase-records: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="userId" width="110px" />
      <el-table-column label="产品ID" align="center" prop="productId" min-width="140px" />
      <el-table-column label="购买数量" align="center" prop="purchaseQuantity" width="110px" />
      <el-table-column label="实际价格" align="center" prop="price" width="110px" />
      <el-table-column label="货币" align="center" prop="currency" width="90px" />
      <el-table-column label="购买时间" align="center" prop="purchaseTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="购买类型" align="center" prop="purchaseType" width="110px">
        <template #default="{ row }">
          <span>{{ getPurchaseTypeLabel(row.purchaseType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="购买状态" align="center" prop="status" width="110px">
        <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="paymentMethod" width="120px" />
      <el-table-column label="交易ID" align="center" prop="transactionId" min-width="160px" />
      <el-table-column label="原始交易ID" align="center" prop="originalTransactionId" min-width="160px" />
      <el-table-column label="产品ID列表" align="center" prop="productIds" min-width="180px" />
      <el-table-column label="苹果购买时间" align="center" prop="purchaseDate" :formatter="dateFormatter" width="180px" />
      <el-table-column label="苹果过期时间" align="center" prop="expiresDate" :formatter="dateFormatter" width="180px" />
      <el-table-column label="苹果环境" align="center" prop="environment" width="120px" />
      <!-- <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:user-purchase-records:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:user-purchase-records: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>

  <!-- 表单弹窗：添加/修改 -->
  <UserPurchaseRecordsForm 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 { UserPurchaseRecordsApi, UserPurchaseRecords } from '@/api/keyboard/userpurchaserecords'
import UserPurchaseRecordsForm from './UserPurchaseRecordsForm.vue'

/** 用户内购记录 列表 */
defineOptions({ name: 'KeyboardUserPurchaseRecords' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<UserPurchaseRecords[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const showMore = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  productId: undefined,
  purchaseQuantity: undefined,
  price: undefined,
  currency: undefined,
  purchaseTime: [],
  purchaseType: undefined,
  status: undefined,
  paymentMethod: undefined,
  transactionId: undefined,
  originalTransactionId: undefined,
  productIds: undefined,
  purchaseDate: [],
  expiresDate: [],
  environment: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const purchaseTypeOptions = [
  { label: '内购', value: '内购' },
  { label: '订阅', value: '订阅' }
]
const statusOptions = [
  { label: '已支付', value: 'PAID', tagType: 'success' },
  { label: '已退款', value: 'REFUNDED', tagType: 'warning' }
]

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserPurchaseRecordsApi.getUserPurchaseRecordsPage(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 UserPurchaseRecordsApi.deleteUserPurchaseRecords(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

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

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: UserPurchaseRecords[]) => {
  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 getPurchaseTypeLabel = (type: unknown) => {
  const option = purchaseTypeOptions.find((item) => String(item.value) === String(type))
  return option?.label ?? (type === null || type === undefined || type === '' ? '-' : String(type))
}

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

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
