import request from "@/utils/request";
import type { PaginationParams, PaginationResponse } from "@/types/api";

export interface Dict {
  id: number;
  name: string;
  code: string;
  description?: string;
  validState?: number;
  createBy?: number;
  updateBy?: number;
  createTime?: string;
  updateTime?: string;
  items?: DictItem[];
}

export interface DictItem {
  id: number;
  dictId: number;
  label: string;
  value: string;
  sort: number;
  validState: number;
}

export interface CreateDictForm {
  name: string;
  code: string;
  description?: string;
}

export interface UpdateDictForm {
  name?: string;
  code?: string;
  description?: string;
}

// 获取字典列表
export async function getDictsList(
  params: PaginationParams
): Promise<PaginationResponse<Dict>> {
  const response = await request.get<any, PaginationResponse<Dict>>("/api/dict/page", {
    params,
  });
  return response;
}

// 获取单个字典详情
export async function getDictDetail(id: number): Promise<Dict> {
  const response = await request.get<any, Dict>(`/api/dict/${id}`);
  return response;
}

// 根据编码获取字典
export async function getDictByCode(code: string): Promise<Dict> {
  const response = await request.get<any, Dict>(`/api/dict/code/${code}`);
  return response;
}

// 创建字典
export async function createDict(data: CreateDictForm): Promise<Dict> {
  const response = await request.post<any, Dict>("/api/dict", data);
  return response;
}

// 更新字典
export async function updateDict(
  id: number,
  data: UpdateDictForm
): Promise<Dict> {
  const response = await request.put<any, Dict>(`/api/dict/${id}`, data);
  return response;
}

// 删除字典
export async function deleteDict(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/dict/${id}`);
}

// 兼容性导出：保留 dictApi 对象
export const dictApi = {
  getList: getDictsList,
  getDetail: getDictDetail,
  getByCode: getDictByCode,
  create: createDict,
  update: updateDict,
  delete: deleteDict,
};

// ==================== 字典项管理 ====================

export interface CreateDictItemForm {
  dictId: number;
  label: string;
  value: string;
  sort?: number;
}

export interface UpdateDictItemForm {
  label?: string;
  value?: string;
  sort?: number;
}

// 创建字典项
export async function createDictItem(data: CreateDictItemForm): Promise<DictItem> {
  const response = await request.post<any, DictItem>("/api/dict/item", data);
  return response;
}

// 获取字典项列表
export async function getDictItems(dictId: number): Promise<DictItem[]> {
  const response = await request.get<any, DictItem[]>(`/api/dict/item/${dictId}`);
  return response;
}

// 更新字典项
export async function updateDictItem(
  id: number,
  data: UpdateDictItemForm
): Promise<DictItem> {
  const response = await request.put<any, DictItem>(`/api/dict/item/${id}`, data);
  return response;
}

// 删除字典项
export async function deleteDictItem(id: number): Promise<void> {
  return await request.delete<any, void>(`/api/dict/item/${id}`);
}

