import { SYSTEM_SERVICE_PREFIX } from '@/constants/service';
import { request } from '../request';

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();
}

/** 获取字典类型分页 */
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 function fetchGetDictDataPage(params: Api.Dict.DictDataSearchParams) {
  return request<Api.Dict.PageResult<Api.Dict.DictData>>({
    url: `${DICT_DATA_PREFIX}/page`,
    method: 'get',
    params
  });
}

/** 获取前端运行时字典缓存 */
export function fetchGetFrontendDictCache() {
  return request<Api.Dict.FrontendDictCache>({
    url: `${DICT_DATA_PREFIX}/frontend-cache`,
    method: 'get'
  });
}

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

/** 更新字典数据 */
export function fetchUpdateDictData(data: { id: number } & Api.Dict.SaveDictDataParams) {
  return request<boolean>({
    url: `${DICT_DATA_PREFIX}/update`,
    method: 'put',
    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 function fetchGetDictDataByCode(code: string) {
  return request<Api.Dict.PageResult<Api.Dict.DictData>>({
    url: `${DICT_DATA_PREFIX}/code?code=${code}`,
    method: 'get'
  });
}
