local Lang = require("common.Lang")
local Util = require("common.Util")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local WeekTaskExcel = require("excel.weekTask")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local ChatPaoMaLogic = require("chat.ChatPaoMaLogic")
local RoleSystemLogic = require("roleSystem.RoleSystemLogic")
local RoleSystemDefine = require("roleSystem.RoleSystemDefine")
local ItemDefine = require("bag.ItemDefine")
local ChengjiuLogic = require("chengjiu.ChengjiuLogic")
local ChengjiuDefine = require("chengjiu.ChengjiuDefine")
local YunYingLogic = require("yunying.YunYingLogic")
local WeekTaskExcel = require("excel.weekTask")

local AnniversaryActiveWheel

-- weekTask = {
     -- task ={ id  =  isGet,finiscnt,state}

	 --huoyueBox = {}

	 --nowHuoyue
-- }

WEEK_TASK_ID_1  = 1  --寻星10次 o
WEEK_TASK_ID_2  = 2  --高级召唤50次 o
WEEK_TASK_ID_3  = 3  --天命召唤7次 o
WEEK_TASK_ID_4  = 4  --公会BOSS挑战50次 x
WEEK_TASK_ID_5  = 5  --宝箱开启35次 o
WEEK_TASK_ID_6  = 6  --扫荡28次 o
WEEK_TASK_ID_7  = 7  --任意商定购买50次 o
WEEK_TASK_ID_8  = 8  --勇者试炼战胜30次 x
WEEK_TASK_ID_9  = 9  --冰龙巢穴挑战7次 o
WEEK_TASK_ID_10 = 10 --魔王珠玑跳转7次 o


function WeekTaskQuery(human, isOnLogin)
	-- print("当前进入周任务查询")
	local sendErr = isOnLogin == false and true or false
	if RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_802, sendErr) ~= true then
		return
	end

	local weekTaskConfig = WeekTaskExcel.weekTask
	if not weekTaskConfig then return end
	
	-- 每周更新一次
	-- ObjHuman.updateWeek(human)
	
	local msgRet = Msg.gc.GC_WEEKTASK_QUERY
	--下次刷新时间？
	local now = os.time()
	local ts1 = Util.getWeekStartTime(now)
	msgRet.nextRefreshTime = 24 * 60 * 60 * 7 - (now - ts1)
	
	local cnt = 0
	for key, value in ipairs(WeekTaskExcel.weekTask) do 
		cnt = cnt + 1
		msgRet.list[cnt].taskID = key
		msgRet.list[cnt].desc = value.taskDesc
		msgRet.list[cnt].maxCnt = value.taskProgress

		local len = 0 
		for i = 1, #value.reward do 
			len = len + 1
			local itemId = value.reward[i][1]
			local itemCnt = value.reward[i][2]
			Grid.makeItem(msgRet.list[cnt].itemData[len], itemId, itemCnt)
		end
		msgRet.list[cnt].itemData[0] = len


		msgRet.list[cnt].finishCnt = 0
		msgRet.list[cnt].isGet = 0
		msgRet.list[cnt].jump = value.panelID
		if human.db.weekTask and human.db.weekTask.task and human.db.weekTask.task[key] then
			msgRet.list[cnt].finishCnt = human.db.weekTask.task[key].finishCnt or 0
			if human.db.weekTask.task[key].isGet then 
				msgRet.list[cnt].isGet = 1
			end
		end
	end
	
	local huoYueBoxConfig = WeekTaskExcel.huoYueBox
	msgRet.huoYueBox[0] = #huoYueBoxConfig
	for i=1,#WeekTaskExcel.huoYueBox do
		msgRet.huoYueBox[i].boxID = i 
		msgRet.huoYueBox[i].needHuoYue = huoYueBoxConfig[i].needHuoYue
		
		msgRet.huoYueBox[i].items[0] = #huoYueBoxConfig[i].reward
		for j=1,#huoYueBoxConfig[i].reward do
			local itemID = huoYueBoxConfig[i].reward[j][1]
			local itemCnt = huoYueBoxConfig[i].reward[j][2]
			Grid.makeItem(msgRet.huoYueBox[i].items[j],itemID,itemCnt)
		end

		local isGet = human.db.weekTask and human.db.weekTask.huoYueBox and human.db.weekTask.huoYueBox[i] or 0
		msgRet.huoYueBox[i].isGet = isGet
	end

	msgRet.nowHuoYue = human.db.weekTask and human.db.weekTask.nowHuoYue or 0

	msgRet.list[0] = cnt
	-- table.print_lua_table(msgRet)
	print("周任务查询成功!")
	Msg.send(msgRet, human.fd)
end

