
<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, DocumentCopy } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { copyToClip } from '@/utils/copy'
import { AppApiManagement } from '@/api/new-ai/appApi'
import { hideKey } from '@/api/models/index'
import { TableColumn } from '@/types/table'

const props = defineProps({
  channel: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['reload'])
const router = useRouter()

// 表格配置
const columns = ref<TableColumn[]>([
  {
    label: '密钥',
    field: 'apiKey',
    formatter: (row: any) => hideKey(row.apiKey)
  },
  {
    label: '创建时间',
    field: 'createTime',
    width: 180
  },
  {
    label: '操作',
    field: 'action',
    width: 150
  }
])

// 使用表格Hook
const { register, methods, tableObject } = useTable({
  getListApi: async (params) => {
    const res = await AppApiManagement.getApiList({
      ...params,
      appId: router.currentRoute.value.params.id,
      channel: props.channel
    })
    return {
      list: res.data,
      total: res.total
    }
  }
})

// 复制API密钥
const handleCopy = async (record: any) => {
  await copyToClip(record.apiKey)
  ElMessage.success('密钥复制成功')
}

// 删除API
const handleDelete = (record: any) => {
  ElMessageBox.confirm('确定要删除该API吗？删除后原Key将立即失效，请谨慎操作', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        await AppApiManagement.deleteApi(record.id)
        ElMessage.success('删除成功')
        methods.getList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 新增API
const handleAdd = async () => {
  try {
    await AppApiManagement.createApi({
      appId: router.currentRoute.value.params.id,
      channel: props.channel
    })
    ElMessage.success('新增成功')
    methods.getList()
  } catch (error) {
    ElMessage.error('新增失败')
  }
}
const pagination = computed(() => {
  return {
    total: tableObject.total,
    currentPage: tableObject.currentPage,
    pageSize: tableObject.pageSize
  }
})
// 初始加载
onMounted(() => {
  methods.getList()
})
</script>

<template>
  <div class="app-container">
    <el-button type="primary" class="mb-10px" @click="handleAdd">新增密钥</el-button>
    <Table
      border
      :columns="columns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="pagination"
      @register="register"
    >
      <template #action="{ row }">
        <el-button :icon="DocumentCopy" text type="primary" @click="handleCopy(row)" />
        <el-button :icon="Delete" text type="danger" @click="handleDelete(row)" />
      </template>
    </Table>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
</style>
