<script setup lang="ts">
import { computed, ref, provide } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { message, Skeleton, Tabs, TabPane } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { apiConfigInfo, apiConfigAdd, apiConfigEdit } from '#/api/erp/api';
import type { ErpApiConfig, ErpApiParam } from '#/api/erp/api';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import {
  apiMethodOptions,
  apiVersionOptions,
  resultTypeOptions,
  dataSourceOptions,
} from './data';
import SQLTemplate from './edit-tabs/sql-template.vue';

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? '编辑API配置' : '新增API配置';
});

const currentTab = ref('basic');
const paramsData = ref<ErpApiParam[]>([]);
const apiData = ref<ErpApiConfig>({} as ErpApiConfig);

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

// 基础设置表单Schema
const basicSchema = () => [
  {
    component: 'Input',
    fieldName: 'apiId',
    label: 'API ID',
    dependencies: {
      show: () => false,
      triggerFields: ['apiId'],
    },
  },
  {
    component: 'Input',
    fieldName: 'apiName',
    label: 'API名称',
    rules: 'required',
    componentProps: {
      placeholder: '请输入API名称',
    },
  },
  {
    component: 'Input',
    fieldName: 'apiPath',
    label: 'API路径',
    rules: 'required',
    componentProps: {
      placeholder: '例如：/erp/dynamic/v1/customer_list',
    },
  },
  {
    component: 'Select',
    fieldName: 'apiMethod',
    label: 'HTTP方法',
    rules: 'required',
    componentProps: {
      options: apiMethodOptions,
    },
  },
  {
    component: 'InputTextArea',
    fieldName: 'apiDesc',
    label: 'API描述',
    componentProps: {
      placeholder: '请输入API描述',
      rows: 2,
    },
  },
  {
    component: 'Select',
    fieldName: 'apiVersion',
    label: 'API版本',
    componentProps: {
      options: apiVersionOptions,
    },
  },
  {
    component: 'Select',
    fieldName: 'dataSource',
    label: '数据源',
    componentProps: {
      options: dataSourceOptions,
    },
  },
  {
    component: 'Select',
    fieldName: 'resultType',
    label: '结果类型',
    rules: 'required',
    componentProps: {
      options: resultTypeOptions,
    },
  },
  {
    component: 'Switch',
    fieldName: 'supportPagination',
    label: '支持分页',
    componentProps: {
      checkedChildren: '是',
      unCheckedChildren: '否',
      checkedValue: 1,
      unCheckedValue: 0,
    },
  },
  {
    component: 'Input',
    fieldName: 'pageParamName',
    label: '页码参数名',
    dependencies: {
      show: (values) => values.supportPagination === 1,
      triggerFields: ['supportPagination'],
    },
    componentProps: {
      placeholder: '默认：pageNum',
    },
  },
  {
    component: 'Input',
    fieldName: 'sizeParamName',
    label: '页大小参数名',
    dependencies: {
      show: (values) => values.supportPagination === 1,
      triggerFields: ['supportPagination'],
    },
    componentProps: {
      placeholder: '默认：pageSize',
    },
  },
  {
    component: 'Switch',
    fieldName: 'requireAuth',
    label: '需要认证',
    componentProps: {
      checkedChildren: '是',
      unCheckedChildren: '否',
      checkedValue: 1,
      unCheckedValue: 0,
    },
  },
  {
    component: 'Input',
    fieldName: 'permissionCode',
    label: '权限标识',
    dependencies: {
      show: (values) => values.requireAuth === 1,
      triggerFields: ['requireAuth'],
    },
    componentProps: {
      placeholder: '例如：erp:customer:list',
    },
  },
  {
    component: 'Switch',
    fieldName: 'enableCache',
    label: '启用缓存',
    componentProps: {
      checkedChildren: '是',
      unCheckedChildren: '否',
      checkedValue: 1,
      unCheckedValue: 0,
    },
  },
  {
    component: 'Input',
    fieldName: 'cacheKeyTemplate',
    label: '缓存键模板',
    dependencies: {
      show: (values) => values.enableCache === 1,
      triggerFields: ['enableCache'],
    },
    componentProps: {
      placeholder: '支持参数占位符',
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'cacheTtl',
    label: '缓存过期时间',
    dependencies: {
      show: (values) => values.enableCache === 1,
      triggerFields: ['enableCache'],
    },
    componentProps: {
      placeholder: '秒',
      min: 1,
    },
  },
  {
    component: 'Input',
    fieldName: 'sourceTable',
    label: '来源表名',
    componentProps: {
      disabled: true,
      placeholder: '如果是从表导入生成的，会显示来源表名',
    },
  },
  {
    component: 'InputTextArea',
    fieldName: 'remark',
    label: '备注',
    componentProps: {
      placeholder: '请输入备注',
      rows: 2,
    },
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 120,
  },
  schema: basicSchema(),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const loading = ref(false);
const [BasicDrawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);
    loading.value = true;

    const { apiId } = drawerApi.getData() as { apiId?: number | string };
    isUpdate.value = !!apiId;

    if (isUpdate.value && apiId) {
      const response = await apiConfigInfo(Number(apiId));
      await formApi.setValues(response.info);
      apiData.value = response.info;
      paramsData.value = response.params || [];
    } else {
      // 设置默认值
      const defaultData = {
        apiMethod: 'GET',
        apiVersion: 'v1',
        dataSource: 'erp',
        resultType: 'LIST',
        supportPagination: 0,
        pageParamName: 'pageNum',
        sizeParamName: 'pageSize',
        requireAuth: 0,
        enableCache: 0,
        cacheTtl: 300,
        status: 1,
        sqlTemplate: '',
      };
      await formApi.setValues(defaultData);
      apiData.value = defaultData as ErpApiConfig;
      paramsData.value = [];
    }

    await markInitialized();

    drawerApi.drawerLoading(false);
    loading.value = false;
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      currentTab.value = 'basic';
      return;
    }

    const formValues = cloneDeep(await formApi.getValues());

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

    // 验证SQL模板
    if (!apiData.value.sqlTemplate) {
      message.error('请填写SQL模板');
      currentTab.value = 'sql';
      return;
    }

    // 合并数据（formApi数据 + apiData中的sqlTemplate）
    const submitData = {
      ...formValues,
      sqlTemplate: apiData.value.sqlTemplate,
      params: paramsData.value,
    };

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

    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error: any) {
    message.error('保存失败: ' + (error.message || '未知错误'));
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  paramsData.value = [];
  resetInitialized();
}
</script>

