<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <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="被邀请人用户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="inviteCodeId">
        <el-input v-model="queryParams.inviteCodeId" placeholder="请输入使用的邀请码ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="绑定方式" prop="bindType">
        <el-select v-model="queryParams.bindType" placeholder="请选择绑定方式" clearable class="!w-240px">
          <el-option v-for="item in bindTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定时间" prop="boundAt">
        <el-date-picker v-model="queryParams.boundAt" value-format="YYYY-MM-DD" type="date" placeholder="选择绑定时间"
          clearable class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="点击Token" prop="clickToken">
        <el-input v-model="queryParams.clickToken" placeholder="请输入点击Token" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="绑定IP" prop="bindIp">
        <el-input v-model="queryParams.bindIp" placeholder="请输入绑定IP" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="UserAgent" prop="bindUserAgent">
        <el-input v-model="queryParams.bindUserAgent" placeholder="请输入UserAgent" 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 v-show="showMore" label="收益租户ID" prop="profitTenantId">
        <el-input v-model="queryParams.profitTenantId" placeholder="请输入收益租户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="收益员工ID" prop="profitEmployeeId">
        <el-input v-model="queryParams.profitEmployeeId" placeholder="请输入收益员工ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="邀请人租户ID" prop="inviterTenantId">
        <el-input v-model="queryParams.inviterTenantId" placeholder="请输入邀请人租户ID" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item v-show="showMore" label="邀请码快照" prop="inviteCode">
        <el-input v-model="queryParams.inviteCode" 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-invites:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard:user-invites:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard:user-invites: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="inviterUserId" width="130px" />
      <el-table-column label="被邀请人用户ID" align="center" prop="inviteeUserId" width="140px" />
      <el-table-column label="邀请码ID" align="center" prop="inviteCodeId" width="110px" />
      <el-table-column label="点击Token" align="center" prop="clickToken" min-width="180px" />
      <el-table-column label="绑定方式" align="center" prop="bindType" width="120px">
        <template #default="{ row }">
          <el-tag :type="getBindTypeTagType(row.bindType)">
            {{ getBindTypeLabel(row.bindType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="绑定时间" align="center" prop="boundAt" :formatter="dateFormatter" width="180px" />
      <el-table-column label="绑定IP" align="center" prop="bindIp" width="120px" />
      <el-table-column label="UserAgent" align="center" prop="bindUserAgent" min-width="160px" />
      <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="收益租户ID" align="center" prop="profitTenantId" width="120px" />
      <el-table-column label="收益员工ID" align="center" prop="profitEmployeeId" width="120px" />
      <el-table-column label="邀请人租户ID" align="center" prop="inviterTenantId" width="120px" />
      <el-table-column label="邀请码快照" align="center" prop="inviteCode" 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:user-invites:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:user-invites: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>

  <!-- 表单弹窗：添加/修改 -->
  <UserInvitesForm 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 { UserInvitesApi, UserInvites } from '@/api/keyboard/userinvites'
import UserInvitesForm from './UserInvitesForm.vue'

/** 用户邀请关系绑定台账表，记录新用户最终归属的邀请人 列表 */
defineOptions({ name: 'KeyboardUserInvites' })

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

const loading = ref(true) // 列表的加载中
const list = ref<UserInvites[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const showMore = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  inviterUserId: undefined,
  inviteeUserId: undefined,
  inviteCodeId: undefined,
  clickToken: undefined,
  bindType: undefined,
  boundAt: undefined,
  bindIp: undefined,
  bindUserAgent: undefined,
  inviteType: undefined,
  profitTenantId: undefined,
  profitEmployeeId: undefined,
  inviterTenantId: undefined,
  inviteCode: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const bindTypeOptions = [
  { label: '手动填写邀请码', value: 1, tagType: 'warning' },
  { label: '邀请链接自动绑定', value: 2, tagType: 'success' },
  { label: '其他方式', value: 3, tagType: 'info' }
]
const inviteTypeOptions = [
  { label: '普通用户邀请', value: 'USER', tagType: 'info' },
  { label: '代理邀请', value: 'AGENT', tagType: 'warning' }
]

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

/** 批量删除用户邀请关系绑定台账表，记录新用户最终归属的邀请人 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await UserInvitesApi.deleteUserInvitesList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

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

const getBindTypeOption = (bindType: unknown) => {
  return bindTypeOptions.find((item) => String(item.value) === String(bindType))
}

const getBindTypeLabel = (bindType: unknown) => {
  return getBindTypeOption(bindType)?.label ?? '-'
}

const getBindTypeTagType = (bindType: unknown) => {
  return getBindTypeOption(bindType)?.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 handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserInvitesApi.exportUserInvites(queryParams)
    download.excel(data, '用户邀请关系绑定台账表，记录新用户最终归属的邀请人.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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