var pageSys = {

}


function renderIsOpen(data, type, row) { return data == 1 ? "启用" : "禁用" }

var roleTypeDef = {} // = { 1: "角色1", 2: "角色2" } // 调用接口查询获取角色定义
function renderRole(data, type, row) {
  var text = roleTypeDef[data]
  return text != undefined ? text : ''
}

// 需要调用接口查询获取策略类型定义
var policyTypeDef = { 1: "发电策略", 2: "储能策略", 3: "充电策略" }
function renderPolicy(data, type, row) {
  var text = policyTypeDef[data]
  return text != undefined ? text : ''
}

var deviceTypeDef = {
  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 renderDeviceType(data, type, row) {
  var text = deviceTypeDef[data]
  return text != undefined ? text : ''
}

var priceTypeDef = {
  1: "充电计费"
}
function renderPriceType(data, type, row) {
  var text = priceTypeDef[data]
  return text != undefined ? text : ''
}

var syslogTypeDef = {
  0: "其它",
  1: "系统日志",
  2: "操作员日志",
  3: "设备日志",
  4: "告警日志",
}
function renderSyslogType(data, type, row) {
  var text = syslogTypeDef[data]
  return text != undefined ? text : ''
}

var tableDef = {
  user: {
    table: null,
    columns: [
      { title: '用户ID', width: '80px' },
      { title: '用户名', width: '150px' },
      { title: '姓名' },
      { title: '性别', render: function (data, type, row) { return data == 1 ? "男" : "女" } },
      { title: '年龄' },
      { title: '手机号' },
      { title: '邮箱' },
      { title: '角色', render: renderRole },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      { title: '上次登录时间', width: '180px' },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptDel },
      },
    ],
    header: ['user_id', 'account', 'name', 'gender', 'age', 'phone', 'email', 'is_open', 'login_time', 'role_id'],
    query: G.cppNative.queryUserList,
    update: G.cppNative.updateUser,
    insert: G.cppNative.insertUser,
    poptitle: "人员",
    popkeys: ['', 'account', 'name', 'gender', 'age', 'phone', 'email', 'is_open', '', 'role_id'],
  },

  role: {
    table: null,
    columns: [
      { title: '角色ID', width: '80px' },
      { title: '角色名称', width: '150px' },
      { title: '角色描述' },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptDel },
      },
    ],
    header: ['role_id', 'name', 'describe', 'is_open', 'create_time', 'update_time', 'update_by'],
    query: G.cppNative.queryRoleList,
    update: G.cppNative.updateRole,
    insert: G.cppNative.insertRole,
    poptitle: "角色",
    popkeys: ['', 'name', 'describe', 'is_open', 'permission'],
  },

  permission: {
    table: null,
    columns: [
      { title: '权限ID', width: '80px' },
      { title: '权限名称', width: '150px' },
      { title: '权限描述' },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptDel },
      },
    ],
    header: ['permission_id', 'name', 'describe', 'is_open', 'create_time', 'update_time', 'update_by'],
    query: G.cppNative.queryPermissionList,
    update: G.cppNative.updatePermission,
    insert: G.cppNative.insertPermission,
    poptitle: "权限",
    popkeys: ['', 'name', 'describe', 'is_open'],
  },

  device: {
    table: null,
    columns: [
      { title: '设备ID', width: '80px' },
      { title: '所属场站', width: '120px' },
      { title: '设备类型', width: '120px', render: renderDeviceType },
      { title: '设备名称', width: '120px' },
      { title: '设备编号' },
      { title: '设备型号' },
      { title: '厂家信息' },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      { title: '属性参数', width: '180px' },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptAttrs },
      },
    ],
    header: ['device_id', 'type', 'name', 'code', 'model', 'factory', 'is_open', 'create_time', 'update_time', 'attrs'],
    query: G.cppNative.queryDeviceList,
    update: G.cppNative.updateDevice,
    insert: G.cppNative.insertDevice,
    poptitle: "设备",
    popkeys: ['', 'type', 'name', 'code', 'model', 'factory', 'is_open'],
  },

  price: {
    table: null,
    columns: [
      { title: 'ID', width: '80px' },
      { title: '类型', width: '120px', render: renderPriceType },
      { title: '名称', width: '150px' },
      { title: '描述' },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      { title: '创建时间', width: '180px' },
      { title: '更新时间', width: '180px' },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptDel },
      },
    ],
    header: ['price_id', 'type', 'name', 'describe', 'is_open', 'create_time', 'update_time'],
    query: G.cppNative.queryPriceList,
    update: G.cppNative.updatePrice,
    insert: G.cppNative.insertPrice,
    poptitle: "计费",
    popkeys: ['', 'type', 'name', 'describe', 'is_open'],
  },

  policy: {
    table: null,
    columns: [
      { title: '策略ID', width: '80px' },
      { title: '策略名称', width: '150px' },
      { title: '策略类型', render: renderPolicy },
      { title: '策略描述', width: '120px' },
      { title: '策略参数', width: '180px' },
      { title: '是否启用', width: '120px', render: renderIsOpen },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptDel },
      },
    ],
    header: ['policy_id', 'name', 'type', 'value', 'describe', 'is_open', 'create_time', 'update_time'],
    query: G.cppNative.queryPolicyList,
    update: G.cppNative.updatePolicy,
    insert: G.cppNative.insertPolicy,
    poptitle: "策略",
    popkeys: ['', 'name', 'type', 'value', 'describe', 'is_open'],
  },

  syslog: {
    table: null,
    columns: [
      { title: '日志ID', width: '80px' },
      { title: '日志类型', width: '100px', render: renderSyslogType },
      { title: '操作用户', width: '120px' },
      { title: '日志内容', },
      { title: '创建时间', width: '180px' },
      { title: '日志状态', width: '180px' }
    ],
    header: ['log_id', 'type', 'user_id', 'user_acount', 'content', 'create_time'],
    query: G.cppNative.querySyslogList,
  },
  alertlog: {
    table: null,
    columns: [
      { title: 'ID', width: '80px' },
      { title: '类型', width: '100px', render: renderSyslogType },
      { title: '设备类型', width: '120px' },
      { title: '设备ID', width: '120px' },
      { title: '错误码', width: '120px' },
      { title: '错误描述', width: '120px' },
      { title: '告警状态', width: '120px' },
      { title: '告警时间', width: '120px' },
      { title: '处理人员', width: '120px' },
      { title: '处理方式', width: '120px' },
      { title: '处理时间', width: '120px' }
    ],
    header: ['log_id', 'type', 'user_id', 'user_acount', 'content', 'create_time'],
    query: G.cppNative.querySyslogList,
  },
  station: {
    table: null,
    columns: [
      { title: 'ID', width: '80px' },
      { title: '场站名称', width: '100px' },
      { title: '场站位置', width: '120px' },
      { title: '场站经度', width: '120px' },
      { title: '场站纬度', width: '120px' },
      { title: '场站电话', width: '120px' },
      { title: '场站状态', width: '120px' },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptAttrs },
      },
    ],
  },
  apiservice: {
    table: null,
    columns: [
      { title: '接口ID', width: '80px' },
      { title: '接口名称', width: '100px' },
      { title: '接口描述', width: '120px' },
      { title: '接口参数', width: '120px' },
      { title: '接口状态', width: '120px' },
      {
        title: '操作',
        width: '200px',
        render: function (data, type, row) { return htmlOptEdit + htmlOptAttrs },
      },
    ],
  },

}

