-- [{"connect_port":"VINTF_TCP","depth":0,"product_key":"206627059","sn":"21881200000E_PCSALL","template_id":"206627059"}]
require "log"
require "sys"
require "utils"
require "patch"
require "pack"
require "bit"
siganl = require 'posix.signal'
syswait = require 'posix.sys.wait'
unistd = require 'posix.unistd'
mqtt = require "mosquitto"
base64 = require("base64")
dyutils = require("dyutils")
lpack = require("lua_pack")
require "internal_api"
require "lsqlite3"

local config_table = {}

local config_servic_info = {
    TAG_4E22 = 0,
    TAG_4E23 = 0,
    TAG_4E24 = 0,
    TAG_4E25 = 0,
    TAG_4E26 = 0,
    TAG_4E29 = 0,
    TAG_4E3E = 0,
    TAG_4F2F = 0,
    TAG_4F30 = 0,
    TAG_4E63 = 0, -- 充电中
    TAG_4E64 = 0  -- 放电中

}

local config_servic_option = {
    TAG_4E22 = 0,
    TAG_4E23 = 0,
    TAG_4E24 = 0,
    TAG_4E25 = 0,
    TAG_4E26 = 0,
    TAG_4E29 = 0,
    TAG_4E3E = 0,
    TAG_4F2F = 0,
    TAG_4F30 = 0
}

local config_sub_dev = {{
    sn = "_PCS1",
    type = "pcs",
    TAG_4E22 = 0,
    TAG_4E23 = 0,
    TAG_4E24 = 0,
    TAG_4E25 = 0,
    TAG_4E26 = 0,
    TAG_4E29 = 0,
    TAG_4E3E = 0,
    TAG_4F2F = 0,
    TAG_4F30 = 0
}, {
    sn = "_Rack1_1",
    type = "rack",
    TAG_9C82 = 0   --0x0: 静置; 0x1: 放电; 0x2: 充电 0x0: IDle; 0x1: Discharging; 0x2: Charging
}}

local config_serviceup = {{
    iotidentifier = "Read32_40Data",
    identifier = "Read32_40Data1",
    tags = {"TAG_4E22", "TAG_4E23", "TAG_4E24", "TAG_4E25", "TAG_4E26", "TAG_4E29", "TAG_4E3E", "TAG_4F2F", "TAG_4F30"}
}, {
    iotidentifier = "Read32_40Data",
    identifier = "rackxinxi",
    tags = {"TAG_9C82"}
}}

local config_servicedown = {{
    iotidentifier = nil,
    identifier = "Read126_148Data",
    tags = {"TAG_2728"}
}}

local nodes_cfg =
    '[{"connect_port":"MODBUS_TCP","depth":0,"product_key":"206627059","sn":"2188120000E8_PCS1","template_id":"206627059"}]'

local function nodes_show(nodes_cfg)
    local nodejs = cjson.decode(nodes_cfg)
    for i, v in ipairs(nodejs) do
        log.debug(i, v.connect_port, v.sn, v.product_key)
    end
end

