<script lang="ts" setup>
/**
 * AI API Key 管理：列表脱敏，详情/编辑走传输加密
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Tag, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { getAiPlatformOption } from '../platform/api';
import { deleteAiApiKey, getAiApiKeyList } from './api';
import FormModal from './components/modal.vue';
import { STATUS_OPTIONS } from './config/constants';

defineOptions({ name: 'AiApiKey' });

const hasTopTableDropDownActions = ref(false);
const platformOptions = ref<{ label: string; value: number }[]>([]);

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: [
      {
        component: 'VbenSelect',
        fieldName: 'platform_id',
        label: '平台',
        componentProps: {
          allowClear: true,
          options: platformOptions,
          placeholder: '全部平台',
        },
      },
      {
        component: 'VbenInput',
        fieldName: 'name',
        label: '别名',
        componentProps: { placeholder: '密钥别名' },
      },
      {
        component: 'VbenSelect',
        fieldName: 'status',
        label: '状态',
        componentProps: { allowClear: true, options: STATUS_OPTIONS },
      },
    ],
  },
  gridOptions: {
    checkboxConfig: { highlight: true, labelField: '' },
    columns: [
      { type: 'checkbox', width: 60 },
      { field: 'id', title: 'ID', width: 80 },
      { field: 'platform_name', title: '平台', minWidth: 120 },
      { field: 'platform_code', title: '编码', width: 100 },
      { field: 'name', title: '别名', minWidth: 140 },
      { field: 'api_key_mask', title: '密钥', minWidth: 160 },
      { field: 'status', title: '状态', width: 90, slots: { default: 'status' } },
      { field: 'sort', title: '排序', width: 80 },
      { field: 'created_at', title: '创建时间', width: 170 },
      { title: '操作', slots: { default: 'action' }, width: 160, fixed: 'right' },
    ],
    keepSource: true,
    pagerConfig: {},
    proxyConfig: {
      ajax: {
        query: async ({ page }: any, formValues: any) => {
          return await getAiApiKeyList({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    height: 'auto',
    toolbarConfig: {
      search: true,
      refresh: true,
      slots: { buttons: 'toolbar-actions' },
    },
  },
  gridEvents: {
    checkboxChange() {
      hasTopTableDropDownActions.value =
        gridApi.grid.getCheckboxRecords().length > 0;
    },
    checkboxAll() {
      hasTopTableDropDownActions.value =
        gridApi.grid.getCheckboxRecords().length > 0;
    },
  } as VxeGridListeners<any>,
});

const [FormModalComp, formModalApi] = useVbenModal({
  connectedComponent: FormModal,
});

const showModal = (data: any = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

const handleDelete = async (ids: number[]) => {
  await deleteAiApiKey({ ids });
  message.success('删除成功');
  gridApi.query();
};

onMounted(async () => {
  try {
    const opts = await getAiPlatformOption();
    platformOptions.value = Array.isArray(opts) ? opts : opts?.data || [];
    gridApi.formApi?.updateSchema?.([
      {
        fieldName: 'platform_id',
        componentProps: {
          allowClear: true,
          options: platformOptions.value,
          placeholder: '全部平台',
        },
      },
    ]);
  } catch {
    /* ignore */
  }
});
</script>

<template>
  <Page auto-content-height>
    <FormModalComp />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              onClick: () => showModal({}, false),
            },
          ]"
          :drop-down-actions="
            hasTopTableDropDownActions
              ? [
                  {
                    label: '批量删除',
                    popConfirm: {
                      title: '确认删除选中项？',
                      confirm: () => {
                        const rows = gridApi.grid.getCheckboxRecords();
                        handleDelete(rows.map((r: any) => r.id));
                      },
                    },
                  },
                ]
              : []
          "
        />
      </template>
      <template #status="{ row }">
        <Tag :color="row.status === 1 ? 'success' : 'default'">
          {{ row.status_txt || (row.status === 1 ? '启用' : '禁用') }}
        </Tag>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              onClick: () => showModal(row, true),
            },
            {
              label: '删除',
              popConfirm: {
                title: '确认删除？',
                confirm: () => handleDelete([row.id]),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