var htmlOptEdit = '<button class="btn btn-primary btn-sm" style="width:80px; height:28px;" id="btnRowEdit">编辑</button>'
var htmlOptDel = '' //'<button class="btn btn-outline-danger btn-sm" style="width:80px; margin-left:8px;" id="btnRowDel">删除</button>'
var htmlOptAttrs = '<button class="btn btn-primary btn-sm" style="width:80px; height:28px; margin-left:8px;" id="btnRowAttrs">属性设置</button>'

var popRowdata = null

// 初始化页面和表格的基础数据
async function initSubpage(id) {
  G.clickSubpageBtn(id)

  if (id == 'user') {
    // 查询获取角色列表，初始化下拉表单和表格角色id的映射
    var elementSelectRole = document.getElementById('userForm_role_id')
    elementSelectRole.innerHTML = ''
    await G.cppNative.queryRoleList(0, 0).then(res => {
      res.data.forEach(item => {
        elementSelectRole.options.add(new Option(item.name, item.role_id))
        roleTypeDef[item.role_id] = item.name
      })
    })
  }
  else if (id == 'role') { }
  else if (id == 'price') {
    var elementSelectPriceType = document.getElementById('priceForm_type')
    elementSelectPriceType.innerHTML = ''
    G.cppNative.queryPriceTypeList().then(res => {
      res.forEach(item => { elementSelectPriceType.options.add(new Option(item.name, item.id)) })
    })
  }
  else if (id == 'policy') {
    var elementSelectPolicyType = document.getElementById('policyForm_type')
    elementSelectPolicyType.innerHTML = ''
    for (var k in policyTypeDef) { elementSelectPolicyType.options.add(new Option(policyTypeDef[k], k)) }
  }

  var tableInfo = tableDef[id]
  // 表格已经初始化，重新加载数据
  if (tableInfo.table) {
    tableInfo.table.ajax.reload()
    return
  }

  // 初始化表格
  G.initTable(id, tableInfo)
  // 初始化弹窗Form
  G.initForm(id, popConfirm)
  if (id == 'device') { G.initForm("deviceAttr", popConfirm) }

  // 绑定行编辑
  tableInfo.table.on('click', '#btnRowEdit', function () {
    var row = tableInfo.table.row($(this).closest('tr'))
    showPop(id, row.data())
  })

  tableInfo.table.on('click', '#btnRowAttrs', function () {
    var row = tableInfo.table.row($(this).closest('tr'))
    showPopDeviceAttr(row.data())
  })
}


