var G = {
  user: { username: '' },

  loadPage: function (pagename) {
    while (1) {
      var script = document.querySelector("script[id='mytempfile']")
      if (!script) break
      script.remove()
    }
    var file = 'assets/html/pages/' + pagename + '.html'
    G.cppNative.readFile(file).then(function (text) {
      // 加载 html 页面内容文件
      document.getElementById('mypage').innerHTML = text
      // 加载 js 脚本文件
      var jsUrl = './pages/' + pagename + '.js'
      var element = document.createElement('script')
      element.src = jsUrl + '?t=' + new Date().getTime()
      element.async = false // 脚本按照加载先后顺序处理
      element.setAttribute('id', 'mytempfile')
      document.body.appendChild(element)
    })
  },

  switchSetStatus: function (id1, id2, checked, callback) {
    document.getElementById(id2).checked = !(document.getElementById(id1).checked = checked)
    if (callback) callback(checked)
  },
  switchGetStatus: function (id) { return document.getElementById(id).checked },

  initTable: function (id, info) {
    if (info.table) {
      info.table.ajax.reload()
      return;
    }
    var tableOption = G.tableGetOption()
    tableOption.columns = info.columns
    tableOption.ajax = function (req, callback, settings) {
      G.cppNative.log('lxy=== table ajax start')
      if (info.query) {
        info.query(1, 10).then(res => {
          var result = []
          res.data.forEach(function (item, index) {
            var rowData = []
            info.header.forEach(function (key, index) { rowData.push(item[key]) })
            result.push(rowData)
          })
          G.cppNative.log("table ajax: " + JSON.stringify(result))
          callback({ draw: req.draw, recordsTotal: result.length, recordsFiltered: result.length, data: result })
        })
      } else {
        callback({ draw: req.draw, recordsTotal: 0, recordsFiltered: 0, data: [] })
      }
    }
    // 初始化表格
    info.table = $('#' + id + 'Table').DataTable(tableOption)
    G.cppNative.log('lxy=== table init end')
    //$('div.gotopage').html('<b style="color:#7f8fa4">跳转至 </b><input id="searchNumber" style="width:80px"/><b style="color:#7f8fa4;"> 页</b>')
  },

  updateTableData: function (queryFunc, params) {
    if (queryFunc) {
    }
  },

  cppCall: function (id) {
    var cppfunc = G.cppNative[id]
    if (cppfunc) {
      G.cppNative.log('call cpp function [' + id + ']')
      cppfunc()
    } else {
      G.cppNative.log('call cpp function [' + id + '] error: not exist')
    }
  },

  cppSignal: function (id, callback) {
    var signal = G.cppNative[id]
    if (signal) {
      G.cppNative.log('cpp signal [' + id + '] ')
      signal.connect(callback)
    } else {
      G.cppNative.log('cpp signal [' + id + '] error: not exist')
    }
  },

  initForm: function (id, funcPopConfirm) {
    var form = document.getElementById(id + 'Form')
    var formBtnOk = document.getElementById(id + 'FormOk')
    if (form && formBtnOk) {
      // 监听表单的输入事件，检查表单的必填项是否完成输入，如果未完成，则确认按钮不可用
      form.addEventListener('input', function () { formBtnOk.disabled = !form.checkValidity() })
      // 编辑弹窗的确定按钮监听点击事件
      formBtnOk.addEventListener('click', function () { if (funcPopConfirm) { funcPopConfirm(id) } })
    }
  },

  showElement: function (id, visible) {
    var elemt = document.getElementById(id)
    if (elemt) { elemt.style.display = visible ? 'block' : 'none' }
  },

  popSetParams: function (id, keys, rowdata, callback) {
    keys.forEach(function (key, index) {
      var val = ''
      if (rowdata && rowdata.length > index) { val = rowdata[index] }

      if (key == 'is_open') {
        G.switchSetStatus(id + 'Form_on', id + 'Form_off', parseInt(val))
      } else {
        var myval = (callback) ? callback(id, key, val) : val
        // 回调函数返回 undefined 时， 不需要设置参数值
        if (myval != undefined) {
          val = myval
          var element = $('#' + id + 'Form_' + key)
          if (element) {
            if (element.prop("tagName") == "SELECT" && val == '') {
              element.get(0).selectedIndex = 0;
            } else {
              element.val(val)
            }
          }
        }
      }
    })
  },

  popGetParams: function (id, keys, rowdata, callback) {
    var params = {}
    keys.forEach(function (key, index) {
      var val
      if (key == 'is_open') {
        val = G.switchGetStatus(id + 'Form_on') ? '1' : '0'
      } else {
        var myval = callback ? callback(id, key) : undefined
        val = myval != undefined ? myval : $('#' + id + 'Form_' + key).val()
      }
      if (rowdata) {
        if (rowdata.length > index && val != rowdata[index]) { params[key] = val }
      } else {
        if (val != '') { params[key] = val }
      }
    })
    G.cppNative.log('POP get params： id=' + id + ', params=' + JSON.stringify(params))
    return params
  },

  popSetParamReadonly: function (id, key, isReadonly) {
    $('#' + id + 'Form_' + key).attr('readonly', isReadonly)
  },

  tableGetOption: function () {
    return {
      data: [],
      columns: [],
      bSort: false,
      scollY: "600px",
      //aLengthMenu: [10, 20, 50, 100], //设置每页显示数据条数的下拉选项
      //displayLength: 5, //每页初始显示最大记录数量
      // 设置：表格（t）、分页数据条数（l）、搜索框（f）、表格信息（i）、分页（p）、加载信息（r）
      dom: 'rt<"mydt-ext"p<"item"<"gotopage">><"item"i><"item"f>>',
      language: {
        emptyTable: '无数据',
        lengthMenu: '每页显示 _MENU_ 条记录',
        zeroRecords: '对不起，查询不到任何相关数据',
        info: '共有 _TOTAL_ 条记录', // '当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录',
        infoEmpty: '共 0 页',
        infoFiltered: '数据表中共为 _MAX_ 条记录)',
        processing: '正在加载中...',
        search: '结果中搜索',
        paginate: {
          previous: '上一页', next: '下一页', first: '首页', last: '尾页'
        },
      },
      columnDefs: [{ targets: '_all', className: 'dt-head-left' }, { targets: '_all', className: 'dt-body-left' }],
      //serverSide: true,
      processing: false,
      ajax: function (req, callback, settings) {
        // 查询服务器获取数据， 同时获取总数据条数
        callback({ draw: req.draw, recordsTotal: 0, recordsFiltered: 0, data: [] })
      },

      createdRow: function (row, data, dataIndex) {
        if (dataIndex % 2 === 0) {
          //$(row).css('background-color', '#ff000010')
        } else {
          //$(row).css('background-color', '#00ff0010')
        }

        $(row).on('mouseenter', function () {
          //if (curEditRow && myTableApi.row(curEditRow).index() == myTableApi.row($(this)).index()) return
          $(this).css('background-color', '#ff808050') // 高亮颜色
        })
        $(row).on('mouseleave', function () {
          //if (curEditRow && myTableApi.row(curEditRow).index() == myTableApi.row($(this)).index()) return
          $(this).css('background-color', '') // 恢复默认
        })
      },
    }
  },

  clickSubpageBtn: function (id) {
    if (G.curSubpageId == id) return

    if (G.curSubpageId) {
      var oldBtn = document.getElementById(G.curSubpageId + 'Btn')
      if (oldBtn) { oldBtn.className = 'btn btn-primary' }
      var oldSubpage = $('#' + G.curSubpageId)
      if (oldSubpage) { oldSubpage.hide() }
    }
    if (id) {
      var curBtn = document.getElementById(id + 'Btn')
      if (curBtn) { curBtn.className = 'btn btn-success btn-lg' }
      var curSubpage = $('#' + id)
      if (curSubpage) { curSubpage.show() }
    }

    G.curSubpageId = id
  },


  getRandDataDay: function (a, b, n) {
    var data = []
    var t0 = Date.parse('2025-07-01 00:00:00')
    if (!n) { n = 24 }
    var step = 86400 / n
    var y = a;
    for (var i = 0; i < n; ++i) {
      // data[i] = { x: t0 + i * step * 1000, y: Math.sin(i * 0.1) * (n - m) }
      var x = t0 + i * step * 1000
      y = Math.floor((y + RAND(0, 50) - 25) * 100) / 100
      data[i] = { name: x, value: [x, y] }
    }
    return data
  },


  // 格式化日期为YYYY-MM-DD
  formatDateMD: function (date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    //return `${year}-${month}-${day}`;
    return `${month}-${day}`;
  },

  alertMessage: function (type, message) {
    const wrapper = document.createElement('div')
    wrapper.innerHTML = [
      `<div class="alert alert-${type} alert-dismissible" role="alert">`,
      `   <div>${message}</div>`,
      '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
      '</div>'
    ].join('')

    const elemtParent = document.getElementById('alertBox')
    if (elemtParent) { elemtParent.append(wrapper); }
  },

  dateStr() {
    const now = new Date();
    var dtStr = now.toLocaleString('zh-CN',
      {
        hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'
      }).replace(/\//g, '-')
    return dtStr
  }
}

function RAND(a, b) {
  return a + Math.random() * (b - a)
}