var mapDeviceTypeDef = new Map([
  ['1', '变压器'],
  ['2', '配电柜'],
  ['3', '电表'],
  ['4', '门禁'],
  ['5', '空调'],
  ['6', '照明'],
  ['7', '消防'],
  ['8', '光照监测设备'],
  ['9', '风速监测设备'],
  ['10', '温湿度监测设备'],
  ['11', '烟感监测设备'],
  ['12', '水浸传感器'],
  ['13', '视频监控'],
  ['101', '逆变器'],
  ['102', '汇流箱'],
  ['103', '光伏板'],
  ['104', '风力发电机'],
  ['105', '储能变流器'],
  ['106', '储能电池'],
  ['107', 'BMS'],
  ['108', '充电桩'],
  ['109', '充电枪'],
  ['110', '集中器'],
])

function getDeviceTypeId(name) {
  var res = ''
  mapDeviceTypeDef.forEach((v, k) => { if (v == name) { res = k } })
  return res;
}
function getDeviceTypeName(id) {
  var res = ''
  mapDeviceTypeDef.forEach((v, k) => { if (k == id) { res = v } })
  return res;
}

function addDeviceCardPanel(root, deviceid, name, type, subList) {
  var card = document.createElement('div')
  card.className = 'mycard'
  card.setAttribute('id', deviceid) // 设置id
  if (type == "充电桩") { card.style.width = '320px' }
  card.innerHTML =
    `<div class="myrow" style="margin-bottom: 20px">
      <div style="width:64px; height:64px; background-color: #2991b6;border-radius: 10px;"></div>
      <div class="mycol" style="margin-left: 10px; font-size:15px;">
        <div> ${deviceid} </div>
        <div style="font-size:15px;"> ${name} </div>
        <div style="color: #08afff; font-size:14px; font-weight: bold;"> ${type} </div>
      </div>
    </div>`

  // 充电桩区分1号枪和2号枪
  if (subList && subList.length > 1) {
    card.innerHTML +=
      `<div class="myrow">
        <div id="${deviceid}_${subList[0]}" style="width: calc(50% - 10px); border: solid gray; border-width: 0 1px 0 0;">
          <div class="myrow" style="font-size:14px; margin-left: 10px;">
            <div style="background-color:#00dbd7; width: 5px; height:18px; "></div>
            <div style="margin-left: 10px;">#${subList[0]}</div>
          </div>
        </div>
        <div id="${deviceid}_${subList[1]}" style="width: calc(50% - 10px); margin-left: 10px;">
          <div class="myrow" style="font-size:14px; margin-left: 10px;">
            <div style="background-color:#00dbd7; width: 5px; height:18px; "></div>
            <div style="margin-left: 10px;">#${subList[1]}</div>
          </div>
        </div>
      </div>`
  }
  root.appendChild(card)
  return card
}

/// =========================================================== 
// 创建设备卡片的参数信息
// @param deviceid: 设备 ID
// @param subid: 参数子分类 ID，如充电桩的充电枪的编号：1号枪，2号枪
// @param key: 参数名称
// @param key: 参数值
// 说明： 每个参数值的 element 的 id 设置为：{deviceid}_{subid}_{key}
function addDeviceCardParam(deviceid, subid, key, text) {
  var elemtid = deviceid + (subid ? ("_" + subid) : "") + "_" + key
  param = document.createElement('div')
  param.className = 'mycard-param'
  param.innerHTML = `<div class="mycard-param-key">${key}: </div>
    <div id="${elemtid}" class="mycard-param-text">${text}</div>`

  if (subid) {
    $('#' + deviceid + '_' + subid).append(param)
  } else {
    $('#' + deviceid).append(param)
  }
  if (text == '离线' | text == '故障') {
    $("#" + elemtid).css("color", "red")
  }
}

/// =========================================================== 
// 设置设备卡片的参数值
// @param deviceid: 设备ID
// @param subid: 参数子分类ID，如充电桩的充电枪的编号：1号枪，2号枪
// @param key: 参数名称
// @param key: 参数值
// 说明： 每个参数值的 element 的 id 设置为：{deviceid}_{subid}_{key}
function setDeviceCardParam(deviceid, subid, key, text) {
  var elemtid = deviceid + (subid ? ("_" + subid) : "") + "_" + key
  $("#" + elemtid).text(text);
  // 特殊状态设置颜色区分显示
  if (text == '离线' | text == '故障') {
    $("#" + elemtid).css("color", "red")
  }
}