function showPop(id, rowData) {
  popRowdata = (rowData && rowData.length > 0) ? rowData : null
  var isEdit = (popRowdata) ? true : false

  G.showElement(id + 'Pop', true)
  document.getElementById(id + 'FormOk').disabled = true

  var tableInfo = tableDef[id]

  // 设置弹框的标题
  $('#' + id + 'PopTitle').text((isEdit ? '编辑' : '新增') + tableInfo.poptitle)
  // 设置弹框的参数信息
  G.popSetParams(id, tableInfo.popkeys, popRowdata, callbackPopSetParams)

  if (id == 'user') { G.popSetParamReadonly('user', 'account', isEdit) }
}

var deviceAttrKeyDef = { commType: "通讯方式", ip: "通讯地址", port: "通讯端口", isclient: "客户端" }

// 显示设备的属性编辑弹窗，属性字段格式为JSON: attrs="{}"
function showPopDeviceAttr(rowData) {
  G.showElement('deviceAttrPop', true)

  popRowdata = (rowData && rowData.length > 0) ? rowData : null

  var device_id = rowData[0]
  var deviceType = rowData[1]
  var deviceTypeStr = deviceTypeDef[deviceType]
  var attrsStr = rowData[9]

  var attrs = {}
  try { attrs = JSON.parse(attrsStr); } catch (error) { attrs = {} }
  if (Object.keys(attrs).length == 0) { attrs = { commType: "", ip: "", port: 0, isclient: 1 } }

  var elemtForm = document.getElementById('deviceAttrForm')
  elemtForm.innerHTML =
    `<div class="input-group mb-3">
      <span class="input-group-text" style="width: 90px; background-color: #a6c0da">ID</span>
      <input type="text" class="form-control" value='${device_id}' disabled />
    </div>
    <div class="input-group mb-3">
      <span class="input-group-text" style="width: 90px; background-color: #a6c0da">设备类型</span>
      <input type="text" class="form-control" value='${deviceTypeStr}' disabled />
    </div>
    `
  for (k in attrs) {
    var title = deviceAttrKeyDef[k]
    var v = attrs[k]
    if (k == "commType") {

      var optionStr = ('<option ' + (v == "TCP" ? 'selected ' : '') + 'value="TCP">TCP</option>')
        + ('<option ' + (v == "MODBUS" ? 'selected ' : '') + 'value="MODBUS">MODBUS</option>')
        + ('<option ' + (v == "SDK" ? 'selected ' : '') + 'value="SDK">SDK</option>')
        + ('<option ' + (v == "ACTIVEX" ? 'selected ' : '') + 'value="ACTIVEX">ACTIVEX</option>')

      elemtForm.innerHTML +=
        `<div class="input-group mb-3">
          <span class="input-group-text" style="width: 90px; background-color: #a6c0da">${title}</span>
          <select id="${k}" class="form-select" required>
            ${optionStr}
          </select>
        </div>
        `
    } else {
      elemtForm.innerHTML +=
        `<div class="input-group mb-3">
          <span class="input-group-text" style="width: 90px; background-color: #a6c0da">${title}</span>
          <input id="${k}" type="text" class="form-control" value='${v}' />
        </div>
        `
    }
  }

  G.cppNative.log(elemtForm.innerHTML);
}

function showPrompt(text, status) {
  G.showElement('promptPop', true)
  var promptText = $('#promptText')
  promptText.text(text)
  promptText.css('color', status == 0 ? 'green' : 'red')
}
function hidePrompt() {
  G.showElement('promptPop', false)
}

