/**
 * API 接口层
 * 基础路径: /laboratory/labScreen (lab), /auth (auth)
 */
import request from '@/utils/request'

function wrapResult(data) {
  return { code: 200, data, msg: 'success' }
}

const PIE_COLORS = ['#48d7ff', '#3a7bff', '#36d399', '#ffb020', '#ff8c00', '#ff4d4f', '#a78bfa', '#e91e63', '#00e5ff', '#9c27b0']

// ======================== 1. 实验室基本情况统计 ========================
let _labBasicCache = null

async function fetchLabBasic() {
  if (_labBasicCache) return _labBasicCache
  const res = await request.get('/laboratory/labScreen/labBasicStatistics')
  if (res.code === 200 && res.data) { _labBasicCache = res.data; return res.data }
  throw new Error(res.message || '接口异常')
}

function clearLabBasicCache() {
  setTimeout(() => { _labBasicCache = null }, 5000)
}

export async function getLabBasicStats() {
  const [raw, levelCfg] = await Promise.all([fetchLabBasic(), getLevelTitleConfig()])
  clearLabBasicCache()
  const counts = [raw.levelOneCount, raw.levelTwoCount, raw.levelThreeCount, raw.levelFourCount]
  const levels = levelCfg.map((l, i) => ({ name: l.name, value: counts[i] || 0, color: l.color }))
  return wrapResult({
    totalLabs: raw.labTotal,
    levels,
    usage: { using: raw.useTotal, abnormal: raw.exceptionalTotal, idle: raw.availableTotal }
  })
}

// ======================== 2. 实验室安全分级统计（复用 labBasicStatistics 数据）========================
export async function getSafetyLevelStats() {
  const [raw, levelCfg] = await Promise.all([fetchLabBasic(), getLevelTitleConfig()])
  clearLabBasicCache()
  const departments = (raw.labLevelVOList || []).map(d => ({
    name: d.deptName,
    total: (d.levelOneCount || 0) + (d.levelTwoCount || 0) + (d.levelThreeCount || 0) + (d.levelFourCount || 0),
    level1: d.levelOneCount || 0,
    level2: d.levelTwoCount || 0,
    level3: d.levelThreeCount || 0,
    level4: d.levelFourCount || 0
  }))
  return wrapResult({ departments, levelCfg })
}

