local AbsActExcel = require("excel.absAct")
local Lang = require("common.Lang")
local Util = require("common.Util")
local Msg = require("core.Msg")
local Broadcast = require("broadcast.Broadcast")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local ItemDefine = require("bag.ItemDefine")
local BuyLogic = require("topup.BuyLogic")
local AbsActDefine = require("absAct.AbsActDefine")
local AbsActLogic = require("absAct.AbsActLogic")
local YunYingLogic = require("yunying.YunYingLogic")
local EquipLogic = require("equip.EquipLogic")
local PanelDefine = require("broadcast.PanelDefine")

MANGHE_ONE_NEED = 1 
MANGHE_TEN_NEED = 10

MANGHE_MR_1 = 1  -- 每日登陆奖励
MANGHE_MR_2 = 2  -- 每日活跃度奖励
MANGHE_MR_3 = 3  -- 每日充值奖励

MANGHE_MR_STATUS_1 = 1 --可领取
MANGHE_MR_STATUS_2 = 2 --已领取

MANGHE_RARE_MAX = nil   -- 权重和
MANGHE_RARE_MUM = nil   -- 保底权重和

local MANGHE_ABS_ID = 2001

local function initMrDb(human, id, mrId)
   local absAct = human.db.absAct[id]
   if not absAct then return end

   local manheMrConfig = AbsActExcel.mangHeMr[mrId]
   if not manheMrConfig then return end

   absAct.mrReward = absAct.mrReward or {}
   absAct.mrReward[mrId] = absAct.mrReward[mrId] or {}
   absAct.mrReward[mrId].status = absAct.mrReward[mrId].status or 0
   absAct.mrReward[mrId].cur = absAct.mrReward[mrId].cur or 0
end



function refreshRare()
    if MANGHE_RARE_MAX then return end 
    for _, v in ipairs(AbsActExcel.mangHe) do
        MANGHE_RARE_MAX = MANGHE_RARE_MAX or 0
        MANGHE_RARE_MAX = MANGHE_RARE_MAX + v.rare    
        if v.mum ~= 0 then
            MANGHE_RARE_MUM = MANGHE_RARE_MUM or 0
            MANGHE_RARE_MUM = MANGHE_RARE_MUM + v.rare    
        end
    end
end

-- 封装 礼包
function fontGift(human, id , net)
    local config = AbsActExcel.mangHeGift[1]
    net.id = 1
    for i = 1, #config.reward do
        Grid.makeItem(net.item[i], config.reward[i][1], config.reward[i][2])
    end
    net.item[0] = #config.reward
    net.name = config.name or ""
    net.cnt = human.db.absAct[id].buyCnt and human.db.absAct[id].buyCnt or 0
    net.maxCnt = config.cnt
    BuyLogic.fontBuyItem(human, net.buyMsg[1], config.buyID)
    net.buyMsg[0]=1
    net.needItem[0]=0
    net.icon = 0
end

-- 封装成就
function fontCj(human, id, net)
    local getID =  human.db.absAct[id].getID and  human.db.absAct[id].getID or 0
    local nextID = getID + 1 
    nextID = AbsActExcel.mangHeCj[nextID] and nextID or getID
    local config = AbsActExcel.mangHeCj[nextID]
    net.cjNow = human.db.absAct[id].drawCnt and human.db.absAct[id].drawCnt or 0
    net.cjMax = config.need
    net.cjGet = getID
    net.cjItemID = nextID
    Grid.makeItem(net.cjItem, config.item[1], config.item[2])
end


