import type { AxiosResponse } from 'axios'
import type { PageInfo, Result } from '@cacp/ui'
import request from '@/utils/request'

import type {GenTable,GenTableQuery}  from '@/types/gen/GenTable'

export interface PreviewResult {
  [key: string]: string
}

const contextPath = '/gen/GenTable'

// 查询代码生成业务列表
export async function getList(query: GenTableQuery): Promise<Result<PageInfo<GenTable>>> {
  const res: AxiosResponse<Result<PageInfo<GenTable>>> = await request.post(`${contextPath}/get-list`, query)
  return res.data
}

// 获取代码生成业务详情
export async function getDetail(tableId: string): Promise<Result<GenTable>> {
  const res: AxiosResponse<Result<GenTable>> = await request.get(`${contextPath}/get-detail?tableId=${tableId}`)
  return res.data
}

// 新增代码生成业务
export async function insert(row: GenTable): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.post(`${contextPath}/insert-genTable`, row)
  return res.data
}

// 更新代码生成业务
export async function update(row: GenTable): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.post(`${contextPath}/update-genTable`, row)
  return res.data
}

// 删除代码生成业务
export async function remove(genTables: string | string[]): Promise<Result<number>> {
  // 统一转换为数组格式
  const ids = Array.isArray(genTables) ? genTables : [genTables];
  const res: AxiosResponse<Result<number>> = await request.post(
    `${contextPath}/delete-genTable?ids`,ids
  )
  return res.data
}

// 查询db数据库列表
export async function listDbTable(query: GenTableQuery): Promise<Result<PageInfo<GenTable>>> {
  const res: AxiosResponse<Result<PageInfo<GenTable>>> = await request.post(
    `${contextPath}/db-list`,
    query
  )
  return res.data
}

// 导入表
export async function importTable(data: string): Promise<Result<number>> {
  console.log(data);
  const res: AxiosResponse<Result<number>> = await request.get(
    `${contextPath}/importTable?tables=${data}`,
  )
  return res.data
}


// 预览生成代码
export async function previewTable(tableId: string): Promise<Result<PreviewResult>> {
  const res: AxiosResponse<Result<PreviewResult>> = await request.get(
    `${contextPath}/preview-code?tableId=${tableId}`
  )
  return res.data
}

// 同步数据库
export async function synchDb(tableName: string): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.get(
    `${contextPath}/synchDb-tableName?tableName=${tableName}`
  )
  return res.data
}

// api/tool/gen.ts
export const batchGenCode = (tables: string) => {
  return request({
    url: `${contextPath}/batchGenCode`,
    method: 'get',
    params: { tables },
    responseType: 'blob',
    withCredentials: false
  })
}