local function config_init(nodes_cfg,sn)
    local nodejs = cjson.decode(nodes_cfg)
    config_table.mysn = nodejs[1].sn
    config_table.gwsn = io.getGatewayID()
    config_table.connect_port = nodejs[1].connect_port
    log.info("gwsn:", config_table.gwsn, "mysn:", config_table.mysn)
    config_table.dev = config_sub_dev
    log.info("devnum:", #config_table.dev)
    config_table.upservice = config_serviceup
    config_table.downservice = config_servicedown
    for i, v in ipairs(config_table.dev) do
        v.sn = sn .. v.sn
    end

    for i, v in ipairs(config_table.upservice) do
        log.info("upservice :", i, v.identifier)
        for i = 0, #v.tags do
            print(v.tags[i])
        end
    end

    for i, v in ipairs(config_table.downservice) do
        log.info("downservice :", i, v.identifier)
        for i = 0, #v.tags do
            print(v.tags[i])
        end
    end
end
local chargeFlag = 0
local reportsn  = nil
local function report_process(msg)
    local identifier = nil
    for i, v in ipairs(config_table.upservice) do
        if v.identifier == msg.identifier then
            identifier = v.iotidentifier
            for i = 1, #v.tags do
                for _, dev in ipairs(config_table.dev) do
                    if dev.sn == msg.sn then
                        if dev.type == "pcs" then
                        config_servic_info[v.tags[i]] = dev[v.tags[i]]
                        reportsn = dev.sn
                        end
                    end
                end
            end
        end
    end
    if chargeFlag == 0 then
        config_servic_info["TAG_4E63"] = 0
        config_servic_info["TAG_4E64"] = 0
    elseif chargeFlag == 1 then
        config_servic_info["TAG_4E63"] = 0
        config_servic_info["TAG_4E64"] = 1
    elseif chargeFlag == 2 then
        config_servic_info["TAG_4E63"] = 1
        config_servic_info["TAG_4E64"] = 0
    end
    local msg1 = cjson.encode(config_servic_info)
    log.info("report_iot:", msg1)
    if not reportsn then return end
    internal_api.service_response(config_table.gwsn, reportsn, config_table.connect_port, identifier, msg1,
        msg.mi)
end

local function port2pp(playlad, len)
    local msg = cjson.decode(playlad)
    local flag = 0
    log.info("port2pp:", msg.identifier, msg.sn)
    local data = cjson.decode(msg.tag_node)
    for _, v in ipairs(config_table.upservice) do
        if (v.identifier == msg.identifier) then
            for _, dev in ipairs(config_table.dev) do
                if dev.sn == msg.sn then
                    for i = 0, #v.tags do
                        if data[v.tags[i]] ~= nil then

                            dev[v.tags[i]] = data[v.tags[i]]
                            if dev.type == "rack" then
                                chargeFlag = dev[v.tags[i]]
                            end
                        end
                    end

                    flag = 1
                    break
                end
            end
            break
        end
    end
    if flag == 1 then
        report_process(msg)
    end
end

local function iot2pp(playlad, len)
    local msg = cjson.decode(playlad)
    log.info("port2pp:", msg.identifier)
end

local function on_mqtt_msg(topic, payload)
    if string.find(topic, "data/service") then
        local ret, err = pcall(port2pp, payload, #payload)
        if not ret then
            log.warn("mqtt.recv", err)
        end
    elseif string.find(topic, "data/Set_Rglt") then
        local ret, err = pcall(iot2pp, payload, #payload)
        if not ret then
            log.warn("mqtt.recv", err)
        end
    else

    end
end

local function mqtt_init()
    local subscribe = {}
    local devtopic = {}
    for i, v in ipairs(config_table.dev) do
        for k, vv in ipairs(config_table.upservice) do
            devtopic = string.format("ipc/%s/+/device/%s/data/service/%s", config_table.gwsn, v.sn, vv.identifier)
            table.insert(subscribe, devtopic)
        end
    end
    devtopic = string.format("ipc/%s/+/device/%s/data/Set_Rglt", config_table.gwsn, config_table.mysn)
    table.insert(subscribe, devtopic)
    for i, v in ipairs(subscribe) do
        log.info(i, v)
    end
    internal_api.mqtt_session("localhost", 1883, nil, nil, subscribe, on_mqtt_msg)
end

local function handler()
    local pid, status, code = syswait.wait(-1, syswait.WNOHANG)
    log.error('system exit', pid, status, code) -- 打印不出来
    os.exit(0)
end

local function signal_init()
    siganl.signal(siganl.SIGKILL, handler)
    siganl.signal(siganl.SIGHUP, handler)
end

local function startserver()
    sys.taskInit(function()
        local last_time = 0
        local report_time = 0
        while true do
            sys.wait(1000)
            log.info("--------------####-----")
        end
    end)
    -- 启动系统框架
    sys.init(0, 0)
    sys.run()
end

local function main(nodes_cfg, sn)
    signal_init()
    -- nodes_show(nodes_cfg)
    config_init(nodes_cfg,sn)
    mqtt_init()
    startserver()
end

main(arg[1], arg[2])
-- main(nodes_cfg, "2188120000E8")
