function string.split(str)
  local splitlist = {};
  string.gsub(str, '[^,]+', function(w) table.insert(splitlist, w) end )
  return splitlist;
end

function isInTable(value, tbl)
  for k,v in ipairs(tbl) do
    if v == value then
    return true;
    end
  end
  return false;
end

local path = ngx.var.normalPath;
local channelPath = ngx.var.channelPath;

-- 解析手机号和特殊渠道
local tailNumbers = string.split(ngx.var.tailNumber);
local excludeChannel = string.split(ngx.var.excludeChannel)

-- 解析渠道设置
local register = string.split(ngx.var.registerChannel);

-- cookie值
local register_cookie = ngx.var.cookie_registerFrom

-- uri参数值
local args = ngx.req.get_uri_args()
local register_uri = args['registerFrom']
local phoneNo = args['phoneNo']
if (not phoneNo or string.len(phoneNo) == 0) then
  phoneNo = ngx.var.cookie_phoneNo
end

local baiTiao = '222';

if (register_uri) then
  isBaitiao = register_uri == baiTiao
else
  isBatitiao = register_cookie == baiTiao
end

if (isBatitiao) then
  return channelPath;
end

-- 没有设置渠道，设置了手机号，属于特殊渠道（不属于特殊，但符合尾号规则）时，返回旧版
if (ngx.var.excludeChannel ~= '' or ngx.var.tailNumber ~= '') then
  local hitExclude = isInTable(register_uri, excludeChannel) or isInTable(register_cookie, excludeChannel)

  if (hitExclude) then
    return path;
  end

  -- 是否符合手机尾号规则
  local hitTailNumber = false
  if phoneNo then
    for key,value in ipairs(tailNumbers)
    do
      if (string.match(phoneNo, value..'$')) then
        hitTailNumber = true
        break
      end
    end
  end
  
  if (hitTailNumber) then
    return channelPath;
  end
end

return channelPath;

