local Lang = require("common.Lang")
local Util = require("common.Util")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local DailyTaskExcel = require("excel.dailyTask")
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 WeekTaskLogic = require("dailyTask.WeekTaskLogic")
local HonorTaskLogic = require("dailyTask.HonorJourney")

local CommonActMoneyTree
local AnniversaryActiveWheel

DAILY_TASK_ID_1  = 1  --日常登陆1次 o
DAILY_TASK_ID_2  = 2  --赠送友情点5次 o
DAILY_TASK_ID_3  = 3  --进行3次招将 o
DAILY_TASK_ID_4  = 4  --擂台挑战3次 x
DAILY_TASK_ID_5  = 5  --通天塔扫荡/挑战3次 o
DAILY_TASK_ID_6  = 6  --公会boss挑战3次 o
DAILY_TASK_ID_7  = 7  --进行1次公会建设 o
DAILY_TASK_ID_8  = 8  --参与1次无尽试炼 x
DAILY_TASK_ID_9  = 9  --接取3次民生任务 o
DAILY_TASK_ID_10 = 10 --参与2次日常副本 o
DAILY_TASK_ID_11 = 11 --圣树试炼胜利3次 o
DAILY_TASK_ID_12 = 12 --征战扫荡5次 o

-- 查询每日任务
function dailyTaskQuery(human, isOnLogin)
	local sendErr = isOnLogin == false and true or false
	if RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_801, sendErr) ~= true then
		return
	end

	local dailyTaskConfig = DailyTaskExcel.dailyTask
	if not dailyTaskConfig then return end
	
	-- 每日更新
	ObjHuman.updateDaily(human)
	
	local msgRet = Msg.gc.GC_DAILYTASK_QUERY 
	local now = os.time()
	local ts1 = Util.getDayStartTime(now)
	msgRet.nextRefreshTime = 24 * 60 * 60 - (now - ts1)
	
	local cnt = 0
	for key, value in ipairs(DailyTaskExcel.dailyTask) do 
		cnt = cnt + 1
		msgRet.list[cnt].taskID = key
		msgRet.list[cnt].desc = value.taskDesc
		msgRet.list[cnt].maxCnt = value.taskCnt

		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.dailyTask and human.db.dailyTask.task and human.db.dailyTask.task[key] then
			msgRet.list[cnt].finishCnt = human.db.dailyTask.task[key].finishCnt or 0
			if human.db.dailyTask.task[key].isGet then 
				msgRet.list[cnt].isGet = 1
			end
		end
	end
	
	local huoYueBoxConfig = DailyTaskExcel.huoYueBox
	msgRet.huoYueBox[0] = #huoYueBoxConfig
	for i=1,#DailyTaskExcel.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.dailyTask and human.db.dailyTask.huoYueBox and human.db.dailyTask.huoYueBox[i] or 0
		msgRet.huoYueBox[i].isGet = isGet
	end

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

	msgRet.list[0] = cnt
	--Msg.trace(msgRet)
	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.ITME_HUOYUE_ID then
            onDailyTaskHuoYue(human,itemCnt)
        else
			local newCnt = math.ceil(itemCnt)
			--BagLogic.updateMomentItem(2, itemId, itemCnt)
			BagLogic.updateMomentItem(2, itemId, newCnt)
        end
	end
end


