<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="邀请码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入邀请码" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="邀请人用户ID" prop="ownerUserId">
        <el-input v-model="queryParams.ownerUserId" 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="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="expiresAt">
        <el-date-picker v-model="queryParams.expiresAt" value-format="YYYY-MM-DD" type="date" placeholder="选择过期时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="最大可用次数" prop="maxUses">
        <el-input v-model="queryParams.maxUses" placeholder="请输入最大可用次数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="已使用次数" prop="usedCount">
        <el-input v-model="queryParams.usedCount" placeholder="请输入已使用次数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="系统用户ID" prop="systemUserId">
        <el-input v-model="queryParams.systemUserId" placeholder="请输入系统用户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="所属租户" prop="ownerTenantId">
        <el-input v-model="queryParams.ownerTenantId" placeholder="请输入所属租户" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="所属系统用户" prop="owenrSystemUserId">
        <el-input v-model="queryParams.owenrSystemUserId" placeholder="请输入所属系统用户" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="邀请码类型" prop="inviteType">
        <el-select v-model="queryParams.inviteType" placeholder="请选择邀请码类型" clearable class="!w-240px">
          <el-option v-for="item in inviteTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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-invite-codes:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:user-invite-codes:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:user-invite-codes: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="邀请码" align="center" prop="code" min-width="160px" />
      <el-table-column label="邀请人用户ID" align="center" prop="ownerUserId" width="130px" />
      <el-table-column label="状态" align="center" prop="status" width="90px">
        <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="createdAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="过期时间" align="center" prop="expiresAt" :formatter="expiresAtFormatter" width="180px" />
      <el-table-column label="最大次数" align="center" prop="maxUses" :formatter="maxUsesFormatter" width="110px" />
      <el-table-column label="已使用" align="center" prop="usedCount" width="90px" />
      <el-table-column label="所属租户" align="center" prop="ownerTenantId" width="120px" />
      <el-table-column label="所属系统用户" align="center" prop="ownerSystemUserId" width="130px" />
      <el-table-column label="邀请码类型" align="center" prop="inviteType" width="120px">
        <template #default="{ row }">
          <el-tag :type="getInviteTypeTagType(row.inviteType)">
            {{ getInviteTypeLabel(row.inviteType) }}
          </el-tag>
        </template>
      </el-table-column>
      <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-invite-codes:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:user-invite-codes: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>

  <!-- 表单弹窗：添加/修改 -->
  <UserInviteCodesForm 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 { UserInviteCodesApi, UserInviteCodes } from '@/api/keyboard/userinvitecodes'
import UserInviteCodesForm from './UserInviteCodesForm.vue'

/** 用户生成的邀请码表，用于邀请新用户注册/安装并建立邀请关系 列表 */
defineOptions({ name: 'KeyboardUserInviteCodes' })

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

const loading = ref(true) // 列表的加载中
const list = ref<UserInviteCodes[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const showMore = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  ownerUserId: undefined,
  status: undefined,
  createdAt: undefined,
  expiresAt: undefined,
  maxUses: undefined,
  usedCount: undefined,
  systemUserId: undefined,
  ownerTenantId: undefined,
  owenrSystemUserId: undefined,
  inviteType: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const statusOptions = [
  { label: '启用', value: 1, tagType: 'success' },
  { label: '停用', value: 0, tagType: 'danger' }
]
const inviteTypeOptions = [
  { label: '用户', value: 'USER', tagType: 'info' },
  { label: '代理', value: 'AGENT', tagType: 'warning' }
]

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

/** 批量删除用户生成的邀请码表，用于邀请新用户注册/安装并建立邀请关系 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UserInviteCodesApi.deleteUserInviteCodesList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: UserInviteCodes[]) => {
  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 getInviteTypeOption = (inviteType: unknown) => {
  return inviteTypeOptions.find((item) => String(item.value) === String(inviteType))
}

const getInviteTypeLabel = (inviteType: unknown) => {
  return getInviteTypeOption(inviteType)?.label ?? '-'
}

const getInviteTypeTagType = (inviteType: unknown) => {
  return getInviteTypeOption(inviteType)?.tagType ?? 'info'
}

const expiresAtFormatter = (_row: UserInviteCodes, _column: any, cellValue: any) => {
  return cellValue ? dateFormatter(_row, _column, cellValue) : '永久有效'
}

const maxUsesFormatter = (_row: UserInviteCodes, _column: any, cellValue: any) => {
  if (cellValue === null || cellValue === undefined || cellValue === '') return '不限'
  return cellValue
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserInviteCodesApi.exportUserInviteCodes(queryParams)
    download.excel(data, '用户生成的邀请码表，用于邀请新用户注册/安装并建立邀请关系.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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