<template>
  <!-- 搜索 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="全部" clearable class="!w-240px">
          <el-option label="男" value="male" />
          <el-option label="女" value="female" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-240px">
          <el-option label="上线" :value="1" />
          <el-option label="下线" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="可见性" prop="visibility">
        <el-select v-model="queryParams.visibility" placeholder="全部" clearable class="!w-240px">
          <el-option label="公开" :value="1" />
          <el-option label="内测" :value="2" />
          <el-option label="隐藏" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          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-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:ai-companion:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['keyboard:ai-companion:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['keyboard:ai-companion: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" width="70" />
      <el-table-column label="头像" align="center" prop="avatarUrl" width="80">
        <template #default="scope">
          <el-image
            v-if="scope.row.avatarUrl"
            :src="scope.row.avatarUrl"
            :preview-src-list="[scope.row.avatarUrl]"
            preview-teleported
            fit="cover"
            class="w-40px h-40px rounded-full"
          />
        </template>
      </el-table-column>
      <el-table-column label="角色名称" align="center" prop="name" min-width="120" />
      <el-table-column label="性别" align="center" prop="gender" width="70">
        <template #default="scope">
          <el-tag v-if="scope.row.gender === 'male'" type="primary">男</el-tag>
          <el-tag v-else-if="scope.row.gender === 'female'" type="danger">女</el-tag>
          <el-tag v-else type="info">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄段" align="center" prop="ageRange" width="80" />
      <el-table-column label="简介" align="center" prop="shortDesc" min-width="160" />
      <el-table-column label="说话风格" align="center" prop="speakingStyle" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">上线</el-tag>
          <el-tag v-else type="info">下线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可见性" align="center" prop="visibility" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.visibility === 1">公开</el-tag>
          <el-tag v-else-if="scope.row.visibility === 2" type="warning">内测</el-tag>
          <el-tag v-else-if="scope.row.visibility === 3" type="info">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="70" />
      <el-table-column label="热度" align="center" prop="popularityScore" width="70" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" fixed="right" width="130">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['keyboard:ai-companion:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['keyboard:ai-companion: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>

  <!-- 表单弹窗：添加/修改 -->
  <AiCompanionForm 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 { AiCompanionApi, AiCompanion } from '@/api/keyboard/aicompanion'
import AiCompanionForm from './AiCompanionForm.vue'

defineOptions({ name: 'KeyboardAiCompanion' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<AiCompanion[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  gender: undefined,
  status: undefined,
  visibility: undefined,
  createTime: []
})
const queryFormRef = ref()
const exportLoading = ref(false)

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

/** 批量删除 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: AiCompanion[]) => {
  checkedIds.value = records.map((item) => item.id!)
}
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await AiCompanionApi.deleteAiCompanionList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await AiCompanionApi.exportAiCompanion(queryParams)
    download.excel(data, 'AI陪聊角色.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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