import { defHttp } from '/@/utils/http/axios';
import { omitBy, isNil, forEach, set } from 'lodash-es';
import { ModuleData, ShowStyle, Config } from '/@/components/Configurable/types';

/** 将原本的 formData 格式化为 api.saveOrUpdate 需要的格式 */
export function parseFormDataToParams(formData: Record<string, number | string | undefined>) {
  const params = {};
  forEach(formData, (v: string | undefined, k) => {
    if (v === undefined) return;
    return set(params, k, v);
  });

  return params;
}

/** 将 api.list 返回的数据格式化，格式化之后可以支持对应的表单使用，该方法会修改源数据 */
export function parseModuleData(listData: { moduleData: ModuleData; showStyle: ShowStyle }) {
  forEach(listData.showStyle, (v, k) => {
    listData[`showStyle.${k}`] = v;
  });

  return listData;
}

enum Api {
  list = '/safety/configurationData/getConfigurationDataList',
  save = '/safety/configurationData/addConfigurationData',
  edit = '/safety/configurationData/updateConfigurationData',
  deleteById = '/safety/configurationData/deleteConfigurationData',
}

/**
 * 列表接口
 * @param params
 */
export function list(params: any): Promise<{ records: Config[] }> {
  return defHttp.post({ url: Api.list, params: omitBy(params, isNil) }, { joinParamsToUrl: true }).then((result) => {
    result.records.forEach((item) => {
      parseModuleData(item);
    });

    return result;
  });
}

/**
 * 删除配置项
 */
export const deleteById = (params, handleSuccess) => {
  return defHttp.get({ url: Api.deleteById, params }, { joinParamsToUrl: true }).then(() => {
    handleSuccess();
  });
};

// /**
//  * 批量删除配置项
//  * @param params
//  */
// export const batchDeleteById = (params, handleSuccess) => {
//   Modal.confirm({
//     title: '确认删除',
//     content: '是否删除选中数据',
//     okText: '确认',
//     cancelText: '取消',
//     onOk: () => {
//       return defHttp.get({ url: Api.deleteById, data: params }, { joinParamsToUrl: true }).then(() => {
//         handleSuccess();
//       });
//     },
//   });
// };

/**
 * 保存或者更新，额外的，
 * @param params
 */
export const saveOrUpdate = (formData: Record<string, number | string | undefined>, isUpdate) => {
  const url = isUpdate ? Api.edit : Api.save;
  const params = parseFormDataToParams(formData);
  return defHttp.post({ url: url, params });
};
