import type { ApiResponse } from "@/types/api";
import type {
  DictType,
  DictData,
  DictQueryParams,
  DictTypeQueryParams,
} from "@/types/dict";

import { request } from "@/utils/request";

const isMock = import.meta.env.VITE_USE_MOCK === "true";

// backend status mapping: '0' = enabled, '1' = disabled
const mapTypeFromBackend = (t: any): DictType => ({
  ...t,
  status: t.status === "1" ? "disabled" : "enabled",
});
const mapDataFromBackend = (d: any): DictData => ({
  ...d,
  status: d.status === "1" ? "disabled" : "enabled",
});
const mapStatusToBackend = (status?: string) =>
  status === "disabled" ? "1" : status === "enabled" ? "0" : status;

// ---------------- Mock helpers ----------------

const ok = <T>(data: T, message = "success"): ApiResponse<T> => ({
  code: 200,
  message,
  data,
  success: true,
});

const error = <T = null>(code: number, message: string): ApiResponse<T> => ({
  code,
  message,
  data: null as T,
  success: false,
});

// ---------------- Dict Type APIs ----------------

/**
 * 获取所有字典类型
 */
export async function getDictTypes(): Promise<ApiResponse<DictType[]>> {
  if (isMock) {
    const { dictTypes } = await import("../../mock/data/dict.data");
    return ok(dictTypes.filter((t) => t.status === "enabled"));
  }

  const res: any = await request.get("/sys/dict/type/list");
  return {
    code: 200,
    message: res.message || "success",
    data: (res.data || res).map(mapTypeFromBackend),
    success: true,
  };
}

/**
 * 获取字典类型列表（分页）
 */
export async function getDictTypeList(
  params: DictTypeQueryParams,
): Promise<
  ApiResponse<{
    list: DictType[];
    total: number;
    page: number;
    pageSize: number;
  }>
> {
  if (isMock) {
    const { dictTypes } = await import("../../mock/data/dict.data");
    const { page = 1, pageSize = 10, code, name, status } = params;
    let filtered = [...dictTypes];
    if (code) filtered = filtered.filter((item) => item.code.includes(code));
    if (name) filtered = filtered.filter((item) => item.name.includes(name));
    if (status) filtered = filtered.filter((item) => item.status === status);
    const start = (page - 1) * pageSize;
    const list = filtered.slice(start, start + pageSize);
    return ok({ list, total: filtered.length, page, pageSize });
  }

  const res: any = await request.post("/sys/dict/type/page", {
    page: params.page || 1,
    pageSize: params.pageSize || 10,
    name: params.name,
    code: params.code,
    status: mapStatusToBackend(params.status),
  });
  return {
    code: 200,
    message: res.message || "success",
    data: {
      list: ((res.data || res).list || []).map(mapTypeFromBackend),
      total: (res.data || res).total || 0,
      page: (res.data || res).page || params.page || 1,
      pageSize: (res.data || res).pageSize || params.pageSize || 10,
    },
    success: true,
  };
}

/**
 * 创建字典类型
 */
export async function createDictType(
  data: Partial<DictType>,
): Promise<ApiResponse<DictType>> {
  if (isMock) {
    const { dictTypes } = await import("../../mock/data/dict.data");
    const newType: DictType = {
      id: String(Date.now()),
      name: data.name || "",
      code: data.code || "",
      description: data.description,
      status: data.status || "enabled",
      createTime: new Date().toISOString().replace("T", " ").slice(0, 19),
      updateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
    };
    dictTypes.push(newType);
    return ok(newType, "创建成功");
  }

  const res: any = await request.post("/sys/dict/type/save", {
    name: data.name,
    code: data.code,
    description: data.description,
    status: mapStatusToBackend(data.status),
  });
  return {
    code: 200,
    message: res.message || "创建成功",
    data: res.data ? mapTypeFromBackend({ ...data, id: res.data }) : null,
    success: true,
  };
}

/**
 * 更新字典类型
 */
export async function updateDictType(
  id: string,
  data: Partial<DictType>,
): Promise<ApiResponse<DictType>> {
  if (isMock) {
    const { dictTypes } = await import("../../mock/data/dict.data");
    const index = dictTypes.findIndex((item) => item.id === id);
    if (index === -1) return error(404, "字典类型不存在");
    dictTypes[index] = {
      ...dictTypes[index],
      ...data,
      updateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
    };
    return ok(dictTypes[index], "更新成功");
  }

  const res: any = await request.post("/sys/dict/type/save", {
    id,
    name: data.name,
    code: data.code,
    description: data.description,
    status: mapStatusToBackend(data.status),
  });
  return {
    code: 200,
    message: res.message || "更新成功",
    data: null,
    success: true,
  };
}

/**
 * 删除字典类型
 */
export async function deleteDictType(id: string): Promise<ApiResponse<void>> {
  if (isMock) {
    const { dictTypes } = await import("../../mock/data/dict.data");
    const index = dictTypes.findIndex((item) => item.id === id);
    if (index === -1) return error(404, "字典类型不存在");
    dictTypes.splice(index, 1);
    return ok(undefined as unknown as void, "删除成功");
  }

  await request.post("/sys/dict/type/delete", { id });
  return { code: 200, message: "删除成功", data: null, success: true };
}