-- 领取每日任务奖励
function dailyTaskGetReward(human, taskID)
	if RoleSystemLogic.isOpen(human, RoleSystemDefine.ROLE_SYS_ID_801) ~= true then
		return
	end

	-- local dailyTaskConfig = DailyTaskExcel.dailyTask[taskID]
	-- if not dailyTaskConfig then return end

	-- 每日更新
	ObjHuman.updateDaily(human)
	
	-- if human.db.dailyTask == nil or human.db.dailyTask.task == nil or human.db.dailyTask.task[taskID] == nil then
	-- 	return
	-- end

	-- --判断上限	
	-- if human.db.dailyTask.task[taskID].isGet then
	-- 	return
	-- end
		
	-- if human.db.dailyTask.task[taskID].finishCnt == nil or human.db.dailyTask.task[taskID].finishCnt < dailyTaskConfig.taskCnt then
	-- 	return
	-- end
	
	-- --改db
	-- human.db.dailyTask.task[taskID].isGet = true


    -- --奖励倍数
	-- BagLogic.cleanMomentItemList()
	-- for i = 1, #dailyTaskConfig.reward do 
	-- 	local itemId = dailyTaskConfig.reward[i][1]
	-- 	local itemCnt = dailyTaskConfig.reward[i][2]
    --     if itemId == ItemDefine.ITME_HUOYUE_ID then
    --         onDailyTaskHuoYue(human,itemCnt)
    --     else
	-- 		local newCnt = math.ceil(itemCnt) 
	-- 		BagLogic.updateMomentItem(2, itemId, itemCnt)
    --     end
	-- end
    -- BagLogic.addMomentItemList(human, "daily_task")
--	ChatPaoMaLogic.trigger(human, ChatPaoMaLogic.TRIGGER_TYPE_2, rewardID, rewardCnt)
	-- 通知客户端
	-- dailyTaskQuery(human)
	
	-- RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_801)


	------------------------------------新改为: 一键领取所有能领取的奖励---------------------------------------------
	if human.db.dailyTask == nil or human.db.dailyTask.task == nil then
		return
	end

	local isClean = false
	local taskData = human.db.dailyTask.task

	for taskId, data in pairs(taskData) do
		if not data.isGet then
			local dailyTaskConfig = DailyTaskExcel.dailyTask[taskId]
			if data.finishCnt and data.finishCnt >= dailyTaskConfig.taskCnt then
				if not isClean then
					BagLogic.cleanMomentItemList()
					isClean = true
				end
				calcReward(human, dailyTaskConfig.reward)
				data.isGet = true
			end
		end
	end

	if isClean then
		BagLogic.addMomentItemList(human, "daily_task")
		dailyTaskQuery(human)
		RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_801)
	end
end

-- 记录每个任务的完成次数
function recordDailyTaskFinishCnt(human, taskID, addCnt, noSend)
	-- 每日更新
	ObjHuman.updateDaily(human)

	human.db.dailyTask = human.db.dailyTask or {}
	human.db.dailyTask.task = human.db.dailyTask.task or {}
	human.db.dailyTask.task[taskID] = human.db.dailyTask.task[taskID] or {}
	
    if human.db.dailyTask.task[taskID].state ~= nil then
        return
    end

	human.db.dailyTask.task[taskID].finishCnt = (human.db.dailyTask.task[taskID].finishCnt or 0) + addCnt
	
	local dailyTaskConfig = DailyTaskExcel.dailyTask[taskID]
	if not dailyTaskConfig then return end
	if human.db.dailyTask.task[taskID].finishCnt >= dailyTaskConfig.taskCnt then
		human.db.dailyTask.task[taskID].finishCnt = dailyTaskConfig.taskCnt
		human.db.dailyTask.task[taskID].state = 1
		RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_801)

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

        local msgRet = Msg.gc.GC_DAILYSHARE_SET
        msgRet.type = 1
        msgRet.desc = dailyTaskConfig.taskDesc
        Msg.send(msgRet,human.fd)

	end
	
	if noSend ~= true then
		dailyTaskQuery(human)
	end
end

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

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

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

	return true
end

