local CommonDB = require("common.CommonDB")
local Msg = require("core.Msg")
local OpenActExcel = require("excel.openAct")
local Gird = require("bag.Grid")
local YunYingLogic = require("yunying.YunYingLogic")
local PanelDefine = require("broadcast.PanelDefine")
local Util = require("common.Util")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local OpenAct = require("present.OpenAct")
local BagLogic = require("bag.BagLogic")


--[[
    mengxin = {}
    mengxin.task = {}
    mengxin.task[taskID] = {}
    mengxin.task[taskID] = state
    
    mengxin.taskType[type] = {}
    mengxin.taskType[type] = cnt

    mengxin.reach = {}
    mengxin.reach[ID] = state

    mengxin.jifen = jifen
]]

MX_TASK_TYPE_1 = 1          -- 闯关进度
MX_TASK_TYPE_2 = 2          -- 恶魔之塔进度
MX_TASK_TYPE_3 = 3          -- 冠军联赛挑战次数
MX_TASK_TYPE_4 = 4          -- bar任务
MX_TASK_TYPE_5 = 5          -- 冰龙伤害
MX_TASK_TYPE_6 = 6          -- 占卜次数
MX_TASK_TYPE_7 = 7          -- 绝望深渊进度
MX_TASK_TYPE_8 = 8          -- 勇者试炼进度
MX_TASK_TYPE_9 = 9          -- 女巫森林挑战或扫荡次数
MX_TASK_TYPE_10 = 10        -- 公会捐赠
MX_TASK_TYPE_11 = 11        -- 挑战公会boss
MX_TASK_TYPE_12 = 12        -- 高级召唤
MX_TASK_TYPE_13 = 13        -- 合成5星以上英雄
MX_TASK_TYPE_14 = 14        -- 拥有100级以上英雄
MX_TASK_TYPE_15 = 15        -- 获得SSR英雄
MX_TASK_TYPE_16 = 16        -- 遗迹探险打到N关
MX_TASK_TYPE_17 = 17        -- 拥有N个145级英雄
MX_TASK_TYPE_18 = 18        -- 拥有N个180级英雄


function initDB(human)
    if not human.db.mengxin then
        local mengxin = {}
        mengxin.task = {}
        mengxin.taskType ={}
        mengxin.reach = {}
        mengxin.jifen = 0
        human.db.mengxin = mengxin
    end
end

-- 构建task结构体
local function fontTaskNet(human,net,k,v)
    net.id = k
    net.name = Util.format(v.name,v.need)
    net.desc = v.desc
    net.needCnt = v.need
    net.panelID = v.panelID
    net.nowCnt = 0
    net.state = 0
    if human.db.mengxin and 
       human.db.mengxin.task then
        net.state = human.db.mengxin.task[k] or 0
    end
    
    if human.db.mengxin and 
       human.db.mengxin.taskType then
        net.nowCnt = human.db.mengxin.taskType[v.type] or 0
    end

    local len = #v.item
    for i = 1,len do
        Gird.makeItem(net.item[i],v.item[i][1],v.item[i][2])
    end
    net.item[0] = len
end

local function fontReachNet(human,net,k,v)
    net.id = k
    net.jifen = v.need
    net.state = 0
    if human.db.mengxin and 
       human.db.mengxin.reach then
        net.state = human.db.mengxin.reach[k] or 0
    end
    local len = #v.item
    for i = 1,len do
        Gird.makeItem(net.item[i],v.item[i][1],v.item[i][2])
    end
    net.item[0] = len
end

function isDayRed(human,day)
    local openDay = CommonDB.getServerOpenDay()
    if day > openDay then
        return
    end
    local config = OpenActExcel.mxTask
    for k,v in pairs(config) do
        if v.days == day then
            if getTaskState(human,k) == 1 then
                return true
            end
        end
    end
end

