import { SYSTEM_SERVICE_PREFIX } from '@/constants/service';
import { request } from '../request';
import { type ServiceRequestResult, mapServiceResult } from './shared';

const DICT_TYPE_PREFIX = `${SYSTEM_SERVICE_PREFIX}/dict-type`;
const DICT_DATA_PREFIX = `${SYSTEM_SERVICE_PREFIX}/dict-data`;

function createBatchDeleteQuery(ids: number[]) {
  // 后端批量删除接口要求使用重复 query 参数，而不是数组 JSON。
  const query = new URLSearchParams();

  ids.forEach(id => {
    query.append('ids', String(id));
  });

  return query.toString();
}

type DictDataResponse = Omit<Api.Dict.DictData, 'colorType'> & {
  colorType?: string | null;
  color_type?: string | null;
  css_class?: string | null;
};

type DictDataPageResponse = Omit<Api.Dict.PageResult<Api.Dict.DictData>, 'list'> & {
  list: DictDataResponse[];
};

type FrontendDictDataResponse = Omit<Api.Dict.FrontendDictData, 'colorType'> & {
  colorType?: string | null;
  color_type?: string | null;
  css_class?: string | null;
};

type FrontendDictCacheResponse = Record<string, FrontendDictDataResponse[]>;

function normalizeColorType(value?: string | null) {
  return value?.trim() || null;
}

function normalizeDictData(data: DictDataResponse): Api.Dict.DictData {
  const { color_type: colorTypeFromSnakeCase, css_class: cssClassFromSnakeCase, ...rest } = data;

  return {
    ...rest,
    colorType: normalizeColorType(data.colorType ?? colorTypeFromSnakeCase),
    cssClass: normalizeColorType(data.cssClass ?? cssClassFromSnakeCase)
  };
}

function normalizeFrontendDictData(data: FrontendDictDataResponse): Api.Dict.FrontendDictData {
  const { color_type: colorTypeFromSnakeCase, css_class: cssClassFromSnakeCase, ...rest } = data;

  return {
    ...rest,
    colorType: normalizeColorType(data.colorType ?? colorTypeFromSnakeCase),
    cssClass: normalizeColorType(data.cssClass ?? cssClassFromSnakeCase)
  };
}

function toSaveDictDataRequest(data: Api.Dict.SaveDictDataParams) {
  return {
    ...data,
    colorType: normalizeColorType(data.colorType),
    remark: data.remark?.trim() || null
  };
}

/** 获取字典类型分页 */
export function fetchGetDictTypePage(params?: Api.Dict.DictTypeSearchParams) {
  return request<Api.Dict.PageResult<Api.Dict.DictType>>({
    url: `${DICT_TYPE_PREFIX}/page`,
    method: 'get',
    params
  });
}

/** 创建字典类型 */
export function fetchCreateDictType(data: Api.Dict.SaveDictTypeParams) {
  return request<number>({
    url: `${DICT_TYPE_PREFIX}/create`,
    method: 'post',
    data
  });
}

/** 更新字典类型 */
export function fetchUpdateDictType(data: { id: number } & Api.Dict.SaveDictTypeParams) {
  return request<boolean>({
    url: `${DICT_TYPE_PREFIX}/update`,
    method: 'put',
    data
  });
}

/** 删除字典类型 */
export function fetchDeleteDictType(id: number) {
  return request<boolean>({
    url: `${DICT_TYPE_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除字典类型 */
export function fetchBatchDeleteDictType(ids: number[]) {
  return request<boolean>({
    url: `${DICT_TYPE_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/** 获取字典数据分页 */
export async function fetchGetDictDataPage(params: Api.Dict.DictDataSearchParams) {
  const result = await request<DictDataPageResponse>({
    url: `${DICT_DATA_PREFIX}/page`,
    method: 'get',
    params
  });

  if (result.error || !result.data) {
    return result as unknown as Awaited<ReturnType<typeof request<Api.Dict.PageResult<Api.Dict.DictData>>>>;
  }

  return {
    ...result,
    data: {
      ...result.data,
      list: result.data.list.map(normalizeDictData)
    }
  };
}

/** 获取前端运行时字典缓存 */
export async function fetchGetFrontendDictCache() {
  const result = await request<FrontendDictCacheResponse>({
    url: `${DICT_DATA_PREFIX}/frontend-cache`,
    method: 'get'
  });

  return mapServiceResult(
    result as ServiceRequestResult<FrontendDictCacheResponse>,
    data =>
      Object.fromEntries(
        Object.entries(data).map(([dictType, list]) => [dictType, list.map(normalizeFrontendDictData)])
      ) as Api.Dict.FrontendDictCache
  );
}

/** 创建字典数据 */
export function fetchCreateDictData(data: Api.Dict.SaveDictDataParams) {
  return request<number>({
    url: `${DICT_DATA_PREFIX}/create`,
    method: 'post',
    data: toSaveDictDataRequest(data)
  });
}

/** 更新字典数据 */
export function fetchUpdateDictData(data: { id: number } & Api.Dict.SaveDictDataParams) {
  return request<boolean>({
    url: `${DICT_DATA_PREFIX}/update`,
    method: 'put',
    data: toSaveDictDataRequest(data)
  });
}

/** 删除字典数据 */
export function fetchDeleteDictData(id: number) {
  return request<boolean>({
    url: `${DICT_DATA_PREFIX}/delete`,
    method: 'delete',
    params: { id }
  });
}

/** 批量删除字典数据 */
export function fetchBatchDeleteDictData(ids: number[]) {
  return request<boolean>({
    url: `${DICT_DATA_PREFIX}/delete-list?${createBatchDeleteQuery(ids)}`,
    method: 'delete'
  });
}

/** 通过岗位编码获取该字典的所有字典数据 */
export async function fetchGetDictDataByCode(code: string) {
  const result = await request<DictDataPageResponse>({
    url: `${DICT_DATA_PREFIX}/code?code=${code}`,
    method: 'get'
  });

  return mapServiceResult(result as ServiceRequestResult<DictDataPageResponse>, data => ({
    ...data,
    list: (data.list ?? []).map(normalizeDictData)
  }));
}