-- 封装每日奖励
function fontMr(human, id, mrId, net, actId)
    local manheMrConfig = AbsActExcel.mangHeMr[mrId]
    local absAct = human.db.absAct[id]
    net.id = mrId
    net.desc = manheMrConfig.desc
    net.status = absAct.mrReward and absAct.mrReward[mrId] and absAct.mrReward[mrId].status or 0
    net.cur = absAct.mrReward and absAct.mrReward[mrId] and absAct.mrReward[mrId].cur or 0
    net.max = 1
    if MANGHE_MR_2 == mrId then
       net.max = 100
    end

    if mrId == MANGHE_MR_1 and net.status == 0 then
        -- 每日登陆 奖励必完成  ( 存在极小概率  玩家在0点 login updateDaliy 快于 yunyingLogic 的活动更换  导致每日登陆标记失败)
        mrActive(human, mrId, id)
        net.status = MANGHE_MR_STATUS_1
    end
    if net.cur >= net.max then
        net.cur = net.max
    end
    Grid.makeItem(net.item, manheMrConfig.item[actId][1], manheMrConfig.item[actId][2])
end

-- 查询
function query(human, id)
    local state, endTime, starTime = AbsActLogic.isStarted(human, id)
    if not state then return end
    
	local absActConfig = AbsActExcel.absActivity[id]
    local absAct = human.db.absAct[id]
    local bdCnt = absAct.bdCnt or 0
    local msgRet = Msg.gc.GC_ABS_ACT_MANGHE_QUERY
    msgRet.startTime = starTime
    msgRet.endTime  = endTime
	msgRet.bdCnt = 30 - bdCnt
    msgRet.templateId = absActConfig.adIcon
    fontCj(human, id, msgRet)
    fontGift(human, id, msgRet.gift)   
    Grid.makeItem(msgRet.oneNeed, absActConfig.param[1],  absActConfig.param[2])
    Grid.makeItem(msgRet.tenNeed, absActConfig.param[1],  absActConfig.param[2] * MANGHE_TEN_NEED)
    
    fontMr(human, id, MANGHE_MR_1, msgRet.mrReward[MANGHE_MR_1], id)
    fontMr(human, id, MANGHE_MR_2, msgRet.mrReward[MANGHE_MR_2], id)
    fontMr(human, id, MANGHE_MR_3, msgRet.mrReward[MANGHE_MR_3], id)
    msgRet.mrReward[0] = MANGHE_MR_3
    msgRet.qiPao = absAct.qiPao or 1
    absAct.qiPao = 2
    
    Msg.send(msgRet, human.fd)
end

-- 随机一个道具
function random(isLast)
    if not isLast then
        local random = math.random(1, MANGHE_RARE_MAX)
        for k, v in ipairs(AbsActExcel.mangHe) do
            if random <= v.rare then
                return v
            else
                random = random - v.rare
            end
        end
    else
        local random = math.random(1, MANGHE_RARE_MUM)
        for k, v in ipairs(AbsActExcel.mangHe) do
            if v.mum ~= 0 then
                if random <= v.rare then
                    return v
                else
                    random = random - v.rare
                end
            end
        end
    end
end

function addCj(human, id, cnt)
    human.db.absAct[id].drawCnt =  human.db.absAct[id].drawCnt or 0
    human.db.absAct[id].drawCnt =  human.db.absAct[id].drawCnt + cnt
end