function CG_DAILYTASK_GET_HUOYUEBOX(human,boxID)
	-- local huoYueBoxConfig = DailyTaskExcel.huoYueBox[boxID]
	-- if not huoYueBoxConfig then return end

	-- if not huoYueBoxCanGet(human,boxID) then return end

	-- human.db.dailyTask.huoYueBox = human.db.dailyTask.huoYueBox or {}
	-- human.db.dailyTask.huoYueBox[boxID] = 1
    
    -- local double = RoleSystemLogic.isDouble(human, RoleSystemDefine.ROLE_SYS_ID_801)
    -- local rewardCnt = double and 2 or 1
    -- local cjPrivilege = ChengjiuLogic.checkPrivilege(human,ChengjiuDefine.PRIVILEGE_TYPE_2)
    -- local item = Util.copyTable(huoYueBoxConfig.reward)
    -- if cjPrivilege then
    --     local random = math.random(1,100)
    --     if random <= 1 then
    --         local len = #item
    --         for i = 1,len do
    --             item[i][2] = item[i][2] * 2
    --         end
    --     end

       
    -- end

	-- if double then
	-- 	local len = #item
    --     for i = 1,len do
    --         item[i][2] = item[i][2] * rewardCnt
    --     end
	-- end
	
	-- local msgRet = Msg.gc.GC_DAILYTASK_GET_HUOYUEBOX
	-- msgRet.boxID = boxID
    -- msgRet.double = double and 1 or 0
	-- Msg.send(msgRet,human.fd)
    -- BagLogic.addItemList(human, item, "daily_task")
	-- RoleSystemLogic.onDot(human, RoleSystemDefine.ROLE_SYS_ID_801)

	-------------------------------新修改为：一键领取所有能领取的宝箱奖励------------------------------------

	local dailyTaskDB = human.db.dailyTask
	if not dailyTaskDB then
		return
	end

	local nowHuoYue = dailyTaskDB.nowHuoYue
	if not nowHuoYue then
		return
	end


	local double = RoleSystemLogic.isDouble(human, RoleSystemDefine.ROLE_SYS_ID_801)
    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 = dailyTaskDB.huoYueBox
	local boxConfig = DailyTaskExcel.huoYueBox


	for boxId, v in ipairs(boxConfig) do
		if nowHuoYue >= v.needHuoYue and (not boxData or not boxData[boxId]) then
			dailyTaskDB.huoYueBox = dailyTaskDB.huoYueBox or {}
			boxData = dailyTaskDB.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_DAILYTASK_GET_HUOYUEBOX
			msgRet.boxID = boxId
			msgRet.double = double and 1 or 0
			Msg.send(msgRet,human.fd)

			if boxId == #boxConfig then
				CommonActMoneyTree = CommonActMoneyTree or require("absAct.CommonActMoneyTree")
				CommonActMoneyTree.CompleteHuoYueTask(human)
			end
		end
	end

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

end

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

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

local function getMaxDailyHuoYue()
	local finallyIdx = #DailyTaskExcel.huoYueBox
	local finallyCfg = DailyTaskExcel.huoYueBox[finallyIdx]
	return finallyCfg.needHuoYue
end


function onDailyTaskHuoYue(human,sum)
	if not human.db.dailyTask then return end

	human.db.dailyTask.nowHuoYue = (human.db.dailyTask.nowHuoYue or 0) + sum

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

	-- local finallyIdx = #DailyTaskExcel.huoYueBox
	-- local finallyCfg = DailyTaskExcel.huoYueBox[finallyIdx]
	-- if human.db.dailyTask.nowHuoYue >= finallyCfg.needHuoYue then
	-- 	CommonActMoneyTree = CommonActMoneyTree or require("absAct.CommonActMoneyTree")
	-- 	CommonActMoneyTree.CompleteHuoYueTask(human)
	-- end

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

function onLogin(human)	
	recordDailyTaskFinishCnt(human, DAILY_TASK_ID_1, 1, true)
	dailyTaskQuery(human, true)

	--周任务和荣耀历程
	WeekTaskLogic.onLogin(human)
	HonorTaskLogic.onLogin(human)
end

function Gm_AddHuoYue(human, nAddNum)
	onDailyTaskHuoYue(human, nAddNum)
end


function GetDailyHuoYue(human)
	local num = human.db.dailyTask and human.db.dailyTask.nowHuoYue or 0
	return num
end

function isReachMaxDailyHuoYue(human)
	local curVal = GetDailyHuoYue(human)
	local maxVal = getMaxDailyHuoYue()
	return curVal >= maxVal
end