<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { Button, Popconfirm, Space, Switch, Tag, message } from 'ant-design-vue';
import { ref } from 'vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  apiConfigList,
  apiConfigRemove,
  apiConfigChangeStatus,
  apiConfigTest,
  apiConfigClearCache,
} from '#/api/erp/api';
import type { ErpApiConfigVO } from '#/api/erp/api';

import { columns, querySchema } from './data';
import TestModal from './test-modal.vue';
import DocPreviewModal from './doc-preview-modal.vue';
import ApiDrawer from './api-drawer.vue';

// 搜索表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 表格配置
const gridOptions: VxeGridProps<ErpApiConfigVO> = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const response = await apiConfigList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return response;
      },
    },
  },
  rowConfig: {
    keyField: 'apiId',
  },
  id: 'erp-api-config-list',
};

// 初始化表格
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 测试弹窗
const [TestModalComp, testModalApi] = useVbenModal({
  connectedComponent: TestModal,
});

// 文档预览弹窗
const [DocModalComp, docModalApi] = useVbenModal({
  connectedComponent: DocPreviewModal,
});

// 新增/编辑Drawer
const [ApiDrawerComp, apiDrawerApi] = useVbenDrawer({
  connectedComponent: ApiDrawer,
});

// 新增API配置
function handleAdd() {
  apiDrawerApi.setData({});
  apiDrawerApi.open();
}

// 编辑API配置
function handleEdit(record: ErpApiConfigVO) {
  apiDrawerApi.setData({ apiId: record.apiId });
  apiDrawerApi.open();
}

// 测试API
async function handleTest(record: ErpApiConfigVO) {
  testModalApi.setData({ apiId: record.apiId, apiName: record.apiName });
  testModalApi.open();
}

// 文档预览
async function handlePreview(record: ErpApiConfigVO) {
  docModalApi.setData({ apiId: record.apiId, apiName: record.apiName });
  docModalApi.open();
}

// 删除API配置
async function handleDelete(record: ErpApiConfigVO) {
  await apiConfigRemove([record.apiId]);
  message.success('删除成功');
  await tableApi.query();
}

// 批量删除
async function handleMultiDelete() {
  const rows = tableApi.getSelectRows();
  if (!rows.length) {
    message.warning('请选择要删除的数据');
    return;
  }
  const apiIds = rows.map((row) => row.apiId);
  await apiConfigRemove(apiIds);
  message.success('删除成功');
  await tableApi.query();
}

// 更新状态
async function handleStatusChange(record: ErpApiConfigVO, status: boolean) {
  await apiConfigChangeStatus({
    apiId: record.apiId,
    status: status ? 1 : 0,
  });
  message.success('状态更新成功');
  await tableApi.query();
}

// 清除缓存
async function handleClearCache(record: ErpApiConfigVO) {
  await apiConfigClearCache(record.apiId);
  message.success('缓存清除成功');
}

// 从表导入（待实现）
function handleImportFromTable() {
  message.info('从表导入功能正在开发中');
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="API配置列表">
      <template #toolbar-tools>
        <Space>
          <Button v-access:code="['erp:api:add']" type="primary" @click="handleAdd">
            新增
          </Button>
          <Button v-access:code="['erp:api:add']" @click="handleImportFromTable">
            从表导入
          </Button>
          <Button
            v-access:code="['erp:api:remove']"
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            @click="handleMultiDelete"
          >
            批量删除
          </Button>
        </Space>
      </template>

      <template #pagination="{ row }">
        <Tag v-if="row.supportPagination === 1" color="success">是</Tag>
        <Tag v-else color="default">否</Tag>
      </template>

      <template #auth="{ row }">
        <Tag v-if="row.requireAuth === 1" color="warning">需要</Tag>
        <Tag v-else color="default">无需</Tag>
      </template>

      <template #cache="{ row }">
        <Tag v-if="row.enableCache === 1" color="processing">启用</Tag>
        <Tag v-else color="default">未启用</Tag>
      </template>

      <template #status="{ row }">
        <Switch
          :checked="row.status === 1"
          checked-children="启用"
          un-checked-children="禁用"
          @change="(checked: boolean) => handleStatusChange(row, checked)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button
            v-access:code="['erp:api:test']"
            size="small"
            type="link"
            @click="handleTest(row)"
          >
            测试
          </Button>
          <Button size="small" type="link" @click="handlePreview(row)">
            文档
          </Button>
          <Button
            v-access:code="['erp:api:edit']"
            size="small"
            type="link"
            @click="handleEdit(row)"
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除此API配置？"
            @confirm="handleDelete(row)"
          >
            <Button
              v-access:code="['erp:api:remove']"
              size="small"
              type="link"
              danger
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            v-if="row.enableCache === 1"
            v-access:code="['erp:api:cache']"
            size="small"
            type="link"
            @click="handleClearCache(row)"
          >
            清缓存
          </Button>
        </Space>
      </template>
    </BasicTable>

    <TestModalComp @success="tableApi.query()" />
    <DocModalComp />
    <ApiDrawerComp @reload="tableApi.query()" />
  </Page>
</template>