api = freeswitch.API();
local lua_name = argv[0];

local caller_number = session:getVariable("caller_id_number");
local callee_number = session:getVariable("destination_number");
local auuid = session:getVariable("uuid");

-- 默认这个profile进来的呼叫都是长通分机的呼叫
-- sip头域找到实际通话的uuid
local buuid = session:getVariable("sip_h_LCC-ALWAYS-UUID");

if buuid  == nil then
    -- 如果没有获取到，那就尝试在redis上获取一下
    local buuid = api:execute("lcc_hiredis_raw", "default GET base:always:"..callee_number);
    if buuid == "" or string.find(buuid, "ERR") then
        session:consoleLog("ERROR", "[always]"..callee_number..", 分机呼叫不存在.\n");
        session:hangup();
        return;
    end
    local info  = string_split(buuid, "_");
    local buuid = info[1];
    local acd_ip = info[2] or "";
    session:consoleLog("WARNING", "[always]"..callee_number..", 呼叫没有携带sip头域，从redis中获取uuid信息: "..info..".\n");
end
local log_tag = "[always]"..callee_number;

session:consoleLog(log_tag..", enter "..lua_name..", buuid:"..buuid..", caller_number:"..caller_number.."\n")
session:setVariable("hangup_after_bridge", "true");
session:execute("pre_answer");

local b_session = freeswitch.Session(buuid);
local session_state = b_session:getState();
session:consoleLog(log_tag..", bsession status: "..session_state);
if session_state == "ERROR" then
    session:consoleLog("ERROR", log_tag..", 分机session已经不存在: "..buuid..".\n");
    session:hangup();
    return;
end

if session_state == "CS_RESET" then
    api:execute("uuid_park", buuid);
    api:execute("msleep", "200");
    session_state = b_session:getState();
    -- 话务恢复没有bridge，清理数据
    b_session:setVariable("lcc_sub_uuid", nil);
end

 -- 等待500ms，避免呼叫太快，导致的话务未断的情况
 if session_state ~= "CS_PARK" then
    session:consoleLog(log_tag..", 分机当前["..session_state.."]状态，等待500ms，避免呼叫太快，导致的话务未断的情况.\n");
    api:execute("msleep", "500");
    session_state = b_session:getState();
end

if session_state ~= "CS_PARK" then
    local signal_bond_uuid = b_session:getVariable("signal_bond") or "nil";
    local cur_sub_uuid = b_session:getVariable("lcc_sub_uuid") or "nil";
    session:consoleLog(log_tag..", 当前话机已经在通话中["..signal_bond_uuid.."]，虚拟呼叫["..cur_sub_uuid.."].");
    session:hangup("USER_BUSY");
    return ;
end

local cur_sub_uuid = b_session:getVariable("lcc_sub_uuid");
if cur_sub_uuid then
    session:consoleLog(log_tag..", 长通分机已经被占用，虚拟呼叫["..cur_sub_uuid.."].");
    session:hangup("USER_BUSY");
    return;
end

freeswitch.bridge(session, b_session);

session:consoleLog(log_tag..", lua exit");