local DB = require("common.DB")
local LuaMongo = _G.lua_mongo
local Lang = require("common.Lang")
local Util = require("common.Util")
local RoleDBLogic = require("role.RoleDBLogic")
local Log = require("common.Log")
local LogDefine = require("common.LogDefine")
local DataCache = require("core.DataCache")


local RoleList = {}
local function delRoles()
    _G.collectgarbage("step", 1000000)

	local player_uuid_list = {}
	LuaMongo.find(DB.db_char, nil, {lastLoginTime = 1, lastLogoutTime = 1, lv = 1, zuanshi = 1, buy = 1, account = 1})
	local list = {}
	RoleList = {}
	local allCnt = 0
	local delCnt = 0
	local nowTime = _G.real_os_time()
	while true do
		local data = {}
		if not LuaMongo.next(data) then
			break
		end
		allCnt = allCnt + 1
		
		-- 离线时间
        local lastLoginTime = data.lastLoginTime or 0
		local logoutTime = 0
		if data.lastLogoutTime then
			logoutTime = nowTime - math.max(data.lastLogoutTime, data.lastLoginTime)
		else
			logoutTime = nowTime - lastLoginTime
		end
		RoleList[data._id] = data.account

		-- 1级1天无登录 2级2天无登录 3-15级 20天无登录 16-30 30天无登录 无充值 
		local maxLogoutTime = nil
		if data.lv == 1 then
			maxLogoutTime = 86400
		elseif data.lv == 2 then
			maxLogoutTime = 2 * 86400
		elseif data.lv <= 15 then
			maxLogoutTime = 20 * 86400
		elseif data.lv <= 30 then
			maxLogoutTime = 30 * 86400			
		end

		if maxLogoutTime
			and (not data.buy or Util.getTableCount(data.buy) == 0)
			and maxLogoutTime < logoutTime
			then 
			list[delCnt + 1] = data._id
			RoleList[data._id] = nil
			delCnt = delCnt + 1
		else
			player_uuid_list[data._id] = data.lv
		end
	end
	
    _G.collectgarbage("step", 1000000)
	
	print("delRole", delCnt, "/", allCnt)
	local query = {}
	for _, v in ipairs(list) do
		query._id = v
		LuaMongo.remove(DB.db_char, query)
	end

	DataCache.Update_PlayerUuidList(player_uuid_list)
	
    _G.collectgarbage("step", 1000000)
end



local function handleFriend()
	-- 好友
	local delList = {}
	LuaMongo.find(DB.db_friend, nil)
	while true do
		local data = {}
		if not LuaMongo.next(data) then
			break
		end
		
		if RoleList[data.uuid1] == nil then
			delList[#delList+1] = data._id
		elseif RoleList[data.uuid2] == nil then
			delList[#delList+1] = data._id
		end
	end	

	local query = {}
	for k,v in ipairs(delList) do
		query._id = v
		LuaMongo.remove(DB.db_friend, query) 
	end
end

function handleMail()
	local delList = {}
	local allCnt = 0
	LuaMongo.find(DB.db_mail)
	local compareTime = os.time() - 7 * 24 * 3600 --删除7天以上的邮件
	while true do
		--[[local mail = {}
		if not LuaMongo.next(mail) then
			break
		end]]
		local mail = {}
		local pret,perr = pcall(LuaMongo.next,mail)
		if not pret then
		    print(perr)
			break
		end
		if not next(mail) then 
			break
		end

        if mail.expireTime then  -- 有指定过期时间
            if mail.time < os.time() - mail.expireTime then
                delList[#delList+1] = mail._id
            elseif mail.receiverUuid and RoleList[mail.receiverUuid] == nil then
			    delList[#delList+1] = mail._id
		    end
        elseif mail.time < compareTime then
			delList[#delList+1] = mail._id
		elseif mail.receiverUuid and RoleList[mail.receiverUuid] == nil then
			delList[#delList+1] = mail._id
		end

		allCnt = allCnt + 1
	end
	print("delmail:",#delList.."/"..allCnt)
	local query = {}
	for k,v in ipairs(delList) do
		query._id = v
		LuaMongo.remove(DB.db_mail, query) 
	end
end

local function delUnionMember(union,uuid)
	union.member[uuid] = nil

	union.curCnt = union.curCnt - 1

	if union.presidentUuid == uuid then
		union.presidentUuid = nil
	end
end

local function checkLeader(union)
	if union.presidentUuid == nil then
		local uuid
		for k,v in pairs(union.member) do
			if uuid == nil then
				uuid = k
			end
			if v.post == 2 then
				uuid = k
				break
			end
		end
		if uuid then
			union.member[uuid].post = 1
			union.presidentUuid = uuid
		end
	end
end

function handleUnion()
	local delList = {}
	LuaMongo.find(DB.db_union)
	local query = {}
	while true do
		local union = {}
		if not LuaMongo.next(union) then
			break
		end
		local isChange = false
		local delMembers = {}
		for uuid in pairs(union.member) do
			if not RoleList[uuid] then
				delMembers[uuid] = 1
			end
		end
		for uuid in pairs(delMembers) do
			isChange = true
			delUnionMember(union,uuid)
		end
		
		local delApplys = {}
		if union.apply then
			for uuid in pairs(union.apply) do
				if not RoleList[uuid] then
					delApplys[uuid] = 1
				end
			end
		end
		
		for uuid in pairs(delApplys) do
			isChange = true
			union.apply[uuid] = nil
		end
		
		checkLeader(union)
		if union.presidentUuid == nil then
			delList[#delList+1] = union._id
		elseif isChange then
			query._id = union._id
			LuaMongo.update(DB.db_union, query, union)
		end
	end
	
	for _,v in ipairs(delList) do
		query._id = v
		LuaMongo.remove(DB.db_union, query) 
	end
end

local function handleStar()
	-- 星空争霸
	local query = {}	
	local updateSet = {}
	local updateUnset = {}
	local tempTb = {}
			    
	LuaMongo.find(DB.db_the_stars)
	while true do
		local data = {}
		if not LuaMongo.next(data) then
			break
		end
	
		if data.uuid and not RoleList[data.uuid] then    
		    data.uuid = nil
		    data.body = nil
			query._id = data._id			
			LuaMongo.update(DB.db_the_stars, query, data)
		end
	end	
end

local function handleJJC()
    LuaMongo.find(DB.db_jjc)
    local delList = nil
    while true do
    	local jjcData = {}
	    if not LuaMongo.next(jjcData) then
			break
	    end
	    if not jjcData.monsterOutID and not RoleList[jjcData._id] then
	    	delList = delList or {}
	    	delList[#delList + 1] = jjcData._id
	    end
	end
	if not delList then return end

    local query = {}
    for _, uuid in ipairs(delList) do
    	query._id = uuid
    	LuaMongo.remove(DB.db_jjc, query)
    end
end

local function handleVideo()
	LuaMongo.find(DB.db_combat_video, {["combatInfo.attacker"] = 1})
    local delList = nil
    while true do
    	local combatVideo = {}
	    if not LuaMongo.next(combatVideo) then
			break
	    end
	    local uuid = combatVideo.combatInfo.attacker.uuid
	    if not RoleList[uuid] then
	    	delList = delList or {}
	    	delList[#delList + 1] = uuid
	    end
	end	
	if not delList then return end

    local query = {}
    for _, uuid in ipairs(delList) do
    	query._id = uuid
    	LuaMongo.remove(DB.db_combat_video, query)
    end
end

function roleDel()
    if _G.is_middle == true then return end

	delRoles() -- 删角色
	
	-- 删号后其它相关的数据处理
	handleFriend()  -- 处理好友表
	handleMail()	-- 处理邮件表
	handleUnion()   -- 处理公会表 会长如果被删号 会长转移给官员 没官员则转移给随机一个人/如果公会所有人都被删号 删除这个公会
	handleStar()    -- 处理星空争霸 
	handleJJC()		-- 处理单人竞技场
	handleVideo() 	-- 处理战斗记录
end

local QueryCreateRoleLog = {changeNameCnt=0}
local function handleCreateRoleLog()
    _G.collectgarbage("step", 1000000)
	LuaMongo.find(DB.db_char, QueryCreateRoleLog, {_id="1", newUniqueTag=1, name=1, lv = 1, ip=1})
	local list = {}
	RoleList = {}
	local allCnt = 0
	local delCnt = 0
	local nowTime = _G.real_os_time()
	while true do
		local data = {}
		if not LuaMongo.next(data) then
			break
		end
        Log.write(Log.LOGID_OSS_REGISTER, data._id, data.newUniqueTag, data.name, data.ip,"","")
		Log.write(Log.LOGID_OSS_CREATELOSS,data.newUniqueTag, data.name, LogDefine.HUMAN_LOST.CREATE_NAME_FINISH, data.ip, data.pf or "", data.appid or "", data.phpChanelID or 0)
	end
    _G.collectgarbage("step", 1000000)
end

local delQuery = {videoType=2}
local function handleCleanVideoLog()
   -- 清除个人录像记录
   LuaMongo.remove(DB.db_combat_video, delQuery)
end

function initAfterHot()
   if _G.is_middle == true then return end

   --handleCreateRoleLog()
end