var activeCardBtn = null
var activeModuleId = null

function onClickCardBtn(btn, id) {
  if (activeCardBtn) activeCardBtn.className = 'mycardbtn'
  activeCardBtn = btn
  activeCardBtn.className = 'mycardbtn-active'
  activeModuleId = id
  initDeviceList(activeModuleId)
}

function creatElementSwitch(id, x, y) {
  var eswitch = document.createElement('div')
  eswitch.className = 'btn-group'
  eswitch.setAttribute('style', `margin-left: 5px; width: 60px; height: 26px; position:absolute; left: ${x}px; top: ${y}px`);
  eswitch.innerHTML = `
        <input id="${id}_off" type="checkbox" class="btn-check"
          onclick="G.switchSetStatus('${id}_on', '${id}_off', !this.checked)" checked />
        <label class="btn btn-outline-danger" for="${id}_off" style="padding: 0;">关</label>
        <input id="${id}_on" type="checkbox" class="btn-check"
          onclick="G.switchSetStatus('${id}_on', '${id}_off', this.checked)" />
        <label class="btn btn-outline-success" for="${id}_on" style="padding: 0;">开</label>`
  return eswitch;
}

function creatElementCard() {
  var card = document.createElement('div')
  card.className = 'mycard'
  return card;
}

function createCardVideo(name) {
  var elemt = document.createElement('div')
  elemt.className = 'mycard'
  elemt.style.width = '320px'
  elemt.innerHTML = `
    <div>${name}</div>
    <div style='width=90%; height:84%; margin-top:10px; border: 5px solid black;'> 
    <div style='width:100%; height:100%; line-height:200px; text-align: center; background-color: gray'> 无信号</div>
    </div>`
  return elemt;
}