// ---------------- Dict Data APIs ----------------

/**
 * 获取所有字典数据
 */
export async function getAllDictData(): Promise<ApiResponse<DictData[]>> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    return ok(dictData);
  }

  const res: any = await request.get("/sys/dict/data/all");
  const list = (res.data || res).map(mapDataFromBackend);
  return { code: 200, message: res.message || "success", data: list, success: true };
}

/**
 * 根据类型获取字典数据
 */
export async function getDictDataByType(
  typeCode: string,
): Promise<ApiResponse<DictData[]>> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    const filtered = dictData.filter(
      (d) => d.typeCode === typeCode && d.status === "enabled",
    );
    filtered.sort((a, b) => a.sort - b.sort);
    return ok(filtered);
  }

  const res: any = await request.post("/sys/dict/data/page", {
    typeCode,
    page: 1,
    pageSize: 9999,
  });
  const list = ((res.data || res).list || []).map(mapDataFromBackend).filter((d: DictData) => d.status === "enabled");
  return { code: 200, message: "success", data: list, success: true };
}

/**
 * 获取字典数据列表（分页）
 */
export async function getDictDataList(
  params: DictQueryParams,
): Promise<
  ApiResponse<{
    list: DictData[];
    total: number;
    page: number;
    pageSize: number;
  }>
> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    const { page = 1, pageSize = 10, typeCode, label, value, status } = params;
    let filtered = [...dictData];
    if (typeCode) filtered = filtered.filter((item) => item.typeCode === typeCode);
    if (label) filtered = filtered.filter((item) => item.label.includes(label));
    if (value) filtered = filtered.filter((item) => item.value.includes(value));
    if (status) filtered = filtered.filter((item) => item.status === status);
    filtered.sort((a, b) => a.sort - b.sort);
    const start = (page - 1) * pageSize;
    const list = filtered.slice(start, start + pageSize);
    return ok({ list, total: filtered.length, page, pageSize });
  }

  const res: any = await request.post("/sys/dict/data/page", {
    page: params.page || 1,
    pageSize: params.pageSize || 10,
    typeCode: params.typeCode,
    label: params.label,
    value: params.value,
    status: mapStatusToBackend(params.status),
  });
  return {
    code: 200,
    message: res.message || "success",
    data: {
      list: ((res.data || res).list || []).map(mapDataFromBackend),
      total: (res.data || res).total || 0,
      page: (res.data || res).page || params.page || 1,
      pageSize: (res.data || res).pageSize || params.pageSize || 10,
    },
    success: true,
  };
}

/**
 * 创建字典数据
 */
export async function createDictData(
  data: Partial<DictData>,
): Promise<ApiResponse<DictData>> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    const newData: DictData = {
      id: String(Date.now()),
      typeCode: data.typeCode || "",
      label: data.label || "",
      value: data.value || "",
      sort: data.sort || 0,
      status: data.status || "enabled",
      remark: data.remark,
      createTime: new Date().toISOString().replace("T", " ").slice(0, 19),
      updateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
    };
    dictData.push(newData);
    return ok(newData, "创建成功");
  }

  const res: any = await request.post("/sys/dict/data/save", {
    typeCode: data.typeCode,
    label: data.label,
    value: data.value,
    sort: data.sort,
    status: mapStatusToBackend(data.status),
    remark: data.remark,
  });
  return {
    code: 200,
    message: res.message || "创建成功",
    data: res.data ? { ...data, id: res.data } as DictData : null,
    success: true,
  };
}

/**
 * 更新字典数据
 */
export async function updateDictData(
  id: string,
  data: Partial<DictData>,
): Promise<ApiResponse<DictData>> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    const index = dictData.findIndex((item) => item.id === id);
    if (index === -1) return error(404, "字典数据不存在");
    dictData[index] = {
      ...dictData[index],
      ...data,
      updateTime: new Date().toISOString().replace("T", " ").slice(0, 19),
    };
    return ok(dictData[index], "更新成功");
  }

  const res: any = await request.post("/sys/dict/data/save", {
    id,
    typeCode: data.typeCode,
    label: data.label,
    value: data.value,
    sort: data.sort,
    status: mapStatusToBackend(data.status),
    remark: data.remark,
  });
  return {
    code: 200,
    message: res.message || "更新成功",
    data: null,
    success: true,
  };
}

/**
 * 删除字典数据
 */
export async function deleteDictData(id: string): Promise<ApiResponse<void>> {
  if (isMock) {
    const { dictData } = await import("../../mock/data/dict.data");
    const index = dictData.findIndex((item) => item.id === id);
    if (index === -1) return error(404, "字典数据不存在");
    dictData.splice(index, 1);
    return ok(undefined as unknown as void, "删除成功");
  }

  await request.post("/sys/dict/data/delete", { id });
  return { code: 200, message: "删除成功", data: null, success: true };
}
