import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';

const { createConfirm } = useMessage();

enum Api {
  list = '/oroqen/heritageProject/list',
  save = '/oroqen/heritageProject/add',
  edit = '/oroqen/heritageProject/edit',
  deleteOne = '/oroqen/heritageProject/delete',
  deleteBatch = '/oroqen/heritageProject/deleteBatch',
  importExcel = '/oroqen/heritageProject/importExcel',
  exportXls = '/oroqen/heritageProject/exportXls',
  queryById = '/oroqen/heritageProject/queryById',
  recommended = '/oroqen/heritageProject/recommended',
  byLevel = '/oroqen/heritageProject/byLevel',
  byCategory = '/oroqen/heritageProject/byCategory',
}

/**
 * 导出api
 */
export const getExportUrl = Api.exportXls;

/**
 * 导入api
 */
export const getImportUrl = Api.importExcel;

/**
 * 列表接口
 */
export const list = (params) => defHttp.get({ url: Api.list, params });

/**
 * 删除单个
 */
export const deleteOne = (params, handleSuccess) => {
  return defHttp.delete({ url: Api.deleteOne, params }, { joinParamsToUrl: true }).then(() => {
    handleSuccess();
  });
};

/**
 * 批量删除
 */
export const batchDelete = (params, handleSuccess) => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.delete({ url: Api.deleteBatch, data: params }, { joinParamsToUrl: true }).then(() => {
        handleSuccess();
      });
    }
  });
};

/**
 * 保存或者更新
 */
export const saveOrUpdate = (params, isUpdate) => {
  let url = isUpdate ? Api.edit : Api.save;
  return defHttp.post({ url: url, params });
};

/**
 * 通过ID查询
 */
export const queryById = (id) => {
  return defHttp.get({ url: Api.queryById, params: { id } });
};

/**
 * 获取非遗项目选项列表（用于下拉选择）
 */
export const getHeritageProjectOptions = () => {
  return defHttp.get({ 
    url: Api.list, 
    params: { 
      pageNo: 1, 
      pageSize: 1000,
      status: 1 // 只获取启用状态的项目
    } 
  }).then(res => {
    console.log('非遗项目API响应:', res);
    // 修正数据结构判断，直接使用 res.records
    if (res && res.records && Array.isArray(res.records)) {
      const options = res.records.map(item => ({
        label: item.projectName, // 使用 projectName 字段
        value: item.projectName, // 使用项目名称作为值
        key: item.id
      }));
      console.log('非遗项目选项数据:', options);
      return options;
    }
    console.log('非遗项目数据为空或格式错误');
    return [];
  }).catch(error => {
    console.error('获取非遗项目数据失败:', error);
    return [];
  });
};

/**
 * 获取推荐项目列表
 */
export const getRecommendedProjects = () => {
  return defHttp.get({ url: Api.recommended });
};

/**
 * 按级别获取项目列表
 */
export const getProjectsByLevel = (level) => {
  return defHttp.get({ url: Api.byLevel, params: { level } });
};

/**
 * 按类别获取项目列表
 */
export const getProjectsByCategory = (category) => {
  return defHttp.get({ url: Api.byCategory, params: { category } });
};