function initDeviceList(deviceType) {
  var elemtDeviceList = document.getElementById('deviceList')
  elemtDeviceList.innerHTML = ''

  var subList = [null]
  if (deviceType === 'security') {
    document.getElementById('envpanel').style.display = 'block'

    elemtDeviceList.appendChild(createCardVideo('监控点1'))
    elemtDeviceList.appendChild(createCardVideo('监控点2'))
    elemtDeviceList.appendChild(createCardVideo('监控点3'))
    elemtDeviceList.appendChild(createCardVideo('监控点4'))
    elemtDeviceList.appendChild(createCardVideo('监控点5'))
    elemtDeviceList.appendChild(createCardVideo('监控点6'))
    elemtDeviceList.appendChild(createCardVideo('监控点7'))
    elemtDeviceList.appendChild(createCardVideo('监控点8'))
    elemtDeviceList.appendChild(createCardVideo('监控点9'))
    elemtDeviceList.appendChild(createCardVideo('监控点10'))
    elemtDeviceList.appendChild(createCardVideo('监控点11'))
    elemtDeviceList.appendChild(createCardVideo('监控点12'))
    elemtDeviceList.appendChild(createCardVideo('监控点13'))
    elemtDeviceList.appendChild(createCardVideo('监控点14'))
    elemtDeviceList.appendChild(createCardVideo('监控点15'))
    elemtDeviceList.appendChild(createCardVideo('监控点16'))
    return
  }

  document.getElementById('envpanel').style.display = 'none'

  var reqDeviceType = []
  if (deviceType === 'solar') {
    reqDeviceType = ['101', '102', '103']
  }
  else if (deviceType === 'storage') {
    reqDeviceType = ['101', '102', '106']
  }
  else if (deviceType === 'charge') {
    subList = ['1', '2']
    reqDeviceType = ['108']
  }
  else if (deviceType == 'load') {
    reqDeviceType = []
  }

  // 查询数据库，获取设备信息
  //G.cppNative.queryDevice({ type: reqDeviceType }).then((res) => {
  G.cppNative.getDeviceInfo(reqDeviceType).then((res) => {
    res.forEach(function (item, index) {
      var deviceType = getDeviceTypeName(item.type)
      addDeviceCardPanel(elemtDeviceList, item.device_id, item.name, deviceType, subList)

      var params = {
        在线状态: (item.online == 0) ? '离线' : '在线',
        工作状态: (item.status == 0) ? '空闲' : '运行',
        故障状态: (item.err == 0) ? '正常' : '故障',
        额定功率: '-- kW',
        电压: '-- V',
        电流: '-- A',
        功率: '-- kW',
      }

      if (subList) {
        subList.forEach((subid) => {
          Object.keys(params).forEach((k) => {
            addDeviceCardParam(item.device_id, subid, k, params[k]);
          });
        })
      }
      var elemtPanel = document.getElementById(item.device_id)


      //JSON.stringify(item)
      var paramStr = JSON.stringify(item).replace(/"/g, '"')
      elemtPanel.innerHTML += `<button
        class="btn btn-outline-primary btn-sm"
        style="height:30px; margin: 5px 0 0 10px"
        onclick='onDeviceSetting(${paramStr})'>
        参数设置
        </button>`
    })
  })
}

function onDeviceSetting(param) {
  var deviceType = getDeviceTypeName(param.type)
  $('#popDeviceInfo').text(param.device_id + ":" + deviceType + ":" + param.name)
  G.showElement('deviceSettingPop', true)

  if (deviceType == "逆变器") {

  }
}

function updatePageData() {
  if (activeModuleId == "security") {
    // 查询数据获取环境信息：光照、风速、环境温度、湿度
    G.cppNative.getEnvironmentInfo().then(res => {
      // $('#envIllumination').text(res['illumination'] + ' Lux')
      // $('#envWindspeed').text(res['windspeed'] + ' m/s')
      $('#envTemperture').text(res['temperature'] + '℃')
      $('#envHumidity').text(res['humidity'] + '%')
    })

    // 消防信息
    G.cppNative.getFireInfo().then(res => {
      //res.data.forEach(item => { })
    })

  }
}

// ====================================================================================================
// 【注意】 DOM 元素的移除不会自动清理 JavaScript 运行时创建的资源（如定时器、事件监听器等），这些都需要手动管理
// 开启定时器更新页面数据
var timerId = null
// 【注意】 DOM 元素的移除不会自动清理 JavaScript 运行时创建的资源（如定时器、事件监听器等），这些都需要手动管理
// 监听当前script元素的移除事件，清理定时器
document.currentScript.addEventListener('DOMNodeRemoved', () => {
  G.cppNative.log('DOMNodeRemoved: 运行监控')
  clearInterval(timerId);
});


$(document).ready(function () {
  onClickCardBtn(document.getElementById('solarCardBtn'), 'solar')

  G.cppNative.getDeviceInfo([0]).then((res) => {
    var nums = {
      '103': { num: 0, numIdle: 0, numOffline: 0, numFault: 0 },
      '106': { num: 0, numIdle: 0, numOffline: 0, numFault: 0 },
      '108': { num: 0, numIdle: 0, numOffline: 0, numFault: 0 },
    }
    res.forEach(function (item, index) {
      var deviceType = item.type + ''
      if (nums[deviceType]) {
        nums[deviceType].num += 1
        if (item.status == 0) nums[deviceType].numIdle += 1
        if (item.online == 0) nums[deviceType].numOffline += 1
        if (item.err != 0) nums[deviceType].numFault += 1
      }
    })

    $('#solarDeviceNum').text('光伏板数量: ' + nums['103'].num + '')
    $('#solarIdleNum').text('空闲: ' + nums['103'].numIdle + '')
    $('#solarOfflineNum').text('离线: ' + nums['103'].numOffline + '')
    $('#solarFaultNum').text('故障: ' + nums['103'].numFault + '')

    $('#storageDeviceNum').text('储能电池数量: ' + nums['106'].num + '')
    $('#storageIdleNum').text('空闲: ' + nums['106'].numIdle + '')
    $('#storageOfflineNum').text('离线: ' + nums['106'].numOffline + '')
    $('#storageFaultNum').text('故障: ' + nums['106'].numFault + '')

    $('#chargeDeviceNum').text('充电桩数量: ' + nums['108'].num + '')
    $('#chargeIdleNum').text('空闲: ' + nums['108'].numIdle + '')
    $('#chargeOfflineNum').text('离线: ' + nums['108'].numOffline + '')
    $('#chargeFaultNum').text('故障: ' + nums['108'].numFault + '')

    $('#securityDeviceNum').text('摄像头数量: ' + 16 + '')
    $('#securityIdleNum').text('空闲: ' + 16 + '')
  })

  // 定时更新页面数据
  timerId = setInterval(updatePageData, 1000);
})