function getTaskState(human,id)
    if human.db.mengxin and 
       human.db.mengxin.task then
        return human.db.mengxin.task[id]
    end
end

function getReachState(human,id)
    if human.db.mengxin and 
       human.db.mengxin.reach then
        return human.db.mengxin.reach[id]
    end
end

function setTaskState(human,id,state)
    initDB(human)

    human.db.mengxin.task[id] = state
end

function setReachState(human,id,state)
    initDB(human)
    human.db.mengxin.reach[id] = state
end

function isBaseOpen(human,noSend)
	local openLv = YunYingLogic.getOpenLvByPanelID(PanelDefine.PANEL_ID_3605)
    if human.db.lv < openLv then
        if not noSend then
            local str = Util.format(Lang.ROLE_LEV_ERROR,openLv)
            return Broadcast.sendErr(human,str)
        end
    end
    local flag = OpenAct.getOpenActTime(OpenAct.OPEN_ACT_SERVER_GIFT)
    if not flag then
		return
	end

    return true
end

function isOpen(human)
	if isBaseOpen(human,true) then
		return true
	end
end

function getLeftTime()
   local openDay = CommonDB.getServerOpenDay()
   if openDay == nil then
	  return 0
   end

   local OpenActConfig = OpenActExcel.openAct[1]
   if not OpenActConfig then return 0 end

   local sDay = OpenActConfig.sDay;
   local eDay = OpenActConfig.eDay;

   if openDay >= sDay and openDay <= eDay then
      local time = os.time();
   	  local openTime = CommonDB.getServerOpenTime()
      if openTime == 0 then
		 return 0
	  end

      local endTime = Util.getDayStartTime(openTime) + eDay * 86400
      return endTime - time
   end

   return 0
end

-- 查询
function query(human,day)
    -- 开服超过7天 活动已结束
    local openDay = CommonDB.getServerOpenDay()
    if not isOpen(human) then
        return
    end

    if day == 0 then
        day = openDay
    end

    -- 日期传入错误
    if not day or day > openDay or day < 0 then
        return 
    end

    local openTime = CommonDB.getServerOpenTime()
    -- 写数据
    local msgRet = Msg.gc.GC_OA_MENGXIN_QUERY
    local endTime = openTime + 7*86400
    local now = os.time()
    msgRet.leftTime = endTime - now
    msgRet.nowDay = openDay
    msgRet.totalJifen = 0
    if human.db.mengxin and human.db.mengxin.jifen then
        msgRet.totalJifen = human.db.mengxin.jifen
    end
    local config = OpenActExcel.mxTask
    local len = 0
    for k,v in pairs(config) do
        if v.days == day then
            len = len + 1
            local net = msgRet.taskList[len]
            fontTaskNet(human,net,k,v)
        end
    end
    msgRet.taskList[0] = len
    config = OpenActExcel.mxIntegral
    len = #config 
    for i = 1,len do
        local net = msgRet.reachReward[i]
        fontReachNet(human,net,i,config[i])
    end
    msgRet.reachReward[0] = len
    for i = 1,7 do
        msgRet.redList[i] = isDayRed(human,i) and 1 or 0
    end
    msgRet.redList[0] = 7

    Msg.send(msgRet,human.fd)
end

