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

const { createConfirm } = useMessage();

enum Api {
  list = '/oroqen/heritageInheritor/list',
  save = '/oroqen/heritageInheritor/add',
  edit = '/oroqen/heritageInheritor/edit',
  deleteOne = '/oroqen/heritageInheritor/delete',
  deleteBatch = '/oroqen/heritageInheritor/deleteBatch',
  importExcel = '/oroqen/heritageInheritor/importExcel',
  exportXls = '/oroqen/heritageInheritor/exportXls',
}

/**
 * 导出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 });
};

/**
 * 获取传承人选项列表（用于下拉选择）
 */
export const getInheritorOptions = () => {
  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.name,
        value: item.id,
        key: item.id
      }));
      console.log('传承人选项数据:', options);
      return options;
    }
    console.log('传承人数据为空或格式错误');
    return [];
  }).catch(error => {
    console.error('获取传承人数据失败:', error);
    return [];
  });
};