import request from '@/utils/request'

// ============ 燃气管网基础数据 ============
export function getPipeNetworkPage(pageNum, pageSize, params) {
  return request({ url: '/api/pipe-network/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getPipeNetworkById(id) {
  return request({ url: '/api/pipe-network/getById/' + id, method: 'get' })
}
export function getPipeNetworkOptions() {
  return request({ url: '/api/pipe-network/options', method: 'get' })
}
export function addPipeNetwork(data) {
  return request({ url: '/api/pipe-network/save', method: 'post', data })
}
export function updatePipeNetwork(data) {
  return request({ url: '/api/pipe-network/updateById', method: 'put', data })
}
export function deletePipeNetwork(id) {
  return request({ url: '/api/pipe-network/deleteById', method: 'delete', params: { id } })
}
export function exportPipeNetwork(params) {
  return request({ url: '/api/pipe-network/export', method: 'get', params, responseType: 'blob' })
}

// ============ 窨井管理 ============
export function getManholePage(pageNum, pageSize, params) {
  return request({ url: '/api/manhole/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getManholeById(id) {
  return request({ url: '/api/manhole/getById/' + id, method: 'get' })
}
export function getManholeOptions() {
  return request({ url: '/api/manhole/options', method: 'get' })
}
export function getManholeList() {
  return request({ url: '/api/manhole/list', method: 'get' })
}
export function addManhole(data) {
  return request({ url: '/api/manhole/save', method: 'post', data })
}
export function updateManhole(data) {
  return request({ url: '/api/manhole/updateById', method: 'put', data })
}
export function deleteManhole(id) {
  return request({ url: '/api/manhole/deleteById', method: 'delete', params: { id } })
}

// ============ 窨井井下设备关联 ============
// 查询设备已关联的井下设备列表
export function getManholeDeviceRels(equipmentId) {
  return request({ url: '/manhole/device/rel/list/' + equipmentId, method: 'get' })
}
// 搜索可关联设备（排除窨井类型5/9/10，排除已关联设备ID）
export function searchManholeRelDevices(params) {
  return request({ url: '/manhole/device/rel/search', method: 'get', params })
}
// 查询窨井关联的设备列表（兼容 Manhole.vue，manholeId 为 ManholeBase 的 ID）
export function getManholeDevices(manholeId) {
  return request({ url: '/manhole/device/rel/list/' + manholeId, method: 'get' })
}
// 新增窨井井下设备关联
export function addManholeDeviceRel(data) {
  return request({ url: '/manhole/device/rel/save', method: 'post', data })
}
// 删除窨井井下设备关联
export function deleteManholeDeviceRel(relId) {
  return request({ url: '/manhole/device/rel/delete', method: 'delete', params: { relId } })
}

// ============ 井盖监测设备阈值 ============
// 监测设备台账分页（后端已按排水/供水窨井类型过滤，isQueryManholeData=true 返回监测数据）
export function getManholeDevicePage(data) {
  return request({ url: '/manhole/device/findByPage', method: 'post', data })
}
// 监测设备台账详情
export function getManholeDeviceById(id) {
  return request({ url: '/manhole/device/getById/' + id, method: 'get' })
}
// 窨井设备统计：区域分布（数量/占比）+ 类型分布（数量/占比）
export function getManholeDeviceStatistics(data) {
  return request({ url: '/manhole/device/statistics', method: 'post', data })
}
export function getManholeAlarmDeviceList(data = {}) {
  return request({ url: '/manhole/device/getManholeDataList', method: 'post', data })
}

// 查询窨井关联设备的井下最新监测数据（e_real_time_data / radar_data）
export function getManholeRelDeviceData(equipmentId) {
  return request({ url: '/manhole/device/rel/data/' + equipmentId, method: 'get' })
}
// 态势图层 - 获取设备列表和统计（专用于 alarmSanalysis.vue）
export function getManholeLayerData(data = {}) {
  return request({ url: '/manhole/layer/getManholeLayerData', method: 'post', data })
}
/**
 * 窨井盖实时监测 - 获取设备报警监控列表
 *
 * 业务逻辑：
 *   查询所有窨井类型(equipment_type_id IN (9,10))设备的 jg_device_data 最新一条记录
 *   根据以下字段判定告警等级：
 *     - 倾斜角度: tilt_angle > angle_alarm_threshold → 严重告警
 *     - 水浸:     water_infiltration_alarm_status = 1 → 严重告警
 *     - 水位:     water_level_alarm_status = 1       → 严重告警
 *     - 低电量:   battery_level <= 20               → 一般告警
 *     - 弱信号:   signal_strength <= 20              → 一般告警
 *
 * 后端接口: POST /manhole/device/getAlarmMonitorList
 * 请求参数: { keyword?: string }  // keyword 模糊匹配 equipment_code / equipment_name
 * 返回结构:
 * {
 *   code: 200,
 *   data: {
 *     devices: [{
 *       equipmentId: string,
 *       equipmentCode: string,
 *       equipmentName: string,
 *       equipmentLocation: string,
 *       equipmentTypeName: string,
 *       manholeData: {                  // jg_device_data 最新一条记录
 *         id: string,
 *         batteryLevel: string,          // 电量百分比
 *         signalStrength: string,        // 信号强度百分比
 *         temperatureValue: string,      // 温度
 *         tiltAngle: string,             // 当前倾斜角度
 *         angleAlarmThreshold: string,   // 倾斜报警阈值
 *         alarmStatus: string,           // 综合报警状态 0=正常 1=报警
 *         waterInfiltrationAlarmStatus: string, // 水浸报警 0=正常 1=报警
 *         waterLevelAlarmStatus: string,        // 水位报警 0=正常 1=报警
 *         uploadTime: string,            // 数据上传时间
 *         createTime: string             // 记录创建时间
 *       },
 *       equipmentStatus: {              // 设备运维状态
 *         currentStatus: number,         // 1=在用 3=维修
 *         alarmStatus: number,           // 0=正常 1=报警
 *         onlineStatus: number           // 0=离线 1=在线
 *       }
 *     }],
 *     statistics: {
 *       total: number,                  // 设备总数
 *       critical: number,               // 严重告警数
 *       warning: number,                // 一般告警数
 *       normal: number,                 // 正常设备数
 *       onlineCount: number,            // 在线设备数
 *       avgBattery: number              // 平均电量
 *     }
 *   }
 * }
 */
export function getManholeAlarmMonitorList(data = {}) {
  return request({ url: '/manhole/device/getAlarmMonitorList', method: 'post', data })
}

export function getManholeAlarmDeviceDetail(id) {
  return request({ url: '/manhole/device/getById/' + id, method: 'get' })
}
export function saveManholeAlarmThreshold(data) {
  return request({ url: '/manhole/device/saveWarningThreshold', method: 'post', data })
}

export function getManholeTerminalFaultPage(data) {
  return request({ url: '/manhole/terminalFault/findByPage', method: 'post', data })
}

export function getManholeTerminalFaultDetail(id) {
  return request({ url: '/manhole/terminalFault/getById/' + id, method: 'get' })
}

export function handleManholeTerminalFault(data) {
  return request({ url: '/manhole/terminalFault/handleFault', method: 'post', data })
}

// ============ 井盖案件流转 / 工单处置 ============
export function getManholeCasePage(data) {
  return request({ url: '/manhole/caseInfo/findByPage', method: 'post', data })
}

export function getManholeCaseDetail(id) {
  return request({ url: '/manhole/caseInfo/getById/' + id, method: 'get' })
}

export function verifyManholeCase(data) {
  return request({ url: '/manhole/caseInfo/verifyCaseInfo', method: 'post', data })
}

export function getManholeWorkOrderPage(data) {
  return request({ url: '/manhole/workOrder/findByPage', method: 'post', data })
}

export function getManholeWorkOrderProcessingPage(data) {
  return request({ url: '/manhole/workOrder/findProcessingPage', method: 'post', data })
}

export function getManholeWorkOrderFinishedPage(data) {
  return request({ url: '/manhole/workOrder/findFinishedPage', method: 'post', data })
}

export function getManholeWorkOrderDetail(id) {
  return request({ url: '/manhole/workOrder/getById/' + id, method: 'get' })
}

export function addManholeWorkOrder(data) {
  return request({ url: '/manhole/workOrder/addWorkOrder', method: 'post', data })
}

export function operManholeWorkOrder(data) {
  return request({ url: '/manhole/workOrder/operWorkOrder', method: 'post', data })
}
// 修改设备运维状态（currentStatus：1-在用 2-闲置 3-维修 4-报废 5-待入库）
export function updateManholeDeviceStatus(data) {
  return request({ url: '/manhole/device/updateDeviceStatus', method: 'post', data })
}

// ============ 运维数据统计 ============
// 运维看板统计数据：一次返回KPI指标/异常终端趋势/处置率延期率趋势/问题类型分布/区域排行/异常终端列表
export function getManholeMaintenanceDashboard(data = {}) {
  return request({ url: '/manhole/maintenanceDataStat/getDashboardStat', method: 'post', data })
}
// 根据日期查询运维数据统计（KPI指标）
export function getMaintenanceDataStatByDate(data) {
  return request({ url: '/manhole/maintenanceDataStat/queryByDate', method: 'post', data })
}
// 周度/月度 异常终端设备数量趋势分析
export function getAbnormalTerminalTrend(data) {
  return request({ url: '/manhole/maintenanceDataStat/abnormalTerminalTrend', method: 'post', data })
}
// 周度/月度 案件处置率/延期率趋势分析
export function getCaseRateTrend(data) {
  return request({ url: '/manhole/maintenanceDataStat/caseRateTrend', method: 'post', data })
}

// ============ 维修记录 ============
export function getRepairRecordPage(pageNum, pageSize, params) {
  return request({ url: '/api/repair-record/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getRepairStats() {
  return request({ url: '/api/repair-record/stats', method: 'get' })
}

// 可燃气体报警
export function getGasAlarmEquipment() {
  return request({ url: '/api/gas-alarm/equipment', method: 'get' })
}
export function getGasAlarmHistory(pageNum, pageSize, startDate, endDate, deviceCode) {
  return request({ url: '/api/gas-alarm/history', method: 'get', params: { pageNum, pageSize, startDate, endDate, deviceCode } })
}
export function getGasAlarmStats() {
  return request({ url: '/api/gas-alarm/stats', method: 'get' })
}
export function resolveGasAlarm(id) {
  return request({ url: '/api/gas-alarm/resolve/' + id, method: 'put' })
}
export function dispatchGasAlarm(id) {
  return request({ url: '/api/gas-alarm/dispatch/' + id, method: 'post' })
}

// 管线压力报警
export function getPressureAlarmEquipment() { return request({ url: '/api/pressure-alarm/equipment', method: 'get' }) }
export function getPressureAlarmHistory(pageNum, pageSize, startDate, endDate, deviceCode) { return request({ url: '/api/pressure-alarm/history', method: 'get', params: { pageNum, pageSize, startDate, endDate, deviceCode } }) }
export function getPressureAlarmStats() { return request({ url: '/api/pressure-alarm/stats', method: 'get' }) }
export function resolvePressureAlarm(id) { return request({ url: '/api/pressure-alarm/resolve/' + id, method: 'put' }) }
export function dispatchPressureAlarm(id) { return request({ url: '/api/pressure-alarm/dispatch/' + id, method: 'post' }) }
// 培训课程
export function getCourseList(params) { return request({ url: '/api/drill/course/list', method: 'get', params }) }
export function saveCourse(data) { return request({ url: '/api/drill/course', method: 'post', data }) }
export function updateCourse(data) { return request({ url: '/api/drill/course', method: 'put', data }) }
export function deleteCourse(id) { return request({ url: '/api/drill/course/' + id, method: 'delete' }) }
// 演练计划
export function getDrillPlanList(params) { return request({ url: '/api/drill/plan/list', method: 'get', params }) }
export function saveDrillPlan(data) { return request({ url: '/api/drill/plan', method: 'post', data }) }
export function updateDrillPlan(data) { return request({ url: '/api/drill/plan', method: 'put', data }) }
export function deleteDrillPlan(id) { return request({ url: '/api/drill/plan/' + id, method: 'delete' }) }
// 实战演练
// 实战演练模板
export function getPracticalTemplates() { return request({ url: '/api/drill/practical/template', method: 'get' }) }
export function savePracticalTemplate(data) { return request({ url: '/api/drill/practical/template', method: 'post', data }) }
export function updatePracticalTemplate(data) { return request({ url: '/api/drill/practical/template', method: 'put', data }) }
export function deletePracticalTemplate(id) { return request({ url: '/api/drill/practical/template/' + id, method: 'delete' }) }
// 实战演练计划
export function getPracticalPlans() { return request({ url: '/api/drill/practical/plan', method: 'get' }) }
export function savePracticalPlan(data) { return request({ url: '/api/drill/practical/plan', method: 'post', data }) }
export function updatePracticalPlan(data) { return request({ url: '/api/drill/practical/plan', method: 'put', data }) }
export function deletePracticalPlan(id) { return request({ url: '/api/drill/practical/plan/' + id, method: 'delete' }) }
// 模拟演练
export function getSimProjects() { return request({ url: '/api/drill/sim/project', method: 'get' }) }
export function saveSimProject(data) { return request({ url: '/api/drill/sim/project', method: 'post', data }) }
export function deleteSimProject(id) { return request({ url: '/api/drill/sim/project/' + id, method: 'delete' }) }
export function getSimScene(pid) { return request({ url: '/api/drill/sim/scene/' + pid, method: 'get' }) }
export function getSimEvent(pid) { return request({ url: '/api/drill/sim/event/' + pid, method: 'get' }) }
export function getSimRole(pid) { return request({ url: '/api/drill/sim/role/' + pid, method: 'get' }) }
export function getSimTask(pid) { return request({ url: '/api/drill/sim/task/' + pid, method: 'get' }) }
export function getSimLog(pid) { return request({ url: '/api/drill/sim/log/' + pid, method: 'get' }) }
export function getSimResult(pid) { return request({ url: '/api/drill/sim/result/' + pid, method: 'get' }) }
export function addSimLog(data) { return request({ url: '/api/drill/sim/log', method: 'post', data }) }
export function processSimDrill(projectId, action, category) { return request({ url: '/api/drill/sim/process', method: 'post', params: { projectId, action, category } }) }
export function saveSimScene(data) { return request({ url: '/api/drill/sim/scene', method: 'post', data }) }
export function deleteSimScene(id) { return request({ url: '/api/drill/sim/scene/' + id, method: 'delete' }) }
export function saveSimEvent(data) { return request({ url: '/api/drill/sim/event', method: 'post', data }) }
export function deleteSimEvent(id) { return request({ url: '/api/drill/sim/event/' + id, method: 'delete' }) }
export function saveSimRole(data) { return request({ url: '/api/drill/sim/role', method: 'post', data }) }
export function saveSimTask(data) { return request({ url: '/api/drill/sim/task', method: 'post', data }) }
export function getDrillStats() { return request({ url: '/api/drill/stats', method: 'get' }) }
export function sendDrillAnalysis(data) { return request({ url: '/api/drill/practical/analysis', method: 'post', data }) }
// 实战演练记录
export function getDrillRecord(planId) { return request({ url: '/api/drill/practical/record/' + planId, method: 'get' }) }
export function saveDrillRecord(data) { return request({ url: '/api/drill/practical/record', method: 'post', data }) }
export function updateDrillRecord(data) { return request({ url: '/api/drill/practical/record', method: 'put', data }) }
// 演练监测信息
export function getDrillMonitoring(recordId) { return request({ url: '/api/drill/practical/monitoring/' + recordId, method: 'get' }) }
export function saveDrillMonitoring(data) { return request({ url: '/api/drill/practical/monitoring', method: 'post', data }) }
export function deleteDrillMonitoring(id) { return request({ url: '/api/drill/practical/monitoring/' + id, method: 'delete' }) }
// 演练分析结果
export function getDrillAnalysis(planId) { return request({ url: '/api/drill/practical/analysis/' + planId, method: 'get' }) }
export function exportDrillReport(planId) { return request({ url: '/api/drill/practical/report/' + planId, method: 'get', responseType: 'blob' }) }
// 更新演练计划状态
export function updatePlanStatus(planId, status) { return request({ url: '/api/drill/practical/plan/status', method: 'put', params: { planId, status } }) }
export function getRepairRecordById(id) {
  return request({ url: '/api/repair-record/getById/' + id, method: 'get' })
}
export function getRepairRecordByNetwork(networkId) {
  return request({ url: '/api/repair-record/list-by-network/' + networkId, method: 'get' })
}
export function addRepairRecord(data) {
  return request({ url: '/api/repair-record/save', method: 'post', data })
}
export function updateRepairRecord(data) {
  return request({ url: '/api/repair-record/updateById', method: 'put', data })
}
export function deleteRepairRecord(id) {
  return request({ url: '/api/repair-record/deleteById', method: 'delete', params: { id } })
}

// ============ 监测设备管理 ============
export function getEquipmentList() {
  return request({ url: '/EquipmentBase/getList', method: 'get' })
}
export function getEquipmentPage(pageNum, pageSize, params) {
  return request({ url: '/EquipmentBase/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getEquipmentFullPage(pageNum, pageSize, params) {
  return request({ url: '/api/equipment/findFullByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getEquipmentById(id) {
  return request({ url: '/EquipmentBase/getById/' + id, method: 'get' })
}
export function addEquipment(data) {
  const params = {}
  if (data.networkId) params.networkId = data.networkId
  if (data.pointId) params.pointId = data.pointId
  return request({ url: '/api/equipment/save', method: 'post', data, params })
}
export function updateEquipment(data) {
  const params = {}
  if (data.networkId) params.networkId = data.networkId
  if (data.pointId) params.pointId = data.pointId
  return request({ url: '/api/equipment/updateById', method: 'put', data, params })
}
export function deleteEquipment(id) {
  return request({ url: '/api/equipment/deleteById', method: 'delete', params: { id } })
}
export function getEquipmentTypeList() {
  return request({ url: '/EquipmentType/getList', method: 'get' })
}
export function getEquipmentByTopLevelType(typeName) {
  return request({ url: '/EquipmentBase/findByTopLevelType', method: 'get', params: { typeName } })
}
export function getGasDashboardSummary() {
  return request({ url: '/api/gas-dashboard/summary', method: 'get' })
}
export function getEquipmentStatus(equipmentId) {
  return request({ url: '/api/equipment/status/' + equipmentId, method: 'get' })
}
export function getEquipmentAbnormalList() {
  return request({ url: '/api/equipment/abnormal', method: 'get' })
}
export function getPointRelByEquipment(equipmentId) {
  return request({ url: '/api/equipment/point-rel/' + equipmentId, method: 'get' })
}
export function getEquipmentByPoint(pointId) {
  return request({ url: '/api/equipment/point-rel/by-point/' + pointId, method: 'get' })
}
// ============ 管点-设备关联 ============
export function getPipePointDevices(pointId) {
  return request({ url: '/api/gas-pipe-point/device/list/' + pointId, method: 'get' })
}
export function addPipePointDeviceRel(data) {
  return request({ url: '/api/gas-pipe-point/device/save', method: 'post', data })
}
export function saveEquipmentDeviceRel(data) {
  return request({ url: '/api/equipment/device-rel/save', method: 'post', data })
}
export function addPipePointDeviceRelBatch(dataList) {
  return request({ url: '/api/gas-pipe-point/device/save-batch', method: 'post', dataList })
}
export function deletePipePointDeviceRel(relId) {
  return request({ url: '/api/gas-pipe-point/device/delete', method: 'delete', params: { relId } })
}
export function savePointRel(data) {
  return request({ url: '/api/equipment/point-rel/save', method: 'post', data })
}
export function deletePointRel(relId) {
  return request({ url: '/api/equipment/point-rel/delete', method: 'delete', params: { relId } })
}

// ============ 测点管理 ============
export function getPointPage(pageNum, pageSize, params) {
  return request({ url: '/api/monitor-point/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getPointById(id) {
  return request({ url: '/api/monitor-point/getById/' + id, method: 'get' })
}
export function addPoint(data) {
  return request({ url: '/api/monitor-point/save', method: 'post', data })
}
export function updatePoint(data) {
  return request({ url: '/api/monitor-point/updateById', method: 'put', data })
}
export function deletePoint(id) {
  return request({ url: '/api/monitor-point/deleteById', method: 'delete', params: { id } })
}

// ============ 燃气管点管理 ============
export function getGasPipePointPage(pageNum, pageSize, params) {
  return request({ url: '/api/gas-pipe-point/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getGasPipePointById(id) {
  return request({ url: '/api/gas-pipe-point/getById/' + id, method: 'get' })
}
export function getGasPipePointByNetwork(networkId) {
  return request({ url: '/api/gas-pipe-point/list-by-network/' + networkId, method: 'get' })
}
export function getGasPipePointOptions() {
  return request({ url: '/api/gas-pipe-point/options', method: 'get' })
}
export function addGasPipePoint(data) {
  return request({ url: '/api/gas-pipe-point/save', method: 'post', data })
}
export function updateGasPipePoint(data) {
  return request({ url: '/api/gas-pipe-point/updateById', method: 'put', data })
}
export function deleteGasPipePoint(id) {
  return request({ url: '/api/gas-pipe-point/deleteById', method: 'delete', params: { id } })
}

// ============ GIS一张图 ============
export function getGisPipeLines(params) {
  return request({ url: '/api/gis/pipe-lines', method: 'get', params })
}
export function getGisManholes() {
  return request({ url: '/api/gis/manholes', method: 'get' })
}
export function getGisEquipments(params) {
  return request({ url: '/api/gis/equipments', method: 'get', params })
}

// ============ 预警阈值配置 ============
export function getWarningThresholdPage(pageNum, pageSize, params) {
  return request({ url: '/warningThreshold/findByPage', method: 'get', params: { pageNum, pageSize, ...params } })
}
export function getWarningThresholdModulePage(pageNum, pageSize, typeName, params) {
  return request({ url: '/warningThreshold/findByModulePage', method: 'get', params: { pageNum, pageSize, typeName, ...params } })
}
export function getWarningThresholdList(params) {
  return request({ url: '/warningThreshold/getWarningThresholdList', method: 'get', params })
}
export function getWarningThresholdById(id) {
  return request({ url: '/warningThreshold/getById/' + id, method: 'get' })
}
export function saveWarningThreshold(data, moduleType) {
  return request({ url: '/warningThreshold/save', method: 'post', data, params: moduleType ? { moduleType } : undefined })
}
export function updateWarningThreshold(data, moduleType) {
  return request({ url: '/warningThreshold/update', method: 'post', data, params: moduleType ? { moduleType } : undefined })
}
export function deleteWarningThreshold(ids) {
  return request({ url: '/warningThreshold/deleteBatch', method: 'post', data: ids })
}
