/**
 * 数据服务工具
 * 封装了与后端数据相关的API请求
 */

import { api } from './api';

/**
 * 养殖场数据服务
 */
export const farmService = {
  /**
   * 获取所有养殖场
   * @returns {Promise<Array>} 养殖场列表
   */
  async getAllFarms() {
    const response = await api.get('/farms/public');
    const farms = response && response.success ? response.data : response;
    
    // 标准化location字段格式
    return farms.map(farm => {
      if (farm.location) {
        // 如果location是字符串，尝试解析为JSON
        if (typeof farm.location === 'string') {
          try {
            farm.location = JSON.parse(farm.location);
          } catch (error) {
            console.warn(`解析养殖场 ${farm.id} 的location字段失败:`, error);
            farm.location = null;
          }
        }
        
        // 标准化location字段格式，支持latitude/longitude和lat/lng
        if (farm.location) {
          if (farm.location.latitude && farm.location.longitude) {
            // 将latitude/longitude转换为lat/lng
            farm.location.lat = farm.location.latitude;
            farm.location.lng = farm.location.longitude;
          } else if (farm.location.lat && farm.location.lng) {
            // 已经是lat/lng格式，保持不变
          } else {
            console.warn(`养殖场 ${farm.id} 的location字段格式不正确:`, farm.location);
            farm.location = null;
          }
        }
      }
      return farm;
    });
  },
  
  /**
   * 获取养殖场详情
   * @param {string} id - 养殖场ID
   * @returns {Promise<Object>} 养殖场详情
   */
  async getFarmById(id) {
    const response = await api.get(`/farms/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 创建养殖场
   * @param {Object} farmData - 养殖场数据
   * @returns {Promise<Object>} 创建的养殖场
   */
  async createFarm(farmData) {
    return api.post('/farms', farmData);
  },
  
  /**
   * 更新养殖场
   * @param {string} id - 养殖场ID
   * @param {Object} farmData - 养殖场数据
   * @returns {Promise<Object>} 更新后的养殖场
   */
  async updateFarm(id, farmData) {
    return api.put(`/farms/${id}`, farmData);
  },
  
  /**
   * 删除养殖场
   * @param {string} id - 养殖场ID
   * @returns {Promise<Object>} 删除结果
   */
  async deleteFarm(id) {
    return api.delete(`/farms/${id}`);
  }
};

/**
 * 动物数据服务
 */
export const animalService = {
  /**
   * 获取所有动物
   * @returns {Promise<Array>} 动物列表
   */
  async getAllAnimals() {
    const response = await api.get('/animals/public');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取养殖场的所有动物
   * @param {string} farmId - 养殖场ID
   * @returns {Promise<Array>} 动物列表
   */
  async getAnimalsByFarm(farmId) {
    const response = await api.get(`/farms/${farmId}/animals`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取动物详情
   * @param {string} id - 动物ID
   * @returns {Promise<Object>} 动物详情
   */
  async getAnimalById(id) {
    const response = await api.get(`/animals/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 创建动物
   * @param {Object} animalData - 动物数据
   * @returns {Promise<Object>} 创建的动物
   */
  async createAnimal(animalData) {
    return api.post('/animals', animalData);
  },
  
  /**
   * 更新动物
   * @param {string} id - 动物ID
   * @param {Object} animalData - 动物数据
   * @returns {Promise<Object>} 更新后的动物
   */
  async updateAnimal(id, animalData) {
    return api.put(`/animals/${id}`, animalData);
  },
  
  /**
   * 删除动物
   * @param {string} id - 动物ID
   * @returns {Promise<Object>} 删除结果
   */
  async deleteAnimal(id) {
    return api.delete(`/animals/${id}`);
  }
};

/**
 * 设备数据服务
 */
export const deviceService = {
  /**
   * 获取所有设备
   * @returns {Promise<Array>} 设备列表
   */
  async getAllDevices() {
    const response = await api.get('/devices/public');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取养殖场的所有设备
   * @param {string} farmId - 养殖场ID
   * @returns {Promise<Array>} 设备列表
   */
  async getDevicesByFarm(farmId) {
    const response = await api.get(`/farms/${farmId}/devices`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取设备详情
   * @param {string} id - 设备ID
   * @returns {Promise<Object>} 设备详情
   */
  async getDeviceById(id) {
    const response = await api.get(`/devices/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取设备状态
   * @param {string} id - 设备ID
   * @returns {Promise<Object>} 设备状态
   */
  async getDeviceStatus(id) {
    const response = await api.get(`/devices/${id}/status`);
    return response && response.success ? response.data : response;
  }
};

/**
 * 预警数据服务
 */
export const alertService = {
  /**
   * 获取所有预警
   * @returns {Promise<Array>} 预警列表
   */
  async getAllAlerts() {
    const response = await api.get('/alerts/public');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取养殖场的所有预警
   * @param {string} farmId - 养殖场ID
   * @returns {Promise<Array>} 预警列表
   */
  async getAlertsByFarm(farmId) {
    const response = await api.get(`/farms/${farmId}/alerts`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取预警详情
   * @param {string} id - 预警ID
   * @returns {Promise<Object>} 预警详情
   */
  async getAlertById(id) {
    const response = await api.get(`/alerts/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 处理预警
   * @param {string} id - 预警ID
   * @param {Object} data - 处理数据
   * @returns {Promise<Object>} 处理结果
   */
  async handleAlert(id, data) {
    return api.put(`/alerts/${id}/handle`, data);
  }
};

/**
 * 菜单数据服务
 */
export const menuService = {
  /**
   * 获取所有菜单
   * @returns {Promise<Array>} 菜单列表
   */
  async getAllMenus() {
    const response = await api.get('/menus', { params: { pageSize: 1000 } });
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取菜单详情
   * @param {string} id - 菜单ID
   * @returns {Promise<Object>} 菜单详情
   */
  async getMenuById(id) {
    const response = await api.get(`/menus/public/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取角色的菜单权限
   * @param {string} roleId - 角色ID
   * @returns {Promise<Object>} 角色菜单权限
   */
  async getRoleMenus(roleId) {
    const response = await api.get(`/menus/public/role/${roleId}`);
    return response && response.success ? response.data : response;
  }
};

/**
 * 角色权限数据服务
 */
export const rolePermissionService = {
  /**
   * 获取角色列表
   * @param {Object} params - 查询参数
   * @returns {Promise<Object>} 角色列表
   */
  async getRoles(params = {}) {
    const response = await api.get('/role-permissions/public/roles', { params });
    return response && response.success ? response.data : response;
  },

  /**
   * 获取角色详情
   * @param {string} id - 角色ID
   * @returns {Promise<Object>} 角色详情
   */
  async getRoleById(id) {
    const response = await api.get(`/role-permissions/public/roles/${id}`);
    return response && response.success ? response.data : response;
  },

  /**
   * 创建角色
   * @param {Object} roleData - 角色数据
   * @returns {Promise<Object>} 创建结果
   */
  async createRole(roleData) {
    const response = await api.post('/role-permissions/roles', roleData);
    return response && response.success ? response : response;
  },

  /**
   * 更新角色
   * @param {string} id - 角色ID
   * @param {Object} roleData - 角色数据
   * @returns {Promise<Object>} 更新结果
   */
  async updateRole(id, roleData) {
    const response = await api.put(`/role-permissions/roles/${id}`, roleData);
    return response && response.success ? response : response;
  },

  /**
   * 删除角色
   * @param {string} id - 角色ID
   * @returns {Promise<Object>} 删除结果
   */
  async deleteRole(id) {
    const response = await api.delete(`/role-permissions/roles/${id}`);
    return response && response.success ? response : response;
  },

  /**
   * 获取权限菜单树
   * @returns {Promise<Object>} 权限菜单树
   */
  async getPermissionTree() {
    const response = await api.get('/role-permissions/public/menus');
    return response && response.success ? response.data : response;
  },

  /**
   * 获取角色的菜单权限
   * @param {string} roleId - 角色ID
   * @returns {Promise<Object>} 角色菜单权限
   */
  async getRoleMenuPermissions(roleId) {
    const response = await api.get(`/role-permissions/public/roles/${roleId}/menus`);
    return response && response.success ? response : response;
  },

  /**
   * 设置角色菜单权限
   * @param {string} roleId - 角色ID
   * @param {Object} permissionData - 权限数据
   * @returns {Promise<Object>} 设置结果
   */
  async setRoleMenuPermissions(roleId, permissionData) {
    const response = await api.post(`/role-permissions/roles/${roleId}/menus`, permissionData);
    return response && response.success ? response : response;
  },

  // 获取所有功能权限
  async getAllPermissions(params = {}) {
    const response = await api.get('/role-permissions/public/permissions', { params });
    return response && response.success ? response : response;
  },

  // 获取权限模块列表
  async getPermissionModules() {
    const response = await api.get('/role-permissions/public/permissions/modules');
    return response && response.success ? response : response;
  },

  // 获取角色功能权限
  async getRoleFunctionPermissions(roleId) {
    const response = await api.get(`/role-permissions/public/roles/${roleId}/permissions`);
    return response && response.success ? response : response;
  },

  // 设置角色功能权限
  async setRoleFunctionPermissions(roleId, data) {
    const response = await api.post(`/role-permissions/roles/${roleId}/permissions`, data);
    return response && response.success ? response : response;
  },

  /**
   * 切换角色状态
   * @param {string} id - 角色ID
   * @param {Object} statusData - 状态数据
   * @returns {Promise<Object>} 切换结果
   */
  async toggleRoleStatus(id, statusData) {
    const response = await api.put(`/role-permissions/roles/${id}/status`, statusData);
    return response && response.success ? response : response;
  }
};

/**
 * 智能预警数据服务
 */
export const smartAlertService = {
  /**
   * 获取智能预警统计
   * @returns {Promise<Object>} 智能预警统计数据
   */
  async getSmartAlertStats() {
    const response = await api.get('/smart-alerts/public/stats');
    return response && response.success ? response.data : response;
  },

  /**
   * 获取智能耳标预警统计
   * @returns {Promise<Object>} 耳标预警统计
   */
  async getEartagAlertStats() {
    const response = await api.get('/smart-alerts/public/eartag/stats');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取智能耳标预警列表
   * @param {Object} params - 查询参数
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @param {string} params.search - 搜索关键词
   * @param {string} params.alertType - 预警类型筛选
   * @param {string} params.alertLevel - 预警级别筛选
   * @param {string} params.status - 设备状态筛选
   * @param {string} params.startDate - 开始日期
   * @param {string} params.endDate - 结束日期
   * @returns {Promise<Object>} 智能耳标预警列表响应
   */
  async getEartagAlerts(params = {}) {
    const response = await api.get('/smart-alerts/public/eartag', { params });
    return response;
  },

  /**
   * 获取单个智能耳标预警详情
   * @param {string} id - 预警ID
   * @returns {Promise<Object>} 预警详情
   */
  async getEartagAlertById(id) {
    const response = await api.get(`/smart-alerts/public/eartag/${id}`);
    return response && response.success ? response.data : response;
  },

  /**
   * 处理智能耳标预警
   * @param {string} id - 预警ID
   * @param {Object} data - 处理数据
   * @param {string} data.action - 处理动作
   * @param {string} data.notes - 处理备注
   * @param {string} data.handler - 处理人
   * @returns {Promise<Object>} 处理结果
   */
  async handleEartagAlert(id, data = {}) {
    const response = await api.post(`/smart-alerts/public/eartag/${id}/handle`, data);
    return response;
  },

  /**
   * 批量处理智能耳标预警
   * @param {Object} data - 批量处理数据
   * @param {Array} data.alertIds - 预警ID列表
   * @param {string} data.action - 处理动作
   * @param {string} data.notes - 处理备注
   * @param {string} data.handler - 处理人
   * @returns {Promise<Object>} 处理结果
   */
  async batchHandleEartagAlerts(data) {
    const response = await api.post('/smart-alerts/public/eartag/batch-handle', data);
    return response;
  },

  /**
   * 导出智能耳标预警数据
   * @param {Object} params - 导出参数
   * @param {string} params.search - 搜索关键词
   * @param {string} params.alertType - 预警类型筛选
   * @param {string} params.alertLevel - 预警级别筛选
   * @param {string} params.startDate - 开始日期
   * @param {string} params.endDate - 结束日期
   * @param {string} params.format - 导出格式 (json/csv)
   * @returns {Promise<Object>} 导出结果
   */
  async exportEartagAlerts(params = {}) {
    const response = await api.get('/smart-alerts/public/eartag/export', { params });
    return response;
  },
  
  /**
   * 获取智能项圈预警统计
   * @returns {Promise<Object>} 项圈预警统计
   */
  async getCollarAlertStats() {
    const response = await api.get('/smart-alerts/public/collar/stats');
    return response && response.success ? response.data : response;
  },

  /**
   * 获取智能项圈预警列表
   * @param {Object} params - 查询参数
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @param {string} params.search - 搜索关键词
   * @param {string} params.alertType - 预警类型筛选
   * @param {string} params.alertLevel - 预警级别筛选
   * @param {string} params.status - 设备状态筛选
   * @param {string} params.startDate - 开始日期
   * @param {string} params.endDate - 结束日期
   * @returns {Promise<Object>} 智能项圈预警列表响应
   */
  async getCollarAlerts(params = {}) {
    const response = await api.get('/smart-alerts/public/collar', { params });
    return response;
  },

  /**
   * 获取单个智能项圈预警详情
   * @param {string} id - 预警ID
   * @returns {Promise<Object>} 预警详情
   */
  async getCollarAlertById(id) {
    const response = await api.get(`/smart-alerts/public/collar/${id}`);
    return response && response.success ? response.data : response;
  },

  /**
   * 处理智能项圈预警
   * @param {string} id - 预警ID
   * @param {Object} data - 处理数据
   * @param {string} data.action - 处理动作
   * @param {string} data.notes - 处理备注
   * @param {string} data.handler - 处理人
   * @returns {Promise<Object>} 处理结果
   */
  async handleCollarAlert(id, data = {}) {
    const response = await api.post(`/smart-alerts/public/collar/${id}/handle`, data);
    return response;
  },

  /**
   * 批量处理智能项圈预警
   * @param {Object} data - 批量处理数据
   * @param {Array} data.alertIds - 预警ID列表
   * @param {string} data.action - 处理动作
   * @param {string} data.notes - 处理备注
   * @param {string} data.handler - 处理人
   * @returns {Promise<Object>} 处理结果
   */
  async batchHandleCollarAlerts(data) {
    const response = await api.post('/smart-alerts/public/collar/batch-handle', data);
    return response;
  },

  /**
   * 导出智能项圈预警数据
   * @param {Object} params - 导出参数
   * @param {string} params.search - 搜索关键词
   * @param {string} params.alertType - 预警类型筛选
   * @param {string} params.alertLevel - 预警级别筛选
   * @param {string} params.startDate - 开始日期
   * @param {string} params.endDate - 结束日期
   * @param {string} params.format - 导出格式 (json/csv)
   * @returns {Promise<Object>} 导出结果
   */
  async exportCollarAlerts(params = {}) {
    const response = await api.get('/smart-alerts/public/collar/export', { params });
    return response;
  }
};

/**
 * 智能设备数据服务（基于iot_jbq_client表）
 */
export const smartDeviceService = {
  /**
   * 获取所有智能设备
   * @returns {Promise<Array>} 智能设备列表
   */
  async getAllSmartDevices() {
    const response = await api.get('/smart-devices/public/eartags?limit=1000');
    // 后端返回的数据结构是 { success: true, data: { list: [...] } }
    if (response && response.success && response.data && response.data.list) {
      return response.data.list;
    }
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取智能设备详情
   * @param {string} id - 设备ID
   * @returns {Promise<Object>} 设备详情
   */
  async getSmartDeviceById(id) {
    const response = await api.get(`/smart-devices/eartags/search/${id}`);
    return response && response.success ? response.data : response;
  }
};

/**
 * 牛只数据服务（基于iot_cattle表）
 */
export const cattleService = {
  /**
   * 获取所有牛只
   * @returns {Promise<Array>} 牛只列表
   */
  async getAllCattle() {
    const response = await api.get('/iot-cattle/public?pageSize=1000');
    return response && response.success ? response.data.list : response;
  },
  
  /**
   * 获取牛只详情
   * @param {string} id - 牛只ID
   * @returns {Promise<Object>} 牛只详情
   */
  async getCattleById(id) {
    const response = await api.get(`/iot-cattle/public/${id}`);
    return response && response.success ? response.data : response;
  }
};

/**
 * 栏舍数据服务（基于cattle_pens表）
 */
export const penService = {
  /**
   * 获取所有栏舍
   * @returns {Promise<Array>} 栏舍列表
   */
  async getAllPens() {
    const response = await api.get('/cattle-pens/public?pageSize=1000');
    return response && response.success ? response.data.list : response;
  },
  
  /**
   * 获取栏舍详情
   * @param {string} id - 栏舍ID
   * @returns {Promise<Object>} 栏舍详情
   */
  async getPenById(id) {
    const response = await api.get(`/cattle-pens/public/${id}`);
    return response && response.success ? response.data : response;
  },
  
  /**
   * 创建栏舍
   * @param {Object} penData - 栏舍数据
   * @returns {Promise<Object>} 创建的栏舍
   */
  async createPen(penData) {
    return api.post('/cattle-pens', penData);
  },
  
  /**
   * 更新栏舍
   * @param {string} id - 栏舍ID
   * @param {Object} penData - 栏舍数据
   * @returns {Promise<Object>} 更新后的栏舍
   */
  async updatePen(id, penData) {
    return api.put(`/cattle-pens/${id}`, penData);
  },
  
  /**
   * 删除栏舍
   * @param {string} id - 栏舍ID
   * @returns {Promise<Object>} 删除结果
   */
  async deletePen(id) {
    return api.delete(`/cattle-pens/${id}`);
  }
};

/**
 * 统计数据服务
 */
export const statsService = {
  /**
   * 获取系统概览统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getDashboardStats() {
    const response = await api.get('/stats/public/dashboard');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取养殖场统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getFarmStats() {
    const response = await api.get('/stats/farms');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取动物统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getAnimalStats() {
    const response = await api.get('/stats/animals');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取设备统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getDeviceStats() {
    const response = await api.get('/stats/devices');
    return response && response.success ? response.data : response;
  },
  
  /**
   * 获取预警统计数据
   * @returns {Promise<Object>} 统计数据
   */
  async getAlertStats() {
    const response = await api.get('/stats/alerts');
    return response && response.success ? response.data : response;
  }
};