function callbackPopSetParams(id, key, val) {
  if (key == 'permission') {
    var elementFormPermission = document.getElementById('roleForm_permission')
    elementFormPermission.innerHTML = ""

    if (popRowdata) {
      var roleId = popRowdata[0]
      // 查询权限列表， 更新编辑弹框的权限列表显示内容
      G.cppNative.queryRolePermissionList(roleId).then(res => {
        res.forEach(item => {
          // <li><input class="form-check-input" type="checkbox" value="" />系统总览-查看</li>
          var elemHtml = '<li><input class="form-check-input" type="checkbox" value="' + item.permission_id + '" ' +
            (item.is_open == '1' ? 'checked' : '') + '/>' + item.name + '</li>'
          elementFormPermission.innerHTML += elemHtml
        })
      })
    } else {
      G.cppNative.queryPermissionList(0, 0).then(res => {
        res.data.forEach(item => {
          var elemHtml = '<li><input class="form-check-input" type="checkbox" value="' + item.permission_id + '" ' +
            (item.is_open == '1') + '/>' + item.name + '</li>'
          elementFormPermission.innerHTML += elemHtml
        })
      })
    }
    // 不需要设置参数值
    return undefined
  }
  else {
    return val
  }
}

function callbackPopGetParams(id, key) {
  var val = undefined
  if (key == 'permission') {
    val = []
    var elemtFormPermission = document.getElementById('roleForm_permission')
    var elemtPermissionList = elemtFormPermission.querySelectorAll('input')
    elemtPermissionList.forEach((elemt => { val.push({ permission_id: elemt.value, is_open: (elemt.checked ? 1 : 0) }) }))
  }
  return val
}

function updateTableData(id) {
  var info = tableDef[id]
  var queryFunc = info.query
  if (!queryFunc) return

  queryFunc(1, 10).then((res) => {
  })
}

// 用户弹窗确认
function popConfirm(id) {
  // 设备属性弹窗： 读取属性配置
  if (id == "deviceAttr") {
    /// 选择所有表单元素(input, select, textarea) $('#parentElement :input')
    /// :input 是jQuery特有的选择器，可以匹配所有input、select、textarea和button元素。
    /// 同时选择input和select元素 $('#parentElement input, #parentElement select')
    var param = {}
    $("#deviceAttrForm :input").each(function () {
      var id = $(this).attr('id'); // 获取id属性
      var val = $(this).val();   // 获取value值
      if ((id == "port" || id == "isclient")) { param[id] = parseInt(val) }
      else if (id == "commType") { }
      else if (id) { param[id] = val }
    });
    G.cppNative.log(JSON.stringify(param))

    // 存储更新数据
    G.cppNative.log("rowdata: " + JSON.stringify(popRowdata))
    var dataId = popRowdata[0]
    G.cppNative.updateDevice(dataId, { attrs: JSON.stringify(param) }).then(ret => {
      G.showElement('deviceAttrPop', false)
      showPrompt((ret == 0 ? '操作成功!' : '操作失败!'), ret)
    })
    return;
  }

  // 获取数据表格操作对象
  var mytable = $('#' + id + 'Table').DataTable()
  // 获取弹框的参数信息
  var tableInfo = tableDef[id]
  G.cppNative.log(id + " edit: rowdata=" + JSON.stringify(popRowdata))
  var params = G.popGetParams(id, tableInfo.popkeys, popRowdata, callbackPopGetParams)
  if (Object.keys(params).length == 0) {
    G.showElement(id + 'Pop', false)
    return
  }

  var isEdit = popRowdata ? true : false
  if (isEdit) {
    var msg = '编辑' + tableInfo.poptitle
    var dataId = popRowdata[0]
    tableInfo.update(dataId, params).then(ret => {
      if (ret == 0 && id == "role" && params.permission.length > 0) {
        G.cppNative.updateRolePermission(dataId, params.permission).then(ret => {
          G.showElement(id + 'Pop', false)
          showPrompt(msg + (ret == 0 ? '操作成功!' : '操作失败!'), ret)
          mytable.ajax.reload()
        })
      } else {
        G.showElement(id + 'Pop', false)
        showPrompt(msg + (ret == 0 ? '操作成功!' : '操作失败!'), ret)
        mytable.ajax.reload()
      }
    })
  } else {
    var msg = '新增' + tableInfo.poptitle
    tableInfo.insert(params).then(ret => {
      G.showElement(id + 'Pop', false)
      showPrompt(msg + (ret == 0 ? '操作成功!' : '操作失败!'), ret)
      mytable.ajax.reload()
    })
  }
}

// 设置设备类型下拉列表
var elementSelectDeviceType = document.getElementById('deviceForm_type')
elementSelectDeviceType.innerHTML = ''
for (k in deviceTypeDef) {
  elementSelectDeviceType.options.add(new Option(deviceTypeDef[k], k))
}

$(document).ready(function () {
  initSubpage('user')
  //G.initTable('user', tableDef['user'])
})