// ======================== 3. 实验室进入人数统计及走势 ========================
export async function getPersonStats() {
  const res = await request.get('/laboratory/labScreen/passOutTrend')
  if (res.code === 200 && res.data) {
    const d = res.data
    const toDigits = n => String(n).split('').map(Number)
    const hourMap = {}
    ;(d.entryTrend || []).forEach(t => { hourMap[t.hour] = { enter: t.count, lab: 0 } })
    ;(d.labUserTrend || []).forEach(t => {
      if (!hourMap[t.hour]) hourMap[t.hour] = { enter: 0, lab: 0 }
      hourMap[t.hour].lab = t.count
    })
    const hourlyData = Object.keys(hourMap).sort((a, b) => a - b).map(h => ({
      hour: h + ':00', enter: hourMap[h].enter, lab: hourMap[h].lab
    }))
    return wrapResult({ todayTotal: toDigits(d.todayEntryCount || 0), currentLab: toDigits(d.currentLabUserCount || 0), hourlyData })
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 4. 实验环境安全智能感知 ========================
export async function getEnvSensingList() {
  const res = await request.get('/laboratory/labScreen/envMonitor', { params: { page: 1, pageSize: 50 } })
  if (res.code === 200 && res.data && res.data.records) {
    const list = res.data.records.map((r, i) => {
      const sensors = r.sensorList || []
      const find = code => sensors.find(s => s.code === code)
      const tempS = find('temperature'), humS = find('humidity'), tvocS = find('tvoc'), co2S = find('co2'), o2S = find('o2')
      return {
        id: r.subId || i + 1,
        lab: r.subName + (r.roomNum ? `(${r.roomNum})` : ''),
        dept: '',
        temp: tempS ? tempS.deviceValue : '-',
        humidity: humS ? humS.deviceValue : '-',
        tvoc: tvocS ? tvocS.deviceValue : '-',
        co2: { value: co2S ? co2S.deviceValue : '-', warn: co2S ? !co2S.operatingState : false },
        o2: { value: o2S ? o2S.deviceValue : '-', warn: o2S ? !o2S.operatingState : false },
        sensorList:r.sensorList
      }
    })
    return wrapResult({ list })
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 5. 实验室实时风险预警 ========================
export async function getRiskWarningList() {
  const res = await request.get('/laboratory/labScreen/riskWarning')
  if (res.code === 200 && res.data) {
    const d = res.data
    return wrapResult({
      totalMonth: d.monthAlarmCount,
      emergencyCount: d.emergencyCount || 0,
      violationCount: d.violationCount || 0,
      list: (d.eventList || []).map(e => ({
        id: e.id,
        lab: e.labInfo || e.subName,
        type: e.eventName,
        category: e.category || '',
        time: e.eventStartTime ? e.eventStartTime.replace('T', ' ') : ''
      }))
    })
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 6. 智能环境感知应用设备统计 ========================
export async function getDeviceStats() {
  const res = await request.get('/laboratory/labScreen/iotDeviceStatistics')
  if (res.code === 200 && res.data) {
    const d = res.data
    return wrapResult({
      online: d.onlineCount, offline: d.offlineCount, onlineRate: d.onlineRate,
      devices: [
        { name: '电子信息铭牌', count: d.tagCount || 0 },
        { name: '化学品智能终端', count: d.terminalCount || 0 },
        { name: '传感器', count: d.sensorCount || 0 },
        { name: '摄像头', count: d.cameraCount || 0 },
        { name: '智能设备', count: d.iotCount || 0 }
      ].filter(i => i.count > 0)
    })
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 7. 实验室设备分类及使用统计 ========================
export async function getEquipmentStats() {
  const res = await request.get('/laboratory/labScreen/deviceCategoryStat')
  if (res.code === 200 && res.data) {
    const d = res.data
    return wrapResult({
      categories: (d.categoryList || []).map((c, i) => ({
        name: c.categoryOneName, value: c.totalCount, color: PIE_COLORS[i % PIE_COLORS.length]
      })),
      summary: {
        totalDevices: d.totalCount,
        totalHours: d.totalUsageHours ? d.totalUsageHours.toLocaleString() : '0',
        usageRate: String(d.usageRate || 0)
      },
      status: {
        using:  (d.usageStatusList  || []).find(s => s.name === '使用')?.count  || 0,
        idle:   (d.usageStatusList  || []).find(s => s.name === '空闲')?.count  || 0,
        normal: (d.deviceStatusList || []).find(s => s.name === '正常')?.count  || 0,
        repair: (d.deviceStatusList || []).find(s => s.name === '维修')?.count  || 0
      }
    })
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 天气接口 ========================
export async function getWeather() {
  const res = await request.get('/laboratory/labScreen/weather')
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || '接口异常')
}

// ======================== 8. 建筑结构导航 ========================
function transformTree(nodes) {
  if (!nodes) return []
  return nodes.map(n => ({ id: n.id, label: n.name, children: transformTree(n.buildFloorVoList) }))
}

export async function getBuildingTree(params = {}) {
  const res = await request.post('/laboratory/labScreen/monitorTree', params)
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || '接口异常')
}

// ======================== 9. 视频列表 ========================
export async function getVideoList(params = {}) {
  const res = await request.post('/iot/camera/large/findByCondition', {
    subIds: params.subIds || [], streamType: 0, protocol: params.protocol || 'ws', source: params.source || 3,
    page: params.page || 1, pageSize: params.pageSize || 9
  })
  if (res.code === 200 && res.data && res.data.records) {
    return res
    // return wrapResult({
    //   total: res.data.total, page: res.data.current,
    //   list: res.data.records.map(r => ({
    //     id: r.deviceNo, name: r.subjectName + (r.room ? `(${r.room})` : ''),
    //     ai: false, status: r.streamUrl ? 'online' : 'offline', streamUrl: r.streamUrl
    //   }))
    // })
  }
  throw new Error(res.message || '接口异常')
}
// ======================== 9.1 根据设备ID查询视频流 ========================


export async function iotCameraGetPreviewURLs(params = {}) {
  const res = await request.get('/iot/camera/getPreviewURLs',{params})
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || '接口异常')
}

// ======================== 13. 实验室分级配置 ========================
let _levelConfigCache = null
export async function getLevelTitleConfig() {
  if (_levelConfigCache) return _levelConfigCache
  const res = await request.post('/laboratory/labScreen/getLevelTitleList')
  if (res.code === 200 && res.data) {
    // 按 levelGrade 排序，返回 [{grade, name, color}]
    _levelConfigCache = res.data
      .sort((a, b) => a.levelGrade - b.levelGrade)
      .map(l => ({ grade: l.levelGrade, name: l.titleName, color: l.titleColor }))
    setTimeout(() => { _levelConfigCache = null }, 5 * 60 * 1000)
    return _levelConfigCache
  }
  throw new Error(res.message || '接口异常')
}

// ======================== 系统配置接口 ========================
export async function getMqttConfig() {
  const res = await request.post('/system/config/info/getConfigByType', { category: 2, configType: 5 })
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || '接口异常')
}

// ======================== 化学品库动态统计 ========================
export async function getChemicalStats() {
  const res = await request.get('/chemical/stock/stockSummary')
  if (res.code === 200 && res.data) return res.data
  throw new Error(res.message || '接口异常')
}

// ======================== 验证码接口 ========================
export async function getCaptcha(id = 0) {
  const res = await request.get('/auth/captcha', { params: { id } })
  if (res.code === 200 && res.data) return res.data
  throw new Error(res.message || '获取验证码失败')
}

// ======================== 登录接口 ========================
export async function loginApi(params) {
  const res = await request.post('/auth/bigLogin', params)
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || res.msg || '登录失败')
}

// ======================== 7. 风险预警-触发预案信息 ========================
export async function getTriggerInfo() {
  const res = await request.get('/laboratory/labScreen/selectTriggerInfo')
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || '接口异常')
}

// ======================== 12. 根据条件查询楼道实验室信息 ========================
export async function laboratoryLabScreenRooms(params) {
  const res = await request.post('/laboratory/labScreen/rooms', params)
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || res.msg || '接口异常')
}

// ======================== 11. 二级学院下拉列表 ========================
export async function laboratoryLabScreenDeptDropList(params) {
  const res = await request.post('/laboratory/labScreen/deptDropList', params)
  if (res.code === 200 && res.data) return wrapResult(res.data)
  throw new Error(res.message || res.msg || '接口异常')
}

//应急处置-获取楼层布局数据
export function laboratoryBigViewGetFloorByBigView(params) {
  return request({
    url: '/laboratory/bigView/getFloorByBigView',
    method: 'get',
    params
  })
}
//应急处置-查询当前正在发生的预案
export function laboratoryBigViewSelectTriggerInfo(params) {
  return request({
    url: '/laboratory/bigView/selectTriggerInfo',
    method: 'get',
    params
  })
}
//应急处置-获取当前楼栋-楼层下的疏散数据
export function laboratoryExitLineGetRedisEvacuation(data = {}) {
  return request({
    url: '/laboratory/exitLine/getRedisEvacuation',
    method: 'post',
    data
  })
}

//获取摄像头流地址
export function iotCameraFindByCondition(data = {}) {
  return request({
    url: '/iot/camera/findByCondition',
    method: 'post',
    data
  })
}
//应急处置-查询实验室传感器列表
export function iotBigViewDeviceFindBySubId(params) {
  return request({
    url: '/iot/bigView/device/findBySubId',
    method: 'get',
    params
  })
}

//应急处置-查询实验室喇叭列表
export function iotBigViewDeviceFindByType(data = {}) {
  return request({
    url: '/iot/bigView/device/findByType',
    method: 'post',
    data
  })
}
//应急处置-结束预案
export function laboratoryPlanCloseRiskPlan(params) {
  return request({
    url: '/laboratory/plan/closeRiskPlan',
    method: 'get',
    params
  })
}
//应急处置-结束疏散
export function laboratoryExitLineEndEvacuation(data = {}) {
  return request({
    url: '/laboratory/exitLine/endEvacuation',
    method: 'post',
    data
  })
}
//应急处置-开灯
export function laboratoryExitRelayOpenLight(data = {}) {
  return request({
    url: '/laboratory/exitRelay/openLight',
    method: 'post',
    data
  })
}
//应急处置-关灯
export function laboratoryExitRelayCloseLight(data = {}) {
  return request({
    url: '/laboratory/exitRelay/closeLight',
    method: 'post',
    data
  })
}
//应急处置-执行疏散
export function laboratoryExitLineExecuteEvacuation(data = {}) {
  return request({
    url: '/laboratory/exitLine/executeEvacuation',
    method: 'post',
    data
  })
}
//应急处置-喇叭播放文本
export function iotBigViewSpeakerPlayText(params) {
  return request({
    url: '/iot/bigView/speaker/playText',
    method: 'get',
    params
  })
}
//查询视频配置
export function laboratoryLabScreenScreenConfigGet(params) {
  return request({
    url: '/laboratory/labScreen/screenConfig/get',
    method: 'get',
    params
  })
}
//查询视频配置
export function iotDeviceList(data = {}) {
  return request({
    url: '/iot/device/listPage',
    method: 'post',
    data
  })
}
