<script setup lang="ts">
import { Page, useVbenDrawer } from '@vben/common-ui';
import { Card, Tabs, TabPane, Button, Space, Spin, message } from 'ant-design-vue';
import { ref, onMounted, provide, useTemplateRef } from 'vue';
import { useRouter, useRoute } from 'vue-router';

import { apiConfigInfo, apiConfigAdd, apiConfigEdit } from '#/api/erp/api';
import type { ErpApiConfig, ErpApiParam } from '#/api/erp/api';

import BasicSetting from './edit-tabs/basic-setting.vue';
import ParamsConfig from './edit-tabs/params-config.vue';

const router = useRouter();
const route = useRoute();

const apiId = route.query.apiId as string;
const isUpdate = ref<boolean>(!!apiId);

const apiData = ref<ErpApiConfig>({
  apiId: undefined,
  apiName: '',
  apiPath: '',
  apiMethod: 'GET',
  apiDesc: '',
  apiVersion: 'v1',
  dataSource: 'erp',
  sqlTemplate: '',
  resultType: 'LIST',
  supportPagination: 0,
  pageParamName: 'pageNum',
  sizeParamName: 'pageSize',
  requireAuth: 0,
  permissionCode: '',
  enableCache: 0,
  cacheKeyTemplate: '',
  cacheTtl: 300,
  status: 1,
});

const paramsData = ref<ErpApiParam[]>([]);
const loading = ref(false);
const currentTab = ref('basic');

// 子组件引用
const basicSettingRef = useTemplateRef('basicSettingRef');
const paramsConfigRef = useTemplateRef('paramsConfigRef');

// 提供数据给子组件
provide('apiData', apiData);
provide('paramsData', paramsData);

// 加载API配置详情
async function loadApiInfo() {
  if (!apiId) return;

  loading.value = true;
  try {
    const response = await apiConfigInfo(Number(apiId));
    apiData.value = response.info;
    paramsData.value = response.params || [];
  } catch (error) {
    message.error('加载API配置失败');
    router.push({ path: '/erp/api' });
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  loadApiInfo();
});

// 保存配置
async function handleSave() {
  try {
    // 验证表单
    const valid = await basicSettingRef.value?.validateForm();
    if (!valid) {
      message.error('请填写必填字段');
      currentTab.value = 'basic';
      return;
    }

    // 获取表单数据
    const formValues = await basicSettingRef.value?.getFormValues();
    if (!formValues) {
      message.error('获取表单数据失败');
      return;
    }

    // 验证必填字段
    if (!formValues.apiName || !formValues.apiPath || !formValues.sqlTemplate) {
      message.error('请填写必填字段：API名称、API路径、SQL模板');
      currentTab.value = 'basic';
      return;
    }

    // 获取参数配置数据
    const params = paramsConfigRef.value?.getTableData() || [];

    // 合并数据
    const submitData = {
      ...formValues,
      params,
    };

    if (isUpdate.value) {
      await apiConfigEdit(submitData);
      message.success('修改成功');
    } else {
      await apiConfigAdd(submitData);
      message.success('新增成功');
    }

    router.push({ path: '/erp/api' });
  } catch (error: any) {
    message.error('保存失败: ' + (error.message || '未知错误'));
  }
}

// 返回列表
function handleBack() {
  router.push({ path: '/erp/api' });
}
</script>

<template>
  <Page :auto-content-height="true">
    <Card>
      <Spin v-if="loading" />
      <Tabs v-else v-model:activeKey="currentTab">
        <template #rightExtra>
          <Space>
            <Button @click="handleBack">返回</Button>
            <Button type="primary" @click="handleSave">保存配置</Button>
          </Space>
        </template>

        <TabPane key="basic" tab="基础设置">
          <BasicSetting ref="basicSettingRef" />
        </TabPane>

        <TabPane key="params" tab="参数配置">
          <ParamsConfig ref="paramsConfigRef" />
        </TabPane>
      </Tabs>
    </Card>
  </Page>
</template>