import { request } from '../utils/axios';

export interface KeyVO {
  keyId?: number;
  id?: number; // 兼容字段
  keyCode?: string;
  keyName: string;
  keyNfc?: string;
  macAddress?: string;
  keySpec?: string;
  hardwareId?: number;
  hardwareName?: string;
  exStatus?: string; // 状态：'0' 或 '1'
  exRemark?: string; // 备注
  enableFlag?: string;
  remark?: string;
  createBy?: string;
  createTime?: Date | string;
  updateBy?: string;
  updateTime?: Date | string;
}

export interface PageParam {
  pageNo: number;
  pageSize: number;
  keyCode?: string;
  keyName?: string;
  keyNfc?: string;
  macAddress?: string;
}

// 分页响应类型
export interface PageResponse<T> {
  list: T[];
  total: number;
}

// 钥匙管理 API
export const keyApi = {
  // 查询钥匙-列表
  listKey: async (params: PageParam): Promise<PageResponse<KeyVO>> => {
    const response: any = await request.get({ 
      url: '/iscs/key/getKeyPage', 
      params 
    });
    
    // 处理响应数据格式
    if (response && typeof response === 'object') {
      if ('data' in response && response.data) {
        return response.data;
      } else if ('list' in response || 'records' in response) {
        return {
          list: (response as any).list || (response as any).records || [],
          total: (response as any).total || 0,
        };
      }
    }
    return response as PageResponse<KeyVO>;
  },

  // 获取钥匙详细信息
  getKeyInfo: async (id: number): Promise<KeyVO> => {
    const response: any = await request.get({
      url: '/iscs/key/selectKeyById',
      params: { id }
    });
    return (response?.data || response) as KeyVO;
  },

  // 新增钥匙
  addKey: async (data: KeyVO): Promise<void> => {
    await request.post({ 
      url: '/iscs/key/insertKey', 
      data 
    });
  },

  // 修改钥匙信息
  updateKey: async (data: KeyVO): Promise<void> => {
    await request.put({ 
      url: '/iscs/key/updateKey', 
      data 
    });
  },

  // 删除钥匙信息
  delKey: async (ids: number | number[] | string): Promise<void> => {
    const idsParam = typeof ids === 'string' ? ids : (Array.isArray(ids) ? ids.join(',') : ids);
    await request.delete({
      url: `/iscs/key/deleteKeyList?ids=${idsParam}`,
    });
  },
};

