<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item label="用户 Id" prop="id">
        <el-input v-model="queryParams.uid" placeholder="请输入用户 Id" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="uid" prop="uid">
        <el-input v-model="queryParams.uid" placeholder="请输入用户 Id" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input v-model="queryParams.gender" placeholder="请输入性别" @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <!-- <el-form-item label="头像地址" prop="avatarUrl">
        <el-input
          v-model="queryParams.avatarUrl"
          placeholder="请输入头像地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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 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 label="邮箱地址" prop="email">
        <el-input v-model="queryParams.email" placeholder="请输入邮箱地址" 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 label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="密码" prop="password">
        <el-input
          v-model="queryParams.password"
          placeholder="请输入密码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="苹果登录subjectId" prop="subjectId">
        <el-input
          v-model="queryParams.subjectId"
          placeholder="请输入苹果登录subjectId"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="邮箱是否验证" prop="emailVerified">
        <el-select v-model="queryParams.emailVerified" placeholder="请选择邮箱是否验证" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否是 VIP" prop="isVip">
        <el-select v-model="queryParams.isVip" placeholder="请选择是否是 VIP" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="VIP 过期时间" prop="vipExpiry">
        <el-date-picker v-model="queryParams.vipExpiry" value-format="YYYY-MM-DD" type="date" placeholder="选择VIP 过期时间"
          clearable 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-server:keyboard-user:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['keyboard-server:keyboard-user:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['keyboard-server:keyboard-user:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </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" />
      <el-table-column label="uid" align="center" prop="uid" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="{ row }">
          <el-tag :type="genderTagType(row.gender)" size="small">
            {{ genderFormatter(row, null, row.gender) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="头像地址" align="center" prop="avatarUrl" width="90px">
        <template #default="{ row }">
          <el-image v-if="row.avatarUrl" :src="row.avatarUrl" class="h-60px " @click="imagePreview(row.avatarUrl)" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <!-- <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="email" />
      <el-table-column label="是否禁用" align="center" prop="status">
        <template #default="{ row }">
          <el-tag :type="yesNoTagType(row.status)" size="small">
            {{ yesNoFormatter(row, null, row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="邮箱是否验证" align="center" prop="emailVerified">
        <template #default="{ row }">
          <el-tag :type="yesNoTagType(row.emailVerified)" size="small">
            {{ yesNoFormatter(row, null, row.emailVerified) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否是 VIP" align="center" prop="isVip">
        <template #default="{ row }">
          <el-tag :type="yesNoTagType(row.isVip)" size="small">
            {{ yesNoFormatter(row, null, row.isVip) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="VIP 过期时间" align="center" prop="vipExpiry" :formatter="dateFormatter" width="180px" />
      <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-server:keyboard-user:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard-server:keyboard-user: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>

  <!-- 表单弹窗：添加/修改 -->
  <KeyboardUserForm 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 { KeyboardUserApi, KeyboardUser } from '@/api/keyboard-server/user'
import KeyboardUserForm from './KeyboardUserForm.vue'
import { createImageViewer } from '@/components/ImageViewer'

/** 键盘用户 列表 */
defineOptions({ name: 'KeyboardUser' })

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

const loading = ref(true) // 列表的加载中
const list = ref<KeyboardUser[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  uid: undefined,
  nickName: undefined,
  gender: undefined,
  avatarUrl: undefined,
  // createdAt: undefined,
  createdAt: [],
  // updatedAt: undefined,
  updatedAt: [],
  email: undefined,
  status: undefined,
  password: undefined,
  subjectId: undefined,
  emailVerified: undefined,
  isVip: undefined,
  // vipExpiry: undefined,
  vipExpiry: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const genderFormatter = (_row: KeyboardUser, _column: any, value: number) => {
  if (value === 0) return '男'
  if (value === 1) return '女'
  if (value === 2) return '两性'
  return ''
}

const yesNoFormatter = (_row: KeyboardUser, _column: any, value: boolean) => {
  if (value === true) return '是'
  if (value === false) return '否'
  return ''
}

const genderTagType = (value: number) => {
  if (value === 0) return 'success'
  if (value === 1) return 'warning'
  if (value === 2) return 'info'
  return 'info'
}

const yesNoTagType = (value: boolean) => {
  if (value === true) return 'success'
  if (value === false) return 'danger'
  return 'info'
}

const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await KeyboardUserApi.getKeyboardUserPage(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) => {
  formRef.value.open(type, id)
}

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

/** 批量删除键盘用户 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await KeyboardUserApi.deleteKeyboardUserList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

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

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

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