-- 抽奖
function draw(human, cnt)
    local state,id = AbsActLogic.isStartedByType(human,  AbsActDefine.ABS_ACT_TYPE_2)
    if not state then return end
    if not cnt or (cnt ~= 1 and cnt ~= 10) then
        return
    end

    local absAct = human.db.absAct[id]
    if not absAct then return end

    absAct.bdCnt = absAct.bdCnt or 0

    local absActConfig = AbsActExcel.absActivity[id]
    if not absActConfig then return end

    refreshRare()
    AbsActLogic.checkAbsActClean(human, id)

    -- 检查道具是否足够
    local needCnt = cnt * absActConfig.param[2]
    if needCnt > BagLogic.getItemCnt(human, absActConfig.param[1]) then
        return Broadcast.sendErr(human, Util.format(Lang.COMMON_NO_ITEM, ItemDefine.getValue(ItemDefine.ITEM_MANGHE_ID, "name"))) 
    end
    BagLogic.delItem(human, absActConfig.param[1], needCnt, "abs_manghe")

    local getList = {}
	local isLast = nil
    for i = 1, cnt do
	    isLast = nil
        absAct.bdCnt = absAct.bdCnt + 1
        if absAct.bdCnt == 30 then
            isLast = true
            absAct.bdCnt = 0
        end
        getList[#getList + 1] = random(isLast)
    end    
    addCj(human, id, cnt)
    
    local msgRet = Msg.gc.GC_ABS_ACT_MANGHE_DO 
    local len = 0
    for i = 1, #getList do
        local config = getList[i]
        BagLogic.addItem(human, config.item[1], config.item[2], "abs_manghe",  nil, config.item[3])
        if not ItemDefine.isEquip(config.item[1]) then
            len = len + 1
            Grid.makeItem(msgRet.list[len], config.item[1] , config.item[2])
        end
    end

    msgRet.list[0] = len
    msgRet.list[0] = EquipLogic.makeEquipItem(human, msgRet.list,  msgRet.list[0])
    YunYingLogic.updateIcon(YYInfo[id], human)
    YunYingLogic.sendGroupUpdate(YYInfo[id], human, PanelDefine.PANEL_ID_3702)
    Msg.send(msgRet, human.fd)
    query(human, id)
end

-- 概率查询
function queryRare(human)
    local msgRet = Msg.gc.GC_ABS_ACT_MANGHE_RARE_QUERY
    refreshRare()
    msgRet.isStart = 0
    msgRet.isEnd = 0
    local len = 0
    for k, config in ipairs(AbsActExcel.mangHe) do
        if config.show == 1 then
           if len <= 0 then
              msgRet.isStart = 1  
           end

           len = len + 1
           local net = msgRet.list[len]
           net.id = k
           net.rare = math.floor(config.rare / MANGHE_RARE_MAX * 10000)
           net.rare = net.rare > 0 and net.rare or 1
           Grid.makeItem(net.item, config.item[1], config.item[2], nil, nil, nil, nil, config.item[3]) 
           if len >= 30 then
               msgRet.list[0] = len
               Msg.send(msgRet, human.fd)
               len = 0
               msgRet.isStart = 0
           end
        end
    end
    msgRet.list[0] = len
    msgRet.isEnd = 1
    Msg.send(msgRet, human.fd)
end

MANGHE_CJ_STATE = nil
-- 成就查询
function queryCj(human)
    local state,id = AbsActLogic.isStartedByType(human,  AbsActDefine.ABS_ACT_TYPE_2)
    if not state then return end
    local msgRet = Msg.gc.GC_ABS_ACT_MANGHE_CJ_QUERY
    if not MANGHE_CJ_STATE then
        for k, config in ipairs(AbsActExcel.mangHeCj) do
            local net = msgRet.list[k]
            net.id = k
            net.need = config.need 
            Grid.makeItem(net.item, config.item[1], config.item[2])
        end
        msgRet.list[0] = #AbsActExcel.mangHeCj
        msgRet.cjMax = AbsActExcel.mangHeCj[#AbsActExcel.mangHeCj].need
    end
    msgRet.now =human.db.absAct[id].drawCnt and human.db.absAct[id].drawCnt or 0
    Msg.send(msgRet, human.fd)
end

-- 成就 领取（一键领取所有可领取的成就奖励）
function cjGet(human)
    local state,id = AbsActLogic.isStartedByType(human,  AbsActDefine.ABS_ACT_TYPE_2)
    if not state then return end
    
    local absAct = human.db.absAct[id]
    if not absAct then return end
    
    local getID = absAct.getID and absAct.getID or 0
    local now = absAct.drawCnt and absAct.drawCnt or 0
    
    -- 清空临时列表
    BagLogic.cleanMomentItemList()
    
    local hasReward = false
    local lastGetID = getID
    
    -- 遍历所有成就配置，从下一个未领取的成就开始
    for i = getID + 1, #AbsActExcel.mangHeCj do
        local config = AbsActExcel.mangHeCj[i]
        if not config then break end
        
        -- 检查是否达到领取条件
        if now >= config.need then
            -- 合并奖励到临时列表
            BagLogic.updateMomentItem(BagLogic.ADDITEM_TYPE_1, config.item[1], config.item[2])
            lastGetID = i
            hasReward = true
        else
            -- 如果当前成就未达到条件，后续成就也不会达到（因为need是递增的）
            break
        end
    end
    
    -- 如果有奖励，一次性添加所有奖励并更新getID
    if hasReward then
        absAct.getID = lastGetID
        BagLogic.addMomentItemList(human, "abs_manghe")
        YunYingLogic.sendBanner(human)
    end
    
    query(human, id)
    YunYingLogic.updateIcon(YYInfo[id], human)
    YunYingLogic.sendGroupUpdate(YYInfo[id], human, PanelDefine.PANEL_ID_3702)
end

-- 每日奖励 领取
function mrGet(human, mrId)
    local state,id = AbsActLogic.isStartedByType(human,  AbsActDefine.ABS_ACT_TYPE_2)
    if not state then return end

    local absConfig = AbsActExcel.absActivity[id]
    if not absConfig then return end
    if absConfig.actId == 0 then return end

    local absAct = human.db.absAct[id]
    if not absAct then return end

    -- 忽略前端参数，固定领取 1、2、3 三个活动的奖励
    local mrIdList = {MANGHE_MR_1, MANGHE_MR_2, MANGHE_MR_3}

    absAct.mrReward = absAct.mrReward or {}
    BagLogic.cleanMomentItemList()
    
    local hasReward = false
    -- 遍历所有需要领取的 mrId
    for _, checkMrId in ipairs(mrIdList) do
        local manheMrConfig = AbsActExcel.mangHeMr[checkMrId]
        if manheMrConfig then
            absAct.mrReward[checkMrId] = absAct.mrReward[checkMrId] or {}
            absAct.mrReward[checkMrId].status = absAct.mrReward[checkMrId].status or 0
            
            -- 检查是否可领取
            if absAct.mrReward[checkMrId].status == MANGHE_MR_STATUS_1 then
                -- 更新状态为已领取
                absAct.mrReward[checkMrId].status = MANGHE_MR_STATUS_2
                
                -- 合并奖励到临时列表
                BagLogic.updateMomentItem(BagLogic.ADDITEM_TYPE_1, manheMrConfig.item[absConfig.actId][1], manheMrConfig.item[absConfig.actId][2])
                hasReward = true
            end
        end
    end
    
    -- 如果有奖励，一次性添加所有奖励
    if hasReward then
        BagLogic.addMomentItemList(human, "abs_manghe")
        YunYingLogic.sendBanner(human)
    end
    
    query(human, id)
    YunYingLogic.updateIcon(YYInfo[id], human)
    YunYingLogic.sendGroupUpdate(YYInfo[id], human, PanelDefine.PANEL_ID_3702)
end

-- 盲盒礼包 购买
function mangHeGift(human, id, buyConf, isFirst, cnt, buyNum)
    local state = AbsActLogic.isStarted(human, id)
    if not state then return end
    
    AbsActLogic.checkAbsActClean(human, id)
    local config = AbsActExcel.mangHeGift[1]
    local buyCnt = human.db.absAct[id].buyCnt and human.db.absAct[id].buyCnt or 0
    -- if config.cnt <= buyCnt then
    --     return 
    -- end

    if buyCnt + buyNum > config.cnt  then
        return Broadcast.sendErr(human, Lang.COPY_BUY_CNT_ERR_CNT)
    end
    
    human.db.absAct[id].buyCnt = buyCnt + buyNum
    local tItemList = {}
    for index, v in ipairs(config.reward) do
        table.insert(tItemList, {v[1], v[2]*buyNum})
    end
    BagLogic.addItemList(human, tItemList, "abs_manghe")

    -- human.db.absAct[id].buyCnt = buyCnt + 1
    -- BagLogic.addItemList(human, config.reward, "abs_manghe")
    query(human, id)
end

-- 每日任务激活
function mrActive(human, mrId, id)
    local state = AbsActLogic.isStarted(human, id)
    if not state then return end
    local absAct = human.db.absAct[id]
    if not absAct then return end

    initMrDb(human, id, mrId)
   --MANGHE_MR_1 = 1  -- 每日登陆奖励
   --MANGHE_MR_2 = 2  -- 每日活跃度奖励
   --MANGHE_MR_3 = 3  -- 每日充值奖励

   if mrId == MANGHE_MR_1 or mrId == MANGHE_MR_3 then
      if absAct.mrReward[mrId].status == 0 then
         absAct.mrReward[mrId].status = MANGHE_MR_STATUS_1
         absAct.mrReward[mrId].cur = 1
      end
      return
   end
end


function updateDaily(human, id)
   local state = AbsActLogic.isStarted(human, id)
   if not state then return end

   AbsActLogic.checkAbsActClean(human, id)

   local absAct = human.db.absAct[id]
   if not absAct then return end
   absAct.mrReward = nil

   mrActive(human, MANGHE_MR_1, id)
end

function onDailyTask(human, id)
   local state = AbsActLogic.isStarted(human, id)
   if not state then return end

   AbsActLogic.checkAbsActClean(human, id)

   local absAct = human.db.absAct[id]
   if not absAct then return end

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

   initMrDb(human, id, MANGHE_MR_2)
   absAct.mrReward[MANGHE_MR_2].cur = nowHuoYue

   if nowHuoYue >= 100 then
      if absAct.mrReward[MANGHE_MR_2].status == 0 then
         absAct.mrReward[MANGHE_MR_2].status = MANGHE_MR_STATUS_1
         YunYingLogic.updateIcon(YYInfo[id], human)
         YunYingLogic.sendGroupUpdate(YYInfo[id], human, PanelDefine.PANEL_ID_3702)
      end
   end
end


function onLogin(human,funcID)
    -- 因为玩家在活动未开启前完成了活跃度任务，活动开启后没法完成活跃度任务,所以在玩家上线时,通过onDailyTask()做一次更新活跃度数据操作
    onDailyTask(human, funcID)

    -- 因为玩家在活动未开启前进行充值，活动开启后没法完成充值任务,所以在玩家上线时,通过onCharge()做一次更新活跃度数据操作
    local topupAcountDaily = human.db.topupAcountDaily
    if topupAcountDaily and topupAcountDaily > 0 then
        onCharge(human, topupAcountDaily, funcID)
    end
end


function onCharge(human, price, id)
   local state = AbsActLogic.isStarted(human, id)
   if not state then return end

   AbsActLogic.checkAbsActClean(human, id)
   mrActive(human, MANGHE_MR_3, id)
end


function isRed(human, YYInfo, funcConfig)
    local state = AbsActLogic.isStarted(human, funcConfig.funcID)
    if not state then return end

    local absAct = human.db.absAct[funcConfig.funcID]
    if not absAct then return end

    if absAct.mrReward then
       for k, v in pairs(absAct.mrReward) do
          if v.status == MANGHE_MR_STATUS_1 then
             return true
          end
       end
    end

    local getID =  absAct.getID or 0
    local config = AbsActExcel.mangHeCj[getID + 1]
    if not config then return end
    local now = absAct.drawCnt or 0
    if now >= config.need then 
        return true
    end
end

function isActive(human, YYInfo, funcConfig)
    return not isOpen(human, YYInfo, funcConfig)
end

function isOpen(human, YYInfo, funcConfig)
    return AbsActLogic.isStarted(human, funcConfig.funcID)
end

function GetRemainNum(human, nBuyID)
    local config = AbsActExcel.mangHeGift[1]
    if config.buyID ~= nBuyID then
        return 0
    end

    AbsActLogic.checkAbsActClean(human, MANGHE_ABS_ID)
    local buyCnt = human.db.absAct[MANGHE_ABS_ID].buyCnt and human.db.absAct[MANGHE_ABS_ID].buyCnt or 0
    return buyCnt < config.cnt and (config.cnt - buyCnt) or 0
end