local uci = require "luci.model.uci".cursor()
local sys = require "luci.sys"

m = Map("imei_cell_locker", _("锁频锁小区"), _("在此页面可以锁定频率和小区"))

local band_value = uci:get("imei_cell_locker", "lockcell", "band") or ""
local freq_value = uci:get("imei_cell_locker", "lockcell", "freq") or ""
local cellid_value = uci:get("imei_cell_locker", "lockcell", "cellid") or ""
local tac_value = uci:get("imei_cell_locker", "lockcell", "tac") or ""

s = m:section(TypedSection, "lockcell", _("锁定频率和小区"))
s.addremove = false
s.anonymous = true

band = s:option(Value, "band", _("频段 (Band)"))
band.datatype = "string"
band.default = band_value

freq = s:option(Value, "freq", _("频率 (Frequency)"))
freq.datatype = "uinteger"
freq.default = freq_value

cellid = s:option(Value, "cellid", _("小区 ID (Cell ID)"))
cellid.datatype = "uinteger"
cellid.default = cellid_value

tac = s:option(Value, "tac", _("跟踪区编码 (TAC)"))
tac.datatype = "uinteger"
tac.default = tac_value

-- 添加应用按钮
apply = s:option(Button, "_apply", _("应用锁定"))
apply.inputtitle = _("应用")
apply.inputstyle = "apply"

function apply.write(self, section)
    local new_band = band:formvalue(section)
    local new_freq = freq:formvalue(section)
    local new_cellid = cellid:formvalue(section)
    local new_tac = tac:formvalue(section)

    if new_band and new_freq and new_cellid and new_tac then
        -- 保存新的小区和频率锁定信息
        uci:set("imei_cell_locker", "lockcell", "band", new_band)
        uci:set("imei_cell_locker", "lockcell", "freq", new_freq)
        uci:set("imei_cell_locker", "lockcell", "cellid", new_cellid)
        uci:set("imei_cell_locker", "lockcell", "tac", new_tac)
        uci:commit("imei_cell_locker")

        -- 使用 AT 指令锁定频率和小区
        sys.call("sendat 2 'AT+QNWLOCK=\"1\",5,%s,%s,%s,%s'" % { new_band, new_freq, new_cellid, new_tac })
    end
end

return m
