local lua_mongo = _G.lua_mongo
local Config = require("Config")
local Log = require("common.Log")
local Util = require("common.Util")
local PfLogic = require("platform.PfLogic")
local SdkLogic = require("platform.SdkLogic")

-- 是否需要检验账号
local function isNeedCheck(account)
	if Config.IS_USE_GM_CMD == true then
		return
	end


	--[[if PfLogic.isKunTang() or 
       PfLogic.isShouQ() or 
        PfLogic.isFKW() or 
        PfLogic.isQQ() or 
        PfLogic.isAug() or 
        PfLogic.is9377() or 
        PfLogic.isTaptap() or 
        PfLogic.isYingHe() then
		return  -- 某些平台，不开校验
	end
	return true]]
    return
end

local function getReallyAccout(account)
	if not account then return end

	local tb = Util.split(account, "-")
	if #tb < 2 then return end

	local svrIndex = tonumber(tb[1])
	if math.abs(Config.SVR_INDEX - svrIndex) >= 100000 then
		return -- 账号服务器应该一致
	end	
	local index = #tb
	local realAccount = ""
	for i = 2, index do
		if i > 2 then
			realAccount = realAccount .. "-"
		end
		realAccount = realAccount .. tb[i]
	end

	return realAccount
end

function getCalckey(account, timestamp, ip)
	return lua_mongo.md5(account .. timestamp .. ip .. Config.AUTH_KEY)
end
-- 这里做账号验证
function authCheck(account, authkey, timestamp, ip,sign)
	if isNeedCheck(account) ~= true then
		return true
	end

	local realAccount = getReallyAccout(account)
	if not realAccount then
		Log.write(Log.LOGID_TEST, "auth check fail no realaccount", account, authkey, timestamp, os.time())
		return
	end

	local sec = os.time() - timestamp
	if math.abs(sec) > 86400 then
		Log.write(Log.LOGID_TEST, "auth check fail ts err", account, authkey, timestamp, os.time())
		return
	end
	local signStr = lua_mongo.md5("app_id=12&mem_id="..account.."&user_token="..authkey.."app_key=64ba80a7e327f3f334425d8a8d897117")
	if signStr ~= sign then
		return 
	end
	--return true	
	-- local sdkRet = SdkLogic.CheckUserToken(account,authkey)
	-- if sdkRet == true then
	-- 	return true
	-- end
	-- return false	
	local calckey = getCalckey(realAccount, timestamp, ip)
	if calckey ~= authkey then
		Log.write(Log.LOGID_TEST, "auth check fail calckey", account, authkey, timestamp, os.time(), calckey)
		return
	end
	return true
end