-- 领取任务奖励
function getTaskReward(human,day,id)
    -- 开服超过7天 活动已结束
    -- if not isOpen(human) then
    --     return
    -- end

    -- -- 日期传入错误
    -- if not day or day > 7 or day <= 0 then
    --     return
    -- end

    -- -- 任务校验错误
    -- local config = OpenActExcel.mxTask[id]
    -- if not config or config.days ~= day then
    --     return
    -- end

    -- -- 任务状态未完成
    -- local state = getTaskState(human,id)
    -- if state ~= 1 then
    --     return
    -- end

    -- -- 设置状态
    -- setTaskState(human,id,2)

    -- -- 获得积分
    -- addJifen(human,1)

    -- -- 发奖励
    -- BagLogic.addItemList(human,config.item,"mengxin_opact")

	-- for k, v in pairs(funcID) do
	--     YunYingLogic.updateIcon(YYInfo[k], human)
	--     YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3605)
    --     break
    -- end
    -- query(human,day)

    --------------------------新改为一键领取所有能领取的奖励-----------------------------
    -- 开服超过7天 活动已结束
    if not isOpen(human) then
        return
    end

    -- 日期传入错误
    if not day or day > 7 or day <= 0 then
        return
    end

    local len = 0
    local awardList = {}

    for taskId, cfg in pairs(OpenActExcel.mxTask) do
        if cfg.days == day and getTaskState(human, taskId) == 1 then
            addJifen(human,1)
            setTaskState(human,taskId,2)

            for _, itemInfo in ipairs(cfg.item) do
                len = len + 1
                awardList[len] = {itemInfo[1], itemInfo[2]}
            end
        end
    end

    if len > 0 then
        BagLogic.addItemList(human,awardList,"mengxin_opact")

        for k, v in pairs(funcID) do
            YunYingLogic.updateIcon(YYInfo[k], human)
            YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3605)
            break
        end
        query(human,day)
    end
end

function addJifen(human,jifen)
    -- 开服超过7天 活动已结束
    if not isOpen(human) then
        return
    end

    initDB(human)

    local oldJifen = human.db.mengxin.jifen

    local newJifen = oldJifen + jifen

    human.db.mengxin.jifen = newJifen

    local config = OpenActExcel.mxIntegral
    for i = 1,#config do
        if config[i].need > oldJifen and config[i].need <= newJifen then
            setReachState(human,i,1)
        end
    end
end

function onCallBack(human,type,cnt)
    -- 开服超过7天 活动已结束
    if not isOpen(human) then
        return
    end

    initDB(human)

    local flag = OpenActExcel.mxTask[1].paramType[type]
    if flag == 1 then
        human.db.mengxin.taskType[type] = human.db.mengxin.taskType[type] or 0 
        human.db.mengxin.taskType[type] = human.db.mengxin.taskType[type] + cnt 
    else
        human.db.mengxin.taskType[type] = cnt 
    end

    local config = OpenActExcel.mxTask
    local len = #config
    local hasRed = nil
    for i = 1,len do
        if config[i].type == type then
            if human.db.mengxin.taskType[type] >= config[i].need then
                local state = getTaskState(human,i)
                if state ~= 2 then
                    setTaskState(human,i,1)
                    hasRed = true
                end
            end
        end
    end
    if hasRed then 
	    for k, v in pairs(funcID) do
	        YunYingLogic.updateIcon(YYInfo[k], human)
	        YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3605)
            break
        end
    end
end


-- 领取达标奖励奖励
function getReachReward(human,day,id)
    -- 开服超过7天 活动已结束
    if not isOpen(human) then
        return
    end

    -- 任务校验错误
    local config = OpenActExcel.mxIntegral[id]
    if not config then
        return
    end

    -- 任务状态未完成
    local state = getReachState(human,id)
    if state ~= 1 then
        return
    end

    -- 设置状态
    setReachState(human,id,2)
    
    -- 发奖励
    BagLogic.addItemList(human,config.item,"mengxin_opact")
	for k, v in pairs(funcID) do
	    YunYingLogic.updateIcon(YYInfo[k], human)
	    YunYingLogic.sendGroupUpdate(YYInfo[k], human, PanelDefine.PANEL_ID_3605)
        break
    end
    query(human,day)
end

function isRed(human)
    if not isOpen(human) then
        return
    end

    for i = 1,7 do
        if isDayRed(human,i) then
            return true
        end
    end

    local config = OpenActExcel.mxIntegral
    for i = 1,#config do
        local state = getReachState(human,i)
        if state == 1 then
            return true
        end
    end
end