import type {
  BasicFetchResult,
  BasicOptionResult,
  BasicPageParams,
  BasicTreeOptionResult,
  QueryParams,
} from '#/api/model';

import { requestClient } from '#/api/request';

export namespace QueryApi {
  export interface PageParams extends BasicPageParams {
    name?: string;
    code?: string;
  }

  export interface BasicRecordItem {
    name: string;
    code: string;
    sort: number;
    remark: string;
  }

  export interface RecordItem extends BasicRecordItem {
    id: number;
  }

  export type PageResult = BasicFetchResult<RecordItem>;

  export interface Column {
    tableAlias: string;
    alias: string;
    name: string;
    remark: string;
  }

  export interface Tables {
    remark: string;
    name: string;
    alias: string;
    isMain: boolean;
    columns: Column[];
    columnKeys: string[];
  }

  export const getPage = (params: PageParams) =>
    requestClient.get<PageResult>('/query/page', { params });

  export const getDetail = (id: number) =>
    requestClient.get<RecordItem>('/query/entity', {
      params: { id },
    });

  export const addDetail = (data: BasicRecordItem) =>
    requestClient.post('/query', data);

  export const editDetail = (data: RecordItem) =>
    requestClient.put('/query', data);

  export const deleteDetail = (id: number) =>
    requestClient.delete('/query', { data: { id } });

  export const getColumns = (code: string) =>
    requestClient.get<Column[]>('/query/column-list', { params: { code } });

  export const postExecute = (data: QueryParams) =>
    requestClient.post('/query/execute', data);

  export const postExecuteReal = (data: QueryParams) =>
    requestClient.post('/query/execute-real', data);
  /**
   * @param data
   * { id: number, conditions:{ field: string,op:EnumApi.EnumType.QueryType,value:any } }
   * @returns
   */
  export const postOptions = (data: QueryParams) =>
    requestClient.post<BasicOptionResult[]>('/query/execute-options', data);
  /**
   *
   * @param data
   * @returns
   */
  export const getExecuteTree = (data: QueryParams) =>
    requestClient.post<BasicTreeOptionResult[]>('/query/execute-tree', data);
}
