<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Button, Space, message } from 'ant-design-vue';
import { inject, ref } from 'vue';

import { paramColumns } from '../data';
import type { ErpApiParam } from '#/api/erp/api';

const paramsData = inject<ref<ErpApiParam[]>>('paramsData')!;

const gridOptions: VxeGridProps<ErpApiParam> = {
  columns: paramColumns,
  data: paramsData.value,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
  },
  rowConfig: {
    keyField: 'paramId',
  },
  id: 'erp-api-params-config',
};

const [ParamsTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});

// 新增参数
function handleAddParam() {
  const newParam: ErpApiParam = {
    paramId: Date.now(), // 临时ID
    apiId: 0,
    paramName: '',
    paramType: 'String',
    paramPosition: 'QUERY',
    isRequired: 0,
    defaultValue: '',
    paramDesc: '',
    sort: paramsData.value.length,
  };

  tableApi.insert(newParam);
}

// 删除选中参数
async function handleDeleteParam() {
  const selectRows = tableApi.getSelectRows();
  if (selectRows.length === 0) {
    message.warning('请选择要删除的参数');
    return;
  }

  await tableApi.remove(selectRows);
  message.success('删除成功');
}

// 获取表格数据（供父组件调用）
function getTableData(): ErpApiParam[] {
  return tableApi.getTableData().fullData;
}

// 暴露方法给父组件
defineExpose({
  getTableData,
});
</script>

<template>
  <div class="params-config-container">
    <div class="toolbar mb-2">
      <Space>
        <Button type="primary" @click="handleAddParam">新增参数</Button>
        <Button danger @click="handleDeleteParam">删除选中</Button>
      </Space>
    </div>

    <ParamsTable>
      <template #paramAction="{ row }">
        <Button size="small" type="link" danger @click="tableApi.remove(row)">
          删除
        </Button>
      </template>
    </ParamsTable>
  </div>
</template>

<style scoped>
.params-config-container {
  padding: 16px 0;
}
</style>