<template>
  <BasicDrawer :title="title" class="w-[800px]">
    <Skeleton v-if="loading" active />
    <Tabs v-show="!loading" v-model:activeKey="currentTab">
      <TabPane key="basic" tab="基础设置">
        <BasicForm />
      </TabPane>

      <TabPane key="params" tab="参数配置">
        <div class="p-4">
          <div class="mb-2">
            <a-button type="primary" @click="paramsData.push({
              paramId: Date.now(),
              apiId: 0,
              paramName: '',
              paramType: 'String',
              paramPosition: 'QUERY',
              isRequired: 0,
              defaultValue: '',
              paramDesc: '',
              sort: paramsData.length,
            })">
              新增参数
            </a-button>
          </div>

          <a-table :data-source="paramsData" :columns="[
            { title: '参数名称', dataIndex: 'paramName', width: 150 },
            { title: '参数类型', dataIndex: 'paramType', width: 120 },
            { title: '参数位置', dataIndex: 'paramPosition', width: 100 },
            { title: '必填', dataIndex: 'isRequired', width: 80 },
            { title: '默认值', dataIndex: 'defaultValue', width: 120 },
            { title: '参数描述', dataIndex: 'paramDesc', width: 200 },
            { title: '操作', dataIndex: 'action', width: 100, fixed: 'right' },
          ]" :pagination="false" size="small">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'paramName'">
                <a-input v-model:value="record.paramName" size="small" />
              </template>
              <template v-if="column.dataIndex === 'paramType'">
                <a-select v-model:value="record.paramType" size="small" :options="[
                  { label: 'String', value: 'String' },
                  { label: 'Integer', value: 'Integer' },
                  { label: 'Long', value: 'Long' },
                  { label: 'Date', value: 'Date' },
                ]" />
              </template>
              <template v-if="column.dataIndex === 'paramPosition'">
                <a-select v-model:value="record.paramPosition" size="small" :options="[
                  { label: 'QUERY', value: 'QUERY' },
                  { label: 'BODY', value: 'BODY' },
                ]" />
              </template>
              <template v-if="column.dataIndex === 'isRequired'">
                <a-switch v-model:checked="record.isRequired" :checked-value="1" :un-checked-value="0" size="small" />
              </template>
              <template v-if="column.dataIndex === 'defaultValue'">
                <a-input v-model:value="record.defaultValue" size="small" />
              </template>
              <template v-if="column.dataIndex === 'paramDesc'">
                <a-input v-model:value="record.paramDesc" size="small" />
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" danger size="small" @click="paramsData.splice(index, 1)">
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </TabPane>

      <TabPane key="sql" tab="SQL模板">
        <SQLTemplate />
      </TabPane>
    </Tabs>
  </BasicDrawer>
</template>