--统计奖励
local function calcReward(human, awardCfg)
	for i = 1, #awardCfg do
		local itemId = awardCfg[i][1]
		local itemCnt = awardCfg[i][2]
        if itemId == ItemDefine.ITEM_WEEKTASK_ID then
            onWeekTaskHuoYue(human,itemCnt)
        else
			local newCnt = math.ceil(itemCnt)
			--BagLogic.updateMomentItem(2, itemId, itemCnt)
			BagLogic.updateMomentItem(2, itemId, newCnt)
        end
	end
end
-- 领取每周任务奖励
function weekTaskGetReward(human, taskID)
	print("当前进入领取每周奖励")
	if RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_802) ~= true then
		return
	end
	print("当前进入领取每周奖励1111111111111111111111111111")
	-- ObjHuman.updateWeek(human)
	------------------------------------新改为: 一键领取所有能领取的奖励---------------------------------------------
	if human.db.weekTask == nil or human.db.weekTask.task == nil then
		print("[weekTaskGetReward]..当前没有每周任务，返回了")
		table.print_lua_table(human.db.weekTask)
		return
	end
	print("当前进入领取每周奖励22222222222222222")
	local isClean = false
	local taskData = human.db.weekTask.task
	print("当前进入领取每周奖励3333333333333333333333333")
	for taskId, data in pairs(taskData) do
		if not data.isGet then
			local weekTaskConfig = WeekTaskExcel and WeekTaskExcel.weekTask and WeekTaskExcel.weekTask[taskId]
			if data.finishCnt and data.finishCnt >= weekTaskConfig.taskProgress then
				if not isClean then
					BagLogic.cleanMomentItemList()
					isClean = true
				end
				
				calcReward(human, weekTaskConfig.reward)
				-- onWeekTaskHuoYue(human,10)
				data.isGet = true
			end
		end
	end
	print("当前进入领取每周奖励44444444444444444444444")
	if isClean then
		BagLogic.addMomentItemList(human, "week_task")
		WeekTaskQuery(human)
		RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_802)
	end

	print("每周奖励领取完毕")
end


-- 记录每个任务的完成次数
function recordWeekTaskFinishCnt(human, taskID, addCnt, noSend)

	-- ObjHuman.updateWeek(human)

	human.db.weekTask = human.db.weekTask or {}
	human.db.weekTask.task = human.db.weekTask.task or {}
	human.db.weekTask.task[taskID] = human.db.weekTask.task[taskID] or {}
    if human.db.weekTask.task[taskID].state ~= nil then
		print("[WeekTaskLogic-recordWeekTaskFinishCnt].1111111111111111111111111111111111111在这里返回了")
        return
    end

	human.db.weekTask.task[taskID].finishCnt = (human.db.weekTask.task[taskID].finishCnt or 0) + addCnt
	print("[WeekTaskLogic-recordWeekTaskFinishCnt].2222222222222222222222222222222222222",addCnt)
	local weekTaskConfig = WeekTaskExcel.weekTask[taskID]
	if not weekTaskConfig then return end
	if human.db.weekTask.task[taskID].finishCnt >= weekTaskConfig.taskProgress then
		print("[WeekTaskLogic-recordWeekTaskFinishCnt].3333333333333333333333333333333333",addCnt)
		human.db.weekTask.task[taskID].finishCnt = weekTaskConfig.taskProgress
		human.db.weekTask.task[taskID].state = 1
		RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_802)

        ChengjiuLogic.onCallback(human,ChengjiuDefine.CJ_TASK_TYPE_12,1)

        -- local msgRet = Msg.gc.GC_WEEKSHARE_SET
        -- msgRet.type = 4
        -- msgRet.desc = weekTaskConfig.taskDesc
        -- Msg.send(msgRet,human.fd)

	end
	print("[WeekTaskLogic-recordWeekTaskFinishCnt].44444444444444444444444444444444444",addCnt)
	if noSend ~= true then
		WeekTaskQuery(human)
	end
	print("[WeekTaskLogic-recordWeekTaskFinishCnt].22222222222222222222222222222222222222",human.db.weekTask.task[taskID].finishCnt)
end

-- 领取活跃宝箱
local function huoYueBoxCanGet(human,boxID)
	local weekTaskDB = human.db.weekTask
	if not weekTaskDB then return end

	local isGet = weekTaskDB.huoYueBox and weekTaskDB.huoYueBox[boxID] or 0
	if isGet ~= 0 then return end

	local nowHuoYue = weekTaskDB.nowHuoYue or 0
	local huoYueBoxConfig = WeekTaskExcel.huoYueBox[boxID]
	if nowHuoYue <= 0 or nowHuoYue < huoYueBoxConfig.needHuoYue then return end

	return true
end

function CG_WEEKTASK_GET_HUOYUEBOX(human,boxID)
	
	------------------------------一键领取所有能领取的宝箱奖励------------------------------------
	print("当前进入领取周活跃")
	local weekTaskDB = human.db.weekTask
	if not weekTaskDB then
		print("当前不包含dailDB,返回了")
		return
	end

	local nowHuoYue = weekTaskDB.nowHuoYue
	if not nowHuoYue then
		print("当前不包含nowHuoYue,返回了")
		return
	end


	local double = RoleSystemLogic.isDouble(human, RoleSystemDefine.ROLE_SYS_ID_802)
    local rewardCnt = double and 2 or 1
    local cjPrivilege = ChengjiuLogic.checkPrivilege(human,ChengjiuDefine.PRIVILEGE_TYPE_2)

	local len = 0
	local randRate = 1
	local awardList = {}
	local boxData = weekTaskDB.huoYueBox
	local boxConfig = WeekTaskExcel.huoYueBox

	print("是否走到循环之前？")
	for boxId, v in ipairs(boxConfig) do
		print("当前活跃度不够是否进入循环?")
		if nowHuoYue >= v.needHuoYue and (not boxData or not boxData[boxId]) then
			print("当前进入循环")
			weekTaskDB.huoYueBox = weekTaskDB.huoYueBox or {}
			boxData = weekTaskDB.huoYueBox
			boxData[boxId] = 1

			randRate = 1
			if cjPrivilege then
				local random = math.random(1,100)
				if random <= 1 then
					randRate = 2
				end
			end

			for _, itemInfo in ipairs(v.reward) do
				len = len + 1
				awardList[len] = {itemInfo[1], itemInfo[2] * randRate * rewardCnt}
			end

			--更新
			local msgRet = Msg.gc.GC_WEEKTASK_GET_HUOYUEBOX
			msgRet.boxID = boxId
			msgRet.double = double and 1 or 0
			print("当前周活跃奖励领取完毕")
			print("当前下发周活跃奖励")
			Msg.send(msgRet,human.fd)
		end
	end

	if len > 0 then
		BagLogic.addItemList(human, awardList, "week_task")
		RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_802)
	end
end

function isDot(human)
	-- 主界面的任务包含2个标签 每日任务/成就
	if RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_802) ~= true then
		return false
	end
	
	if human.db.weekTask and human.db.weekTask.task then
		for k,v in pairs(human.db.weekTask.task) do
			if k and v and v.isGet ~= true then
				local weekTaskConfig = WeekTaskExcel.weekTask[k]
				if weekTaskConfig then
					local cnt = v.finishCnt or 0
					if cnt >= weekTaskConfig.taskProgress then
						return true
					end
				end
			end
		end	
	end

	for i=1,#WeekTaskExcel.huoYueBox do
		if huoYueBoxCanGet(human,i) then 
			return true 
		end
	end
	
	return false
end

local function getMaxWeekHuoYue()
	local finallyIdx = #WeekTaskExcel.huoYueBox
	local finallyCfg = WeekTaskExcel.huoYueBox[finallyIdx]
	return finallyCfg.needHuoYue
end

function onWeekTaskHuoYue(human,sum)
	if not human.db.weekTask then return end
	print("当前进入添加活跃度",sum)
	human.db.weekTask.nowHuoYue = (human.db.weekTask.nowHuoYue or 0) + sum

    YunYingLogic.onCallBack(human, "onDailyTask",sum)   

	if isReachMaxWeekHuoYue(human) then
		AnniversaryActiveWheel = AnniversaryActiveWheel or require("absAct.AnniversaryActiveWheel")
		AnniversaryActiveWheel.OnHuoYueReach100(human)
	end
end

function WeekTaskLogic_Refsh(human)
	if not human.db.weekTask then
		human.db.weekTask = {}
		human.db.weekTask.nTime = os.time()
	else
		if not human.db.weekTask.nTime then
			human.db.weekTask.nTime = os.time()
		end
		
		local nLastTime = human.db.weekTask.nTime
		local bIsWeek = Util.isSameWeek(nLastTime, os.time())
		if false == bIsWeek then
			human.db.weekTask = {}
			human.db.weekTask.nTime = os.time()
		end
	end
end

function onLogin(human)	
	WeekTaskLogic_Refsh(human)
end

function GetWeekHuoYue(human)
	local num = human.db.weekTask and human.db.weekTask.nowHuoYue or 0
	return num
end

function isReachMaxWeekHuoYue(human)
	local curVal = GetWeekHuoYue(human)
	local maxVal = getMaxWeekHuoYue()
	return curVal >